edouardfoussier commited on
Commit
845a31e
·
0 Parent(s):

Switch Space to Gradio app with HF Inference API

Browse files
Files changed (2) hide show
  1. app.py +208 -0
  2. requirements.txt +5 -0
app.py ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import ast
3
+ import json
4
+ import threading
5
+ from typing import List, Dict, Any, Optional, Tuple
6
+
7
+ import gradio as gr
8
+ import numpy as np
9
+ from datasets import load_dataset
10
+ from huggingface_hub import InferenceClient
11
+
12
+ # ------------------
13
+ # Config
14
+ # ------------------
15
+ EMBED_COL = os.getenv("EMBED_COL", "embeddings_bge-m3")
16
+ DATASETS = [
17
+ ("edouardfoussier/travail-emploi-clean", "train"),
18
+ ("edouardfoussier/service-public-filtered", "train"),
19
+ ]
20
+
21
+ HF_EMBED_MODEL = os.getenv("HF_EMBEDDINGS_MODEL", "BAAI/bge-m3")
22
+ HF_API_TOKEN = os.getenv("HF_API_TOKEN", "") # set in Space → Settings → Variables
23
+
24
+ # Optional: limit rows per dataset to keep RAM in check while testing
25
+ MAX_ROWS = int(os.getenv("MAX_ROWS_PER_DATASET", "0")) # 0 = no limit
26
+
27
+ # Try FAISS; fall back to NumPy
28
+ _USE_FAISS = True
29
+ try:
30
+ import faiss # type: ignore
31
+ except Exception:
32
+ _USE_FAISS = False
33
+
34
+ # ------------------
35
+ # Embedding client
36
+ # ------------------
37
+ _embed_client: Optional[InferenceClient] = None
38
+ def _get_embed_client() -> InferenceClient:
39
+ global _embed_client
40
+ if _embed_client is None:
41
+ mid = HF_EMBED_MODEL.strip()
42
+
43
+ # Auto-fix very common bad value like "sentence-transformers/BAAI/bge-m3"
44
+ if mid.lower().startswith("sentence-transformers/baai/"):
45
+ mid = mid.split("/", 1)[1] # -> "BAAI/bge-m3"
46
+
47
+ if mid.count("/") != 1:
48
+ raise ValueError(
49
+ f"HF_EMBEDDINGS_MODEL must be 'owner/name', got '{mid}'. "
50
+ "Examples: 'BAAI/bge-m3', 'sentence-transformers/all-MiniLM-L6-v2'."
51
+ )
52
+ if not HF_API_TOKEN:
53
+ raise RuntimeError(
54
+ "HF_API_TOKEN is not set. Go to Space → Settings → Variables and add HF_API_TOKEN (a WRITE token)."
55
+ )
56
+ _embed_client = InferenceClient(model=mid, token=HF_API_TOKEN, repo_type="model")
57
+ return _embed_client
58
+
59
+ # ------------------
60
+ # Vector helpers
61
+ # ------------------
62
+ def _to_vec(x):
63
+ if isinstance(x, list):
64
+ return np.asarray(x, dtype=np.float32)
65
+ if isinstance(x, str):
66
+ return np.asarray(ast.literal_eval(x), dtype=np.float32)
67
+ raise TypeError(f"Unsupported embedding type: {type(x)}")
68
+
69
+ def _normalize(v: np.ndarray) -> np.ndarray:
70
+ v = v.astype(np.float32, copy=False)
71
+ n = np.linalg.norm(v) + 1e-12
72
+ return v / n
73
+
74
+ def _embed_query(text: str) -> np.ndarray:
75
+ vec = _get_embed_client().feature_extraction(text)
76
+ v = np.asarray(vec, dtype=np.float32)
77
+ if v.ndim == 2:
78
+ v = v[0]
79
+ return _normalize(v)
80
+
81
+ # ------------------
82
+ # Index storage
83
+ # ------------------
84
+ _index = None # faiss index or raw matrix (np.ndarray)
85
+ _payloads: List[Dict[str, Any]] = []
86
+ _dim = None
87
+ _lock = threading.Lock()
88
+
89
+ def _load_datasets() -> Tuple[np.ndarray, List[Dict[str, Any]]]:
90
+ vecs, payloads = [], []
91
+ for name, split in DATASETS:
92
+ ds = load_dataset(name, split=split)
93
+ if MAX_ROWS > 0:
94
+ ds = ds.select(range(min(MAX_ROWS, len(ds))))
95
+ for row in ds:
96
+ v = _normalize(_to_vec(row[EMBED_COL]))
97
+ vecs.append(v)
98
+ p = dict(row)
99
+ p.pop(EMBED_COL, None)
100
+ payloads.append(p)
101
+ X = np.stack(vecs, axis=0) if vecs else np.zeros((0, 1), dtype=np.float32)
102
+ return X, payloads
103
+
104
+ def _build_index() -> Tuple[Any, List[Dict[str, Any]], int]:
105
+ X, payloads = _load_datasets()
106
+ if X.size == 0:
107
+ return (np.zeros((0, 1), dtype=np.float32), payloads, 1)
108
+ dim = X.shape[1]
109
+ if _USE_FAISS:
110
+ idx = faiss.IndexFlatIP(dim)
111
+ idx.add(X)
112
+ else:
113
+ idx = X # NumPy fallback
114
+ return idx, payloads, dim
115
+
116
+ def _ensure_index_loaded():
117
+ global _index, _payloads, _dim
118
+ if _index is not None:
119
+ return
120
+ with _lock:
121
+ if _index is not None:
122
+ return
123
+ idx, pls, d = _build_index()
124
+ _index, _payloads, _dim = idx, pls, d
125
+
126
+ def _search_ip_numpy(X: np.ndarray, q: np.ndarray, k: int):
127
+ # Both normalized => inner product = cosine similarity
128
+ scores = X @ q
129
+ k = min(k, len(scores))
130
+ part = np.argpartition(-scores, k - 1)[:k]
131
+ order = part[np.argsort(-scores[part])]
132
+ return scores[order], order
133
+
134
+ def _search(query: str, k: int, source_filter: Optional[str]) -> List[Dict[str, Any]]:
135
+ _ensure_index_loaded()
136
+ if _dim is None or (_USE_FAISS and _index.ntotal == 0) or (not _USE_FAISS and _index.shape[0] == 0):
137
+ return []
138
+ q = _embed_query(query)
139
+ if _USE_FAISS:
140
+ D, I = _index.search(q[None, :], k)
141
+ scores, idxs = D[0], I[0]
142
+ else:
143
+ scores, idxs = _search_ip_numpy(_index, q, k)
144
+ out = []
145
+ for idx, sc in zip(idxs, scores):
146
+ if int(idx) < 0:
147
+ continue
148
+ pl = _payloads[int(idx)]
149
+ if source_filter and pl.get("source") != source_filter:
150
+ continue
151
+ out.append({
152
+ "id": str(int(idx)),
153
+ "score": float(sc),
154
+ "title": (pl.get("title") or "").strip() or "(Sans titre)",
155
+ "url": pl.get("url") or "",
156
+ "source": pl.get("source") or "",
157
+ "snippet": (pl.get("text") or pl.get("chunk_text") or "")[:500]
158
+ })
159
+ return out
160
+
161
+ # ------------------
162
+ # Gradio UI
163
+ # ------------------
164
+ def do_search(query, source, top_k):
165
+ try:
166
+ if not query or not query.strip():
167
+ return gr.update(value="<i>Entrez une question…</i>", visible=True)
168
+ src_filter = None if (not source or source == "(Tous)") else source
169
+ hits = _search(query.strip(), int(top_k), src_filter)
170
+ if not hits:
171
+ return gr.update(value="<b>0 résultat</b>", visible=True)
172
+
173
+ lines = [f"<b>Top {len(hits)} résultats</b><br>"]
174
+ for i, h in enumerate(hits, 1):
175
+ badge = {
176
+ "travail-emploi": '<span style="background:#2563eb;color:white;padding:2px 6px;border-radius:999px;font-size:12px">travail-emploi</span>',
177
+ "service-public": '<span style="background:#059669;color:white;padding:2px 6px;border-radius:999px;font-size:12px">service-public</span>',
178
+ }.get(h["source"].lower(), f'<span style="background:#6b7280;color:white;padding:2px 6px;border-radius:999px;font-size:12px">{h["source"] or "unknown"}</span>')
179
+ title = h["title"]
180
+ url = h["url"]
181
+ score = f"{h['score']:.3f}"
182
+ head = f"#{i} {badge} "
183
+ head += f'<a href="{url}" target="_blank">{title}</a>' if url else title
184
+ lines.append(f"{head} &nbsp;&nbsp; <code>cos={score}</code><br>")
185
+ if h["snippet"]:
186
+ lines.append(f"<div style='margin-left:1rem;color:#444'>{h['snippet']}</div><br>")
187
+ return gr.update(value="\n".join(lines), visible=True)
188
+ except Exception as e:
189
+ return gr.update(value=f"<b>Erreur:</b> {e}", visible=True)
190
+
191
+ with gr.Blocks(title="RAG-RH (Gradio)") as demo:
192
+ gr.Markdown("## 🔎 Assistant RH — RAG Demo (Gradio)")
193
+ with gr.Row():
194
+ query = gr.Textbox(label="Votre question", placeholder="Posez votre question…", scale=3)
195
+ run = gr.Button("Rechercher", variant="primary", scale=1)
196
+ with gr.Row():
197
+ source = gr.Dropdown(choices=["(Tous)", "travail-emploi", "service-public"],
198
+ value="(Tous)", label="Filtre", scale=1)
199
+ topk = gr.Slider(3, 30, value=8, step=1, label="Top-K", scale=2)
200
+
201
+ out = gr.HTML(visible=False)
202
+
203
+ run.click(do_search, inputs=[query, source, topk], outputs=out)
204
+ query.submit(do_search, inputs=[query, source, topk], outputs=out)
205
+
206
+ if __name__ == "__main__":
207
+ # For local testing: `python app.py`
208
+ demo.launch(server_name="0.0.0.0", server_port=7860)
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ gradio>=5.40
2
+ datasets>=2.19.0
3
+ huggingface-hub>=0.19
4
+ faiss-cpu==1.7.4
5
+ numpy<2