Morinash commited on
Commit
340c03d
·
verified ·
1 Parent(s): 2ef34b3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +109 -91
app.py CHANGED
@@ -1,4 +1,3 @@
1
- # app.py
2
  import os
3
  import tempfile
4
  import gradio as gr
@@ -7,7 +6,7 @@ import pandas as pd
7
  import requests
8
  from bs4 import BeautifulSoup
9
  from pypdf import PdfReader
10
- import docx
11
  from sentence_transformers import SentenceTransformer
12
  from langchain.text_splitter import RecursiveCharacterTextSplitter
13
  import faiss
@@ -17,8 +16,8 @@ from transformers import pipeline
17
  # ==============================
18
  # CONFIG
19
  # ==============================
20
- HF_GENERATION_MODEL = os.environ.get("HF_GENERATION_MODEL", "google/flan-t5-large")
21
- EMBEDDING_MODEL_NAME = "sentence-transformers/all-MiniLM-L6-v2"
22
  INDEX_PATH = "faiss_index.index"
23
  METADATA_PATH = "metadata.json"
24
 
@@ -31,34 +30,46 @@ embed_model = SentenceTransformer(EMBEDDING_MODEL_NAME)
31
  # Helper text extractors
32
  # ==============================
33
  def extract_text_from_pdf(file_path):
34
- reader = PdfReader(file_path)
35
- pages = [p.extract_text() or "" for p in reader.pages]
36
- return "\n\n".join(pages)
 
 
 
37
 
38
  def extract_text_from_docx(file_path):
39
- doc = docx.Document(file_path)
40
- return "\n\n".join(p.text for p in doc.paragraphs)
 
 
 
41
 
42
  def extract_text_from_excel(file_path):
43
- df_dict = pd.read_excel(file_path, sheet_name=None)
44
- out = []
45
- for sheet, df in df_dict.items():
46
- out.append(f"Sheet: {sheet}")
47
- out.append(df.fillna("").to_csv(index=False))
48
- return "\n\n".join(out)
 
 
 
49
 
50
  def extract_text_from_url(url):
51
- r = requests.get(url, timeout=10)
52
- soup = BeautifulSoup(r.text, "lxml")
53
- for s in soup(["script", "style", "aside", "nav", "footer"]):
54
- s.decompose()
55
- text = soup.get_text(separator="\n")
56
- return text
 
 
 
57
 
58
  # ==============================
59
- # Text chunking setup
60
  # ==============================
61
- splitter = RecursiveCharacterTextSplitter(chunk_size=1500, chunk_overlap=200)
62
 
63
  # ==============================
64
  # Ingestion function
@@ -67,29 +78,50 @@ def ingest_sources(files, urls):
67
  docs = []
68
  metadata = []
69
 
 
 
 
 
70
  # Handle uploaded files
71
- for f in files:
72
- name = f.name
73
  tmp = tempfile.NamedTemporaryFile(delete=False)
 
74
  try:
 
 
75
  if hasattr(f, "read"):
76
- tmp.write(f.read())
77
- else:
78
- tmp.write(f.encode("utf-8"))
 
 
 
 
 
 
 
 
79
  tmp.flush()
80
  tmp.close()
81
 
82
- if name.lower().endswith(".pdf"):
 
83
  text = extract_text_from_pdf(tmp.name)
84
- elif name.lower().endswith(".docx"):
85
  text = extract_text_from_docx(tmp.name)
86
- elif name.lower().endswith((".xls", ".xlsx")):
87
  text = extract_text_from_excel(tmp.name)
88
  else:
89
  with open(tmp.name, "r", encoding="utf-8", errors="ignore") as fh:
90
  text = fh.read()
 
 
91
  finally:
92
- os.unlink(tmp.name)
 
 
 
 
93
 
94
  chunks = splitter.split_text(text)
95
  for i, c in enumerate(chunks):
@@ -97,37 +129,43 @@ def ingest_sources(files, urls):
97
  metadata.append({"source": name, "chunk": i, "type": "file", "text": c})
98
 
99
  # Handle URLs
100
- for u in urls:
101
- if not u.strip():
 
 
 
 
102
  continue
103
- try:
104
- text = extract_text_from_url(u)
105
- chunks = splitter.split_text(text)
106
- for i, c in enumerate(chunks):
107
- docs.append(c)
108
- metadata.append({"source": u, "chunk": i, "type": "url", "text": c})
109
- except Exception as e:
110
- print("URL error:", u, e)
111
 
112
  if not docs:
113
- return "No text extracted from files or URLs."
114
 
115
- embeddings = embed_model.encode(docs, show_progress_bar=True, convert_to_numpy=True)
116
- dim = embeddings.shape[1]
 
 
117
 
 
118
  if os.path.exists(INDEX_PATH):
119
  index = faiss.read_index(INDEX_PATH)
120
  old_meta = json.load(open(METADATA_PATH, "r", encoding="utf-8"))
121
  index.add(embeddings)
122
  old_meta.extend(metadata)
123
- json.dump(old_meta, open(METADATA_PATH, "w", encoding="utf-8"))
 
124
  else:
125
  index = faiss.IndexFlatL2(dim)
126
  index.add(embeddings)
127
- json.dump(metadata, open(METADATA_PATH, "w", encoding="utf-8"))
 
128
 
129
  faiss.write_index(index, INDEX_PATH)
130
- return f"Ingested {len(docs)} text chunks from {len(files)} files and {len(urls)} URLs."
131
 
132
  # ==============================
133
  # Retrieve top matching chunks
@@ -138,84 +176,64 @@ def retrieve_topk(query, k=5):
138
  q_emb = embed_model.encode([query], convert_to_numpy=True)
139
  index = faiss.read_index(INDEX_PATH)
140
  D, I = index.search(q_emb, k)
141
- metadata = json.load(open(METADATA_PATH, "r", encoding="utf-8"))
142
- results = []
143
- for idx in I[0]:
144
- if idx < len(metadata):
145
- results.append(metadata[idx])
146
  return results
147
 
148
  # ==============================
149
- # Generation pipeline
150
  # ==============================
151
  gen_pipeline = pipeline(
152
  "text2text-generation",
153
  model=HF_GENERATION_MODEL,
154
- device=0 if os.environ.get("HF_DEVICE", "cpu") != "cpu" else -1,
155
  )
156
 
157
  # ==============================
158
  # Ask prompt
159
  # ==============================
160
  def ask_prompt(prompt, top_k=5):
161
- if not os.path.exists(INDEX_PATH) or not os.path.exists(METADATA_PATH):
162
- return "No documents ingested yet."
163
-
164
  hits = retrieve_topk(prompt, k=top_k)
165
  if not hits:
166
- return "No relevant context found. Try ingesting more content."
167
 
168
- # Collect context text
169
- context_parts = [h["text"] for h in hits if "text" in h]
170
  sources = [f"{h['source']} (chunk {h['chunk']})" for h in hits]
171
 
172
- context = "\n\n".join(context_parts)
173
- if not context.strip():
174
- return "No readable text found in the ingested files."
175
 
176
  system_instruction = (
177
- "You are a helpful research assistant. Read the provided context carefully "
178
- "and answer the question accurately and concisely."
179
  )
180
-
181
- full_prompt = f"{system_instruction}\n\nCONTEXT:\n{context}\n\nQUESTION:\n{prompt}\n\nAnswer:"
182
 
183
  try:
184
- out = gen_pipeline(full_prompt, max_length=400, do_sample=False)[0]["generated_text"]
185
  except Exception as e:
186
- return f"Model generation failed: {e}"
187
 
188
- return out + "\n\nSources:\n" + "\n".join(sources)
189
 
190
  # ==============================
191
  # Gradio UI
192
  # ==============================
193
  with gr.Blocks() as demo:
194
- gr.Markdown(
195
- "# 🧠 Research Assistant (Prototype)\nUpload files or paste URLs, click **Ingest**, then ask your question."
196
- )
197
  with gr.Row():
198
  with gr.Column():
199
- file_in = gr.File(
200
- label="Upload files (pdf/docx/xlsx/txt)", file_count="multiple"
201
- )
202
- urls_in = gr.Textbox(
203
- label="URLs (one per line)",
204
- placeholder="https://example.com/article",
205
- )
206
  ingest_btn = gr.Button("Ingest")
207
- ingest_output = gr.Textbox(label="Ingest status")
208
  with gr.Column():
209
- prompt_in = gr.Textbox(label="Your question", lines=4)
210
  ask_btn = gr.Button("Ask")
211
  answer_out = gr.Textbox(label="Answer", lines=12)
212
-
213
- ingest_btn.click(
214
- lambda files, urls: ingest_sources(files or [], (urls or "").splitlines()),
215
- inputs=[file_in, urls_in],
216
- outputs=ingest_output,
217
- )
218
- ask_btn.click(lambda p: ask_prompt(p, top_k=5), inputs=prompt_in, outputs=answer_out)
219
 
220
  if __name__ == "__main__":
221
- demo.launch()
 
 
1
  import os
2
  import tempfile
3
  import gradio as gr
 
6
  import requests
7
  from bs4 import BeautifulSoup
8
  from pypdf import PdfReader
9
+ from docx import Document # Use Document for docx extraction
10
  from sentence_transformers import SentenceTransformer
11
  from langchain.text_splitter import RecursiveCharacterTextSplitter
12
  import faiss
 
16
  # ==============================
17
  # CONFIG
18
  # ==============================
19
+ HF_GENERATION_MODEL = os.environ.get("HF_GENERATION_MODEL", "google/flan-t5-large") # Swap to "deepseek-ai/DeepSeek-V3" if using HF Inference or GPU
20
+ EMBEDDING_MODEL_NAME = "sentence-transformers/paraphrase-MiniLM-L3-v2" # Lighter for CPU
21
  INDEX_PATH = "faiss_index.index"
22
  METADATA_PATH = "metadata.json"
23
 
 
30
  # Helper text extractors
31
  # ==============================
32
  def extract_text_from_pdf(file_path):
33
+ try:
34
+ reader = PdfReader(file_path)
35
+ pages = [p.extract_text() or "" for p in reader.pages]
36
+ return "\n\n".join(pages)
37
+ except Exception as e:
38
+ return f"PDF extraction error: {str(e)}"
39
 
40
  def extract_text_from_docx(file_path):
41
+ try:
42
+ doc = Document(file_path)
43
+ return "\n\n".join(p.text for p in doc.paragraphs)
44
+ except Exception as e:
45
+ return f"DOCX extraction error: {str(e)}"
46
 
47
  def extract_text_from_excel(file_path):
48
+ try:
49
+ df_dict = pd.read_excel(file_path, sheet_name=None)
50
+ out = []
51
+ for sheet, df in df_dict.items():
52
+ out.append(f"Sheet: {sheet}")
53
+ out.append(df.fillna("").to_csv(index=False))
54
+ return "\n\n".join(out)
55
+ except Exception as e:
56
+ return f"Excel extraction error: {str(e)}"
57
 
58
  def extract_text_from_url(url):
59
+ try:
60
+ r = requests.get(url, timeout=10)
61
+ soup = BeautifulSoup(r.text, "lxml")
62
+ for s in soup(["script", "style", "aside", "nav", "footer"]):
63
+ s.decompose()
64
+ text = soup.get_text(separator="\n")
65
+ return text.strip()
66
+ except Exception as e:
67
+ return f"URL extraction error: {str(e)}"
68
 
69
  # ==============================
70
+ # Text chunking setup (optimized for speed: larger chunks = fewer embeddings)
71
  # ==============================
72
+ splitter = RecursiveCharacterTextSplitter(chunk_size=2000, chunk_overlap=100)
73
 
74
  # ==============================
75
  # Ingestion function
 
78
  docs = []
79
  metadata = []
80
 
81
+ # Skip if index exists (to persist across restarts)
82
+ if os.path.exists(INDEX_PATH) and os.path.exists(METADATA_PATH):
83
+ return "Index already exists. Clear files to re-ingest."
84
+
85
  # Handle uploaded files
86
+ for f in files or []:
 
87
  tmp = tempfile.NamedTemporaryFile(delete=False)
88
+ name = getattr(f, "name", "uploaded_file")
89
  try:
90
+ # Robust handling for Gradio file types
91
+ data = None
92
  if hasattr(f, "read"):
93
+ data = f.read()
94
+ elif isinstance(f, str):
95
+ data = f.encode("utf-8")
96
+ elif isinstance(f, dict) and "data" in f:
97
+ data = f["data"]
98
+ if isinstance(data, str):
99
+ data = data.encode("utf-8")
100
+ if data is None:
101
+ raise ValueError(f"Unknown file type: {type(f)}")
102
+
103
+ tmp.write(data)
104
  tmp.flush()
105
  tmp.close()
106
 
107
+ low_name = name.lower()
108
+ if low_name.endswith(".pdf"):
109
  text = extract_text_from_pdf(tmp.name)
110
+ elif low_name.endswith(".docx"):
111
  text = extract_text_from_docx(tmp.name)
112
+ elif low_name.endswith((".xls", ".xlsx")):
113
  text = extract_text_from_excel(tmp.name)
114
  else:
115
  with open(tmp.name, "r", encoding="utf-8", errors="ignore") as fh:
116
  text = fh.read()
117
+ except Exception as e:
118
+ return f"File processing error for {name}: {str(e)}"
119
  finally:
120
+ if os.path.exists(tmp.name):
121
+ os.unlink(tmp.name)
122
+
123
+ if "error" in text.lower():
124
+ continue # Skip failed extractions
125
 
126
  chunks = splitter.split_text(text)
127
  for i, c in enumerate(chunks):
 
129
  metadata.append({"source": name, "chunk": i, "type": "file", "text": c})
130
 
131
  # Handle URLs
132
+ for u in (urls or "").splitlines():
133
+ u = u.strip()
134
+ if not u:
135
+ continue
136
+ text = extract_text_from_url(u)
137
+ if "error" in text.lower():
138
  continue
139
+
140
+ chunks = splitter.split_text(text)
141
+ for i, c in enumerate(chunks):
142
+ docs.append(c)
143
+ metadata.append({"source": u, "chunk": i, "type": "url", "text": c})
 
 
 
144
 
145
  if not docs:
146
+ return "No valid text extracted. Check files/URLs."
147
 
148
+ try:
149
+ embeddings = embed_model.encode(docs, show_progress_bar=True, convert_to_numpy=True)
150
+ except Exception as e:
151
+ return f"Embedding failed: {str(e)}"
152
 
153
+ dim = embeddings.shape[1]
154
  if os.path.exists(INDEX_PATH):
155
  index = faiss.read_index(INDEX_PATH)
156
  old_meta = json.load(open(METADATA_PATH, "r", encoding="utf-8"))
157
  index.add(embeddings)
158
  old_meta.extend(metadata)
159
+ with open(METADATA_PATH, "w", encoding="utf-8") as fh:
160
+ json.dump(old_meta, fh)
161
  else:
162
  index = faiss.IndexFlatL2(dim)
163
  index.add(embeddings)
164
+ with open(METADATA_PATH, "w", encoding="utf-8") as fh:
165
+ json.dump(metadata, fh)
166
 
167
  faiss.write_index(index, INDEX_PATH)
168
+ return f"Ingested {len(docs)} chunks from {len(files or [])} files and {len(urls.splitlines())} URLs."
169
 
170
  # ==============================
171
  # Retrieve top matching chunks
 
176
  q_emb = embed_model.encode([query], convert_to_numpy=True)
177
  index = faiss.read_index(INDEX_PATH)
178
  D, I = index.search(q_emb, k)
179
+ with open(METADATA_PATH, "r", encoding="utf-8") as fh:
180
+ metadata = json.load(fh)
181
+ results = [metadata[idx] for idx in I[0] if idx < len(metadata)]
 
 
182
  return results
183
 
184
  # ==============================
185
+ # Generation pipeline (force CPU for free tier)
186
  # ==============================
187
  gen_pipeline = pipeline(
188
  "text2text-generation",
189
  model=HF_GENERATION_MODEL,
190
+ device=-1, # CPU only
191
  )
192
 
193
  # ==============================
194
  # Ask prompt
195
  # ==============================
196
  def ask_prompt(prompt, top_k=5):
 
 
 
197
  hits = retrieve_topk(prompt, k=top_k)
198
  if not hits:
199
+ return "No relevant content found. Ingest files/URLs first."
200
 
201
+ context_parts = [h.get("text", "") for h in hits]
 
202
  sources = [f"{h['source']} (chunk {h['chunk']})" for h in hits]
203
 
204
+ context = "\n\n".join(filter(None, context_parts)) # Skip empty texts
205
+ if not context:
206
+ return "No usable text in retrieved chunks."
207
 
208
  system_instruction = (
209
+ "You are a helpful research assistant. Use only the provided context to answer the question accurately and concisely."
 
210
  )
211
+ full_prompt = f"{system_instruction}\n\nContext:\n{context}\n\nQuestion:\n{prompt}\n\nAnswer:"
 
212
 
213
  try:
214
+ out = gen_pipeline(full_prompt, max_length=512, do_sample=False)[0]["generated_text"]
215
  except Exception as e:
216
+ return f"Generation failed: {str(e)}"
217
 
218
+ return f"{out}\n\nSources:\n" + "\n".join(sources)
219
 
220
  # ==============================
221
  # Gradio UI
222
  # ==============================
223
  with gr.Blocks() as demo:
224
+ gr.Markdown("# Research Assistant Prototype\nUpload PDFs, Word, Excel, or paste URLs. Ingest, then ask questions.")
 
 
225
  with gr.Row():
226
  with gr.Column():
227
+ file_in = gr.File(label="Upload files (PDF/DOCX/XLSX/TXT)", file_count="multiple")
228
+ urls_in = gr.Textbox(label="URLs (one per line)", placeholder="https://example.com")
 
 
 
 
 
229
  ingest_btn = gr.Button("Ingest")
230
+ ingest_output = gr.Textbox(label="Status")
231
  with gr.Column():
232
+ prompt_in = gr.Textbox(label="Question", lines=4)
233
  ask_btn = gr.Button("Ask")
234
  answer_out = gr.Textbox(label="Answer", lines=12)
235
+ ingest_btn.click(ingest_sources, inputs=[file_in, urls_in], outputs=ingest_output)
236
+ ask_btn.click(ask_prompt, inputs=prompt_in, outputs=answer_out)
 
 
 
 
 
237
 
238
  if __name__ == "__main__":
239
+ demo.launch()