Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,4 +1,3 @@
|
|
| 1 |
-
# app.py
|
| 2 |
import os
|
| 3 |
import tempfile
|
| 4 |
import gradio as gr
|
|
@@ -16,7 +15,7 @@ import numpy as np
|
|
| 16 |
from transformers import pipeline
|
| 17 |
|
| 18 |
# CONFIG
|
| 19 |
-
HF_GENERATION_MODEL = os.environ.get("HF_GENERATION_MODEL","google/flan-t5-large") # change to DeepSeek if ready
|
| 20 |
EMBEDDING_MODEL_NAME = "sentence-transformers/all-MiniLM-L6-v2"
|
| 21 |
INDEX_PATH = "faiss_index.index"
|
| 22 |
METADATA_PATH = "metadata.json"
|
|
@@ -48,7 +47,7 @@ def extract_text_from_excel(file):
|
|
| 48 |
def extract_text_from_url(url):
|
| 49 |
r = requests.get(url, timeout=10)
|
| 50 |
soup = BeautifulSoup(r.text, "lxml")
|
| 51 |
-
for s in soup(["script","style","aside","nav","footer"]):
|
| 52 |
s.decompose()
|
| 53 |
text = soup.get_text(separator="\n")
|
| 54 |
return text
|
|
@@ -59,51 +58,76 @@ splitter = RecursiveCharacterTextSplitter(chunk_size=1500, chunk_overlap=200)
|
|
| 59 |
def ingest_sources(files, urls):
|
| 60 |
docs = []
|
| 61 |
metadata = []
|
|
|
|
| 62 |
for f in files:
|
| 63 |
-
|
| 64 |
-
tmp = tempfile.NamedTemporaryFile(delete=False)
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
tmp.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
if name.lower().endswith(".pdf"):
|
| 73 |
text = extract_text_from_pdf(tmp.name)
|
| 74 |
elif name.lower().endswith(".docx"):
|
| 75 |
text = extract_text_from_docx(tmp.name)
|
| 76 |
-
elif name.lower().endswith((".xls",".xlsx")):
|
| 77 |
text = extract_text_from_excel(tmp.name)
|
| 78 |
else:
|
| 79 |
with open(tmp.name, "r", encoding="utf-8", errors="ignore") as fh:
|
| 80 |
text = fh.read()
|
|
|
|
| 81 |
os.unlink(tmp.name)
|
|
|
|
| 82 |
chunks = splitter.split_text(text)
|
| 83 |
for i, c in enumerate(chunks):
|
| 84 |
docs.append(c)
|
| 85 |
-
metadata.append({"source": name, "chunk": i, "type":"file"})
|
|
|
|
|
|
|
| 86 |
for u in urls:
|
|
|
|
|
|
|
|
|
|
| 87 |
try:
|
| 88 |
text = extract_text_from_url(u)
|
| 89 |
chunks = splitter.split_text(text)
|
| 90 |
for i, c in enumerate(chunks):
|
| 91 |
docs.append(c)
|
| 92 |
-
metadata.append({"source": u, "chunk": i, "type":"url"})
|
| 93 |
except Exception as e:
|
| 94 |
print("url error", u, e)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 95 |
embeddings = embed_model.encode(docs, show_progress_bar=True, convert_to_numpy=True)
|
| 96 |
dim = embeddings.shape[1]
|
|
|
|
| 97 |
if os.path.exists(INDEX_PATH):
|
| 98 |
index = faiss.read_index(INDEX_PATH)
|
| 99 |
-
old_meta = json.load(open(METADATA_PATH,"r"))
|
| 100 |
index.add(embeddings)
|
| 101 |
old_meta.extend(metadata)
|
| 102 |
-
json.dump(old_meta, open(METADATA_PATH,"w"))
|
| 103 |
else:
|
| 104 |
index = faiss.IndexFlatL2(dim)
|
| 105 |
index.add(embeddings)
|
| 106 |
-
json.dump(metadata, open(METADATA_PATH,"w"))
|
|
|
|
| 107 |
faiss.write_index(index, INDEX_PATH)
|
| 108 |
return f"Ingested {len(docs)} chunks from {len(files)} files and {len(urls)} urls."
|
| 109 |
|
|
@@ -113,27 +137,32 @@ def retrieve_topk(query, k=5):
|
|
| 113 |
return []
|
| 114 |
index = faiss.read_index(INDEX_PATH)
|
| 115 |
D, I = index.search(q_emb, k)
|
| 116 |
-
metadata = json.load(open(METADATA_PATH,"r"))
|
| 117 |
results = []
|
| 118 |
for idx in I[0]:
|
| 119 |
if idx < len(metadata):
|
| 120 |
results.append((metadata[idx], idx))
|
| 121 |
return results
|
| 122 |
|
| 123 |
-
gen_pipeline = pipeline("text2text-generation", model=HF_GENERATION_MODEL, device=0 if os.environ.get("HF_DEVICE","cpu")!="cpu" else -1)
|
| 124 |
|
| 125 |
def ask_prompt(prompt, top_k=5):
|
| 126 |
hits = retrieve_topk(prompt, k=top_k)
|
| 127 |
if not hits:
|
| 128 |
return "No documents ingested. Use Ingest first."
|
|
|
|
| 129 |
context_parts = []
|
| 130 |
sources = []
|
| 131 |
for meta, idx in hits:
|
| 132 |
sources.append(f"{meta['source']} (chunk {meta['chunk']})")
|
| 133 |
context_parts.append(f"[{meta['source']} - chunk {meta['chunk']}]")
|
|
|
|
| 134 |
context = "\n\n".join(context_parts)
|
| 135 |
-
system_instruction = (
|
| 136 |
-
|
|
|
|
|
|
|
|
|
|
| 137 |
prompt_text = f"{system_instruction}\n\nCONTEXT:\n{context}\n\nQUESTION:\n{prompt}\n\nAnswer:"
|
| 138 |
out = gen_pipeline(prompt_text, max_length=512, do_sample=False)[0]["generated_text"]
|
| 139 |
out = out + "\n\nSources:\n" + "\n".join(sources)
|
|
|
|
|
|
|
| 1 |
import os
|
| 2 |
import tempfile
|
| 3 |
import gradio as gr
|
|
|
|
| 15 |
from transformers import pipeline
|
| 16 |
|
| 17 |
# CONFIG
|
| 18 |
+
HF_GENERATION_MODEL = os.environ.get("HF_GENERATION_MODEL", "google/flan-t5-large") # change to DeepSeek if ready
|
| 19 |
EMBEDDING_MODEL_NAME = "sentence-transformers/all-MiniLM-L6-v2"
|
| 20 |
INDEX_PATH = "faiss_index.index"
|
| 21 |
METADATA_PATH = "metadata.json"
|
|
|
|
| 47 |
def extract_text_from_url(url):
|
| 48 |
r = requests.get(url, timeout=10)
|
| 49 |
soup = BeautifulSoup(r.text, "lxml")
|
| 50 |
+
for s in soup(["script", "style", "aside", "nav", "footer"]):
|
| 51 |
s.decompose()
|
| 52 |
text = soup.get_text(separator="\n")
|
| 53 |
return text
|
|
|
|
| 58 |
def ingest_sources(files, urls):
|
| 59 |
docs = []
|
| 60 |
metadata = []
|
| 61 |
+
|
| 62 |
for f in files:
|
| 63 |
+
# make sure we have a temp file
|
| 64 |
+
tmp = tempfile.NamedTemporaryFile(delete=False)
|
| 65 |
+
|
| 66 |
+
# handle different types of file objects
|
| 67 |
+
if hasattr(f, "read"): # normal file
|
| 68 |
+
tmp.write(f.read())
|
| 69 |
+
name = getattr(f, "name", "uploaded_file")
|
| 70 |
+
elif isinstance(f, str): # NamedString or text
|
| 71 |
+
tmp.write(f.encode("utf-8"))
|
| 72 |
+
name = "uploaded_text.txt"
|
| 73 |
+
elif isinstance(f, dict) and "data" in f: # HF file dict
|
| 74 |
+
tmp.write(f["data"])
|
| 75 |
+
name = f.get("name", "uploaded_file")
|
| 76 |
+
else:
|
| 77 |
+
raise ValueError(f"Unknown file type: {type(f)}")
|
| 78 |
+
|
| 79 |
+
tmp.flush()
|
| 80 |
+
tmp.close()
|
| 81 |
+
|
| 82 |
+
# extract text depending on file type
|
| 83 |
if name.lower().endswith(".pdf"):
|
| 84 |
text = extract_text_from_pdf(tmp.name)
|
| 85 |
elif name.lower().endswith(".docx"):
|
| 86 |
text = extract_text_from_docx(tmp.name)
|
| 87 |
+
elif name.lower().endswith((".xls", ".xlsx")):
|
| 88 |
text = extract_text_from_excel(tmp.name)
|
| 89 |
else:
|
| 90 |
with open(tmp.name, "r", encoding="utf-8", errors="ignore") as fh:
|
| 91 |
text = fh.read()
|
| 92 |
+
|
| 93 |
os.unlink(tmp.name)
|
| 94 |
+
|
| 95 |
chunks = splitter.split_text(text)
|
| 96 |
for i, c in enumerate(chunks):
|
| 97 |
docs.append(c)
|
| 98 |
+
metadata.append({"source": name, "chunk": i, "type": "file"})
|
| 99 |
+
|
| 100 |
+
# handle URLs
|
| 101 |
for u in urls:
|
| 102 |
+
u = u.strip()
|
| 103 |
+
if not u:
|
| 104 |
+
continue
|
| 105 |
try:
|
| 106 |
text = extract_text_from_url(u)
|
| 107 |
chunks = splitter.split_text(text)
|
| 108 |
for i, c in enumerate(chunks):
|
| 109 |
docs.append(c)
|
| 110 |
+
metadata.append({"source": u, "chunk": i, "type": "url"})
|
| 111 |
except Exception as e:
|
| 112 |
print("url error", u, e)
|
| 113 |
+
|
| 114 |
+
if not docs:
|
| 115 |
+
return "No valid documents or URLs found."
|
| 116 |
+
|
| 117 |
embeddings = embed_model.encode(docs, show_progress_bar=True, convert_to_numpy=True)
|
| 118 |
dim = embeddings.shape[1]
|
| 119 |
+
|
| 120 |
if os.path.exists(INDEX_PATH):
|
| 121 |
index = faiss.read_index(INDEX_PATH)
|
| 122 |
+
old_meta = json.load(open(METADATA_PATH, "r"))
|
| 123 |
index.add(embeddings)
|
| 124 |
old_meta.extend(metadata)
|
| 125 |
+
json.dump(old_meta, open(METADATA_PATH, "w"))
|
| 126 |
else:
|
| 127 |
index = faiss.IndexFlatL2(dim)
|
| 128 |
index.add(embeddings)
|
| 129 |
+
json.dump(metadata, open(METADATA_PATH, "w"))
|
| 130 |
+
|
| 131 |
faiss.write_index(index, INDEX_PATH)
|
| 132 |
return f"Ingested {len(docs)} chunks from {len(files)} files and {len(urls)} urls."
|
| 133 |
|
|
|
|
| 137 |
return []
|
| 138 |
index = faiss.read_index(INDEX_PATH)
|
| 139 |
D, I = index.search(q_emb, k)
|
| 140 |
+
metadata = json.load(open(METADATA_PATH, "r"))
|
| 141 |
results = []
|
| 142 |
for idx in I[0]:
|
| 143 |
if idx < len(metadata):
|
| 144 |
results.append((metadata[idx], idx))
|
| 145 |
return results
|
| 146 |
|
| 147 |
+
gen_pipeline = pipeline("text2text-generation", model=HF_GENERATION_MODEL, device=0 if os.environ.get("HF_DEVICE", "cpu") != "cpu" else -1)
|
| 148 |
|
| 149 |
def ask_prompt(prompt, top_k=5):
|
| 150 |
hits = retrieve_topk(prompt, k=top_k)
|
| 151 |
if not hits:
|
| 152 |
return "No documents ingested. Use Ingest first."
|
| 153 |
+
|
| 154 |
context_parts = []
|
| 155 |
sources = []
|
| 156 |
for meta, idx in hits:
|
| 157 |
sources.append(f"{meta['source']} (chunk {meta['chunk']})")
|
| 158 |
context_parts.append(f"[{meta['source']} - chunk {meta['chunk']}]")
|
| 159 |
+
|
| 160 |
context = "\n\n".join(context_parts)
|
| 161 |
+
system_instruction = (
|
| 162 |
+
"You are an AI research assistant. Use the contextual chunks below to answer the user's question. "
|
| 163 |
+
"Provide a concise answer, then list sources in order of relevance."
|
| 164 |
+
)
|
| 165 |
+
|
| 166 |
prompt_text = f"{system_instruction}\n\nCONTEXT:\n{context}\n\nQUESTION:\n{prompt}\n\nAnswer:"
|
| 167 |
out = gen_pipeline(prompt_text, max_length=512, do_sample=False)[0]["generated_text"]
|
| 168 |
out = out + "\n\nSources:\n" + "\n".join(sources)
|