Spaces:
Runtime error
Runtime error
Update main.py
Browse files
main.py
CHANGED
|
@@ -139,24 +139,86 @@ def _set_stage(st: JobState, stage: str):
|
|
| 139 |
# =============================================================================
|
| 140 |
# UTILS
|
| 141 |
# =============================================================================
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 154 |
if chunk:
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 160 |
|
| 161 |
def _l2_normalize(x: np.ndarray) -> np.ndarray:
|
| 162 |
n = np.linalg.norm(x, axis=1, keepdims=True) + 1e-12
|
|
@@ -289,16 +351,34 @@ def _do_index_job(st: JobState, files: List[Dict[str, str]], chunk_size: int, ov
|
|
| 289 |
_set_stage(st, "chunking")
|
| 290 |
rows: List[Dict[str, Any]] = []
|
| 291 |
st.total_files = len(files)
|
|
|
|
| 292 |
for it in files:
|
| 293 |
path = (it.get("path") or "unknown").strip()
|
| 294 |
txt = it.get("text") or ""
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 299 |
st.total_chunks = len(rows)
|
| 300 |
_add_msg(st, f"Total chunks = {st.total_chunks}")
|
| 301 |
|
|
|
|
| 302 |
# 2) Embedding
|
| 303 |
_set_stage(st, "embedding")
|
| 304 |
texts = [r["text"] for r in rows]
|
|
@@ -424,6 +504,9 @@ class SearchRequest(BaseModel):
|
|
| 424 |
project_id: str
|
| 425 |
query: str
|
| 426 |
k: int = 5
|
|
|
|
|
|
|
|
|
|
| 427 |
|
| 428 |
@fastapi_app.post("/search")
|
| 429 |
def search(req: SearchRequest):
|
|
@@ -455,13 +538,66 @@ def search(req: SearchRequest):
|
|
| 455 |
ids = ids[0].tolist()
|
| 456 |
scores = scores[0].tolist()
|
| 457 |
|
| 458 |
-
|
|
|
|
|
|
|
| 459 |
for idx, sc in zip(ids, scores):
|
| 460 |
if idx < 0 or idx >= len(rows):
|
| 461 |
continue
|
| 462 |
r = rows[idx]
|
| 463 |
-
|
| 464 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 465 |
|
| 466 |
# ----------- ARTIFACTS EXPORT -----------
|
| 467 |
@fastapi_app.get("/artifacts/{project_id}/dataset")
|
|
|
|
| 139 |
# =============================================================================
|
| 140 |
# UTILS
|
| 141 |
# =============================================================================
|
| 142 |
+
import re
|
| 143 |
+
|
| 144 |
+
_RE_CODE_BOUNDARY = re.compile(
|
| 145 |
+
r"""^\s*(export\s+)?(default\s+)?(async\s+)?(function|class|const|let|var)\b|^\s*interface\b|^\s*type\b""",
|
| 146 |
+
re.IGNORECASE,
|
| 147 |
+
)
|
| 148 |
+
|
| 149 |
+
def _infer_kind(path: str) -> str:
|
| 150 |
+
p = (path or "").lower().replace("\\", "/")
|
| 151 |
+
if "/hooks/" in p or p.endswith("hook.ts") or p.startswith("use"):
|
| 152 |
+
return "hook"
|
| 153 |
+
if "/components/" in p:
|
| 154 |
+
return "component"
|
| 155 |
+
if "/pages/" in p or "/routes/" in p:
|
| 156 |
+
return "page"
|
| 157 |
+
if "/api/" in p:
|
| 158 |
+
return "api"
|
| 159 |
+
if p.endswith((".test.ts", ".test.tsx", ".spec.ts", ".spec.tsx", ".test.js", ".spec.js")):
|
| 160 |
+
return "test"
|
| 161 |
+
return "file"
|
| 162 |
+
|
| 163 |
+
def _make_chunk_header(path: str, kind: str, start_line: int, end_line: int) -> str:
|
| 164 |
+
ext = os.path.splitext(path)[1].lstrip(".").lower()
|
| 165 |
+
return (
|
| 166 |
+
f"FILE: {path}\n"
|
| 167 |
+
f"LANG: {ext or 'text'}\n"
|
| 168 |
+
f"KIND: {kind}\n"
|
| 169 |
+
f"LINES: {start_line}-{end_line}\n"
|
| 170 |
+
)
|
| 171 |
+
|
| 172 |
+
def _chunk_text_codeaware(text: str, size: int = 1200, overlap: int = 150) -> List[Dict[str, Any]]:
|
| 173 |
+
"""
|
| 174 |
+
Chunking par lignes (plus stable que caractère par caractère) + frontières de code.
|
| 175 |
+
Retour: liste de {start_line,end_line,text}.
|
| 176 |
+
size/overlap en caractères approximatifs sur le chunk rendu.
|
| 177 |
+
"""
|
| 178 |
+
text = (text or "").replace("\r\n", "\n").replace("\r", "\n")
|
| 179 |
+
lines = text.split("\n")
|
| 180 |
+
out: List[Dict[str, Any]] = []
|
| 181 |
+
|
| 182 |
+
buf: List[str] = []
|
| 183 |
+
buf_len = 0
|
| 184 |
+
start_line = 1
|
| 185 |
+
|
| 186 |
+
def flush(end_line: int):
|
| 187 |
+
nonlocal buf, buf_len, start_line
|
| 188 |
+
chunk = "\n".join(buf).strip()
|
| 189 |
if chunk:
|
| 190 |
+
out.append({"start_line": start_line, "end_line": end_line, "text": chunk})
|
| 191 |
+
buf = []
|
| 192 |
+
buf_len = 0
|
| 193 |
+
start_line = end_line + 1
|
| 194 |
+
|
| 195 |
+
for i, line in enumerate(lines, start=1):
|
| 196 |
+
# frontière “naturelle” de code : on force une coupure si le buffer est déjà gros
|
| 197 |
+
if buf and buf_len >= size and _RE_CODE_BOUNDARY.match(line):
|
| 198 |
+
flush(i - 1)
|
| 199 |
+
|
| 200 |
+
buf.append(line)
|
| 201 |
+
buf_len += len(line) + 1
|
| 202 |
+
|
| 203 |
+
if buf_len >= size:
|
| 204 |
+
flush(i)
|
| 205 |
+
|
| 206 |
+
if buf:
|
| 207 |
+
flush(len(lines))
|
| 208 |
+
|
| 209 |
+
# Overlap: ré-injecte la fin du chunk précédent au début du suivant (approx chars)
|
| 210 |
+
if overlap > 0 and len(out) >= 2:
|
| 211 |
+
new_out = [out[0]]
|
| 212 |
+
for prev, cur in zip(out, out[1:]):
|
| 213 |
+
tail = prev["text"][-overlap:]
|
| 214 |
+
cur2 = dict(cur)
|
| 215 |
+
cur2["text"] = (tail + "\n" + cur["text"]).strip()
|
| 216 |
+
cur2["start_line"] = max(1, cur["start_line"] - 1) # indicatif
|
| 217 |
+
new_out.append(cur2)
|
| 218 |
+
out = new_out
|
| 219 |
+
|
| 220 |
+
return out
|
| 221 |
+
|
| 222 |
|
| 223 |
def _l2_normalize(x: np.ndarray) -> np.ndarray:
|
| 224 |
n = np.linalg.norm(x, axis=1, keepdims=True) + 1e-12
|
|
|
|
| 351 |
_set_stage(st, "chunking")
|
| 352 |
rows: List[Dict[str, Any]] = []
|
| 353 |
st.total_files = len(files)
|
| 354 |
+
|
| 355 |
for it in files:
|
| 356 |
path = (it.get("path") or "unknown").strip()
|
| 357 |
txt = it.get("text") or ""
|
| 358 |
+
|
| 359 |
+
kind = _infer_kind(path)
|
| 360 |
+
chunks = _chunk_text_codeaware(txt, size=int(chunk_size), overlap=int(overlap))
|
| 361 |
+
|
| 362 |
+
_add_msg(st, f"{path}: len(text)={len(txt)} chunks={len(chunks)}")
|
| 363 |
+
|
| 364 |
+
for ci, ck in enumerate(chunks):
|
| 365 |
+
header = _make_chunk_header(path, kind, ck["start_line"], ck["end_line"])
|
| 366 |
+
# On concatène header + chunk (↑ signal sémantique, sans boost “ridicule”)
|
| 367 |
+
merged = header + "\n" + ck["text"]
|
| 368 |
+
|
| 369 |
+
rows.append({
|
| 370 |
+
"path": path,
|
| 371 |
+
"text": merged if store_text else "", # store_text respecté
|
| 372 |
+
"chunk_id": ci,
|
| 373 |
+
"kind": kind,
|
| 374 |
+
"start_line": int(ck["start_line"]),
|
| 375 |
+
"end_line": int(ck["end_line"]),
|
| 376 |
+
})
|
| 377 |
+
|
| 378 |
st.total_chunks = len(rows)
|
| 379 |
_add_msg(st, f"Total chunks = {st.total_chunks}")
|
| 380 |
|
| 381 |
+
|
| 382 |
# 2) Embedding
|
| 383 |
_set_stage(st, "embedding")
|
| 384 |
texts = [r["text"] for r in rows]
|
|
|
|
| 504 |
project_id: str
|
| 505 |
query: str
|
| 506 |
k: int = 5
|
| 507 |
+
group_by_file: bool = True
|
| 508 |
+
fetch_k: int = 50 # nb de chunks à récupérer avant agrégation
|
| 509 |
+
|
| 510 |
|
| 511 |
@fastapi_app.post("/search")
|
| 512 |
def search(req: SearchRequest):
|
|
|
|
| 538 |
ids = ids[0].tolist()
|
| 539 |
scores = scores[0].tolist()
|
| 540 |
|
| 541 |
+
|
| 542 |
+
|
| 543 |
+
raw = []
|
| 544 |
for idx, sc in zip(ids, scores):
|
| 545 |
if idx < 0 or idx >= len(rows):
|
| 546 |
continue
|
| 547 |
r = rows[idx]
|
| 548 |
+
raw.append({
|
| 549 |
+
"path": r.get("path"),
|
| 550 |
+
"text": r.get("text"),
|
| 551 |
+
"score": float(sc),
|
| 552 |
+
"chunk_id": r.get("chunk_id"),
|
| 553 |
+
"kind": r.get("kind"),
|
| 554 |
+
"start_line": r.get("start_line"),
|
| 555 |
+
"end_line": r.get("end_line"),
|
| 556 |
+
})
|
| 557 |
+
|
| 558 |
+
if not req.group_by_file:
|
| 559 |
+
return {"results": raw[: int(req.k)]}
|
| 560 |
+
|
| 561 |
+
# Agrégation par fichier : score = max + 0.15 * moyenne des 3 meilleurs chunks
|
| 562 |
+
from collections import defaultdict
|
| 563 |
+
|
| 564 |
+
by_path = defaultdict(list)
|
| 565 |
+
for hit in raw:
|
| 566 |
+
if hit.get("path"):
|
| 567 |
+
by_path[hit["path"]].append(hit)
|
| 568 |
+
|
| 569 |
+
file_results = []
|
| 570 |
+
for path, hits in by_path.items():
|
| 571 |
+
hits.sort(key=lambda x: x["score"], reverse=True)
|
| 572 |
+
top = hits[:3]
|
| 573 |
+
best = hits[0]
|
| 574 |
+
file_score = best["score"] + 0.15 * (sum(h["score"] for h in top) / max(1, len(top)))
|
| 575 |
+
|
| 576 |
+
file_results.append({
|
| 577 |
+
"path": path,
|
| 578 |
+
"score": float(file_score),
|
| 579 |
+
"best_chunk": {
|
| 580 |
+
"chunk_id": best.get("chunk_id"),
|
| 581 |
+
"kind": best.get("kind"),
|
| 582 |
+
"start_line": best.get("start_line"),
|
| 583 |
+
"end_line": best.get("end_line"),
|
| 584 |
+
"text": best.get("text"),
|
| 585 |
+
"chunk_score": best.get("score"),
|
| 586 |
+
},
|
| 587 |
+
"top_chunks": [
|
| 588 |
+
{"chunk_id": h.get("chunk_id"), "score": h.get("score"),
|
| 589 |
+
"start_line": h.get("start_line"), "end_line": h.get("end_line")}
|
| 590 |
+
for h in top
|
| 591 |
+
],
|
| 592 |
+
"hits": len(hits),
|
| 593 |
+
})
|
| 594 |
+
|
| 595 |
+
file_results.sort(key=lambda x: x["score"], reverse=True)
|
| 596 |
+
return {"results": file_results[: int(req.k)]}
|
| 597 |
+
|
| 598 |
+
|
| 599 |
+
|
| 600 |
+
|
| 601 |
|
| 602 |
# ----------- ARTIFACTS EXPORT -----------
|
| 603 |
@fastapi_app.get("/artifacts/{project_id}/dataset")
|