resberry commited on
Commit
8b95286
·
verified ·
1 Parent(s): 1d1e754

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +393 -351
app.py CHANGED
@@ -1,351 +1,393 @@
1
- # === Required Libraries ===
2
- from huggingface_hub import InferenceClient
3
- import os
4
- import sys
5
- import re
6
- import json
7
- import requests
8
- import logging
9
- from bs4 import BeautifulSoup
10
- from readability import Document
11
- from duckduckgo_search import DDGS
12
- from concurrent.futures import ThreadPoolExecutor
13
- import gradio as gr
14
- from datetime import datetime, timedelta
15
- from sentence_transformers import SentenceTransformer
16
- import faiss
17
- import numpy as np
18
- import wikipedia
19
- # === Configuration ===
20
- HF_TOKEN = os.getenv("HF")
21
- MODEL_NAME = "meta-llama/Llama-3.1-8B-Instruct"
22
- client = InferenceClient(model=MODEL_NAME, token=HF_TOKEN)
23
- HEADERS = {"User-Agent": "Mozilla/5.0"}
24
- MAX_RESULTS = 5
25
- MAX_CHARS = 5000
26
- CONTEXT_DIR = "web_contexts"
27
- CHUNK_STORE = "chunk_store.json"
28
- LOG_FILE = "qa_log.jsonl"
29
- EMBED_FILE = "memory_embeddings.json"
30
- MAX_CHUNK_AGE_DAYS = 3
31
- MIN_CONTEXT_SIMILARITY = 0.4
32
- SEMANTIC_SCHOLAR_API = "https://api.semanticscholar.org/graph/v1/paper/search"
33
- SEMANTIC_SCHOLAR_FIELDS = "title,abstract,url,authors,year"
34
- os.makedirs(CONTEXT_DIR, exist_ok=True)
35
- logging.basicConfig(level=logging.INFO)
36
- # === Embedding Model ===
37
- EMBED_MODEL = SentenceTransformer("all-MiniLM-L6-v2")
38
- def embed(text):
39
- emb = EMBED_MODEL.encode([text])[0]
40
- return np.array(emb, dtype=np.float32)
41
- def cosine_similarity(a, b):
42
- return np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b) + 1e-10)
43
- def chunk_text(text, max_tokens=200):
44
- sentences = re.split(r'(?<=[.!?]) +', text)
45
- chunks, chunk, tokens = [], [], 0
46
- for sent in sentences:
47
- sent_tokens = len(sent.split())
48
- if tokens + sent_tokens > max_tokens:
49
- chunks.append(" ".join(chunk))
50
- chunk, tokens = [], 0
51
- chunk.append(sent)
52
- tokens += sent_tokens
53
- if chunk:
54
- chunks.append(" ".join(chunk))
55
- return chunks
56
- def current_iso_timestamp():
57
- return datetime.utcnow().isoformat()
58
- def save_chunks(query, chunks, urls):
59
- chunk_data = []
60
- now = current_iso_timestamp()
61
- for chunk in chunks:
62
- chunk_data.append({
63
- "query": query,
64
- "chunk": chunk,
65
- "embedding": embed(chunk).tolist(),
66
- "sources": urls,
67
- "timestamp": now
68
- })
69
- if os.path.exists(CHUNK_STORE):
70
- with open(CHUNK_STORE, "r") as f:
71
- existing = json.load(f)
72
- cutoff = datetime.utcnow() - timedelta(days=MAX_CHUNK_AGE_DAYS)
73
- existing = [c for c in existing if datetime.fromisoformat(c.get("timestamp", "1970-01-01T00:00:00")) > cutoff]
74
- else:
75
- existing = []
76
- existing.extend(chunk_data)
77
- with open(CHUNK_STORE, "w") as f:
78
- json.dump(existing, f, indent=2)
79
- def is_recent_chunk(ts):
80
- try:
81
- return (datetime.utcnow() - datetime.fromisoformat(ts)) < timedelta(days=MAX_CHUNK_AGE_DAYS)
82
- except:
83
- return False
84
- def retrieve_context_from_chunks(question, top_k=4):
85
- if not os.path.exists(CHUNK_STORE):
86
- return "", [], 0.0
87
- with open(CHUNK_STORE, "r") as f:
88
- data = json.load(f)
89
- data = [d for d in data if is_recent_chunk(d.get("timestamp", ""))]
90
- if not data:
91
- return "", [], 0.0
92
- embeddings = np.array([d['embedding'] for d in data]).astype('float32')
93
- dim = embeddings.shape[1]
94
- q_emb = embed(question).reshape(1, -1).astype('float32')
95
- if q_emb.shape[1] != dim:
96
- os.remove(CHUNK_STORE)
97
- return "", [], 0.0
98
- index = faiss.IndexFlatL2(dim)
99
- index.add(embeddings)
100
- distances, I = index.search(q_emb, top_k)
101
- top_chunks = [data[i]['chunk'] for i in I[0]]
102
- sources = list({src for i in I[0] for src in data[i]['sources']})
103
- similarities = 1 / (distances[0] + 1e-6)
104
- avg_sim = np.mean(similarities)
105
- return "\n\n".join(top_chunks), sources, avg_sim
106
- def fetch_text(url):
107
- try:
108
- r = requests.get(url, headers=HEADERS, timeout=10)
109
- doc = Document(r.text)
110
- soup = BeautifulSoup(doc.summary(), "html.parser")
111
- text = " ".join(p.get_text() for p in soup.find_all("p")).strip()
112
- return text, url
113
- except Exception as e:
114
- return "", url
115
- def scrape_and_save(query):
116
- filename = re.sub(r'[^a-zA-Z0-9_-]', '_', query)[:50] + ".json"
117
- filepath = os.path.join(CONTEXT_DIR, filename)
118
- if os.path.exists(filepath):
119
- with open(filepath, "r") as f:
120
- d = json.load(f)
121
- return d["context"], d["sources"]
122
- with DDGS() as ddgs:
123
- results = list(ddgs.text(query, max_results=MAX_RESULTS))
124
- urls = list({r['href'] for r in results if 'href' in r})
125
- with ThreadPoolExecutor(max_workers=MAX_RESULTS) as executor:
126
- fetched = list(executor.map(fetch_text, urls))
127
- texts, used_urls, total_chars = [], [], 0
128
- q_emb = embed(query)
129
- for text, url in fetched:
130
- if not text:
131
- continue
132
- if query.lower() not in text.lower():
133
- sim = cosine_similarity(q_emb, embed(text))
134
- if sim < 0.3:
135
- continue
136
- if total_chars + len(text) > MAX_CHARS:
137
- text = text[:MAX_CHARS - total_chars]
138
- texts.append(text)
139
- used_urls.append(url)
140
- total_chars += len(text)
141
- if total_chars >= MAX_CHARS:
142
- break
143
- context = "\n\n".join(texts)
144
- chunks = chunk_text(context)
145
- save_chunks(query, chunks, used_urls)
146
- with open(filepath, "w") as f:
147
- json.dump({"query": query, "context": context, "sources": used_urls}, f, indent=2)
148
- return context, used_urls
149
- def get_similar_memories(question, top_k=3):
150
- if not os.path.exists(EMBED_FILE):
151
- return []
152
- with open(EMBED_FILE, "r") as f:
153
- data = json.load(f)
154
- if not data:
155
- return []
156
- embeddings = np.array([m['embedding'] for m in data]).astype('float32')
157
- dim = embeddings.shape[1]
158
- q_emb = embed(question).reshape(1, -1).astype('float32')
159
- if q_emb.shape[1] != dim:
160
- os.remove(EMBED_FILE)
161
- return []
162
- index = faiss.IndexFlatL2(dim)
163
- index.add(embeddings)
164
- _, I = index.search(q_emb, top_k)
165
- return [data[i] for i in I[0]]
166
- def save_embedding_to_store(entry):
167
- if os.path.exists(EMBED_FILE):
168
- with open(EMBED_FILE, "r") as f:
169
- data = json.load(f)
170
- else:
171
- data = []
172
- data.append(entry)
173
- with open(EMBED_FILE, "w") as f:
174
- json.dump(data, f, indent=2)
175
- def answer_from_context(question):
176
- memory = get_similar_memories(question)
177
- memory_prompt = "\n\n".join(f"Q: {m['q']}\nA: {m['a']}" for m in memory)
178
- context, sources, avg_sim = retrieve_context_from_chunks(question)
179
- prompt = f"""
180
- Today's date is {datetime.utcnow().date()}.
181
- Use context and memory to answer and summarize the following question using fullly finished lines end with., clear, and grammatically correct finish sentences. Ensure that the response is factually accurate, complete, well-organized, finish sentences and easy to understand. Avoid repeating information,unfinish sentences and keep the response concise while still being informative.
182
-
183
- [CONTEXT]
184
- {context}
185
-
186
- [MEMORY]
187
- {memory_prompt}
188
-
189
- [QUESTION]
190
- Answer and summarize the following question using fullly finish linesens end with., clear, and grammatically correct finish sentences. Ensure that the response is factually accurate, complete, well-organized, finish sentences and easy to understand. Avoid repeating information, unfinish sentences, and keep the response concise while still being informative.
191
- {question}
192
-
193
- [ANSWER]
194
- """
195
- try:
196
- response = client.text_generation(prompt, max_new_tokens=512)
197
- reply = response.strip().split("<|assistant|>")[-1].strip()
198
- except Exception as e:
199
- reply = f"Error: {e}"
200
- log = {
201
- "time": str(datetime.utcnow()),
202
- "q": question,
203
- "a": reply,
204
- "sources": sources,
205
- "embedding": embed(question).tolist()
206
- }
207
- with open(LOG_FILE, "a") as f:
208
- f.write(json.dumps(log) + "\n")
209
- save_embedding_to_store(log)
210
- return reply, sources, avg_sim
211
- def needs_web_search_llm(question):
212
- prompt = f"""
213
- You are a helpful assistant that classifies whether a question requires a web search or external data.
214
-
215
- Question: "{question}"
216
-
217
- Answer with only "YES" if a web search is needed or "NO" if not.
218
- """
219
- try:
220
- response = client.text_generation(prompt, max_new_tokens=10)
221
- return "YES" in response.strip().upper()
222
- except Exception as e:
223
- return False
224
- def is_general_knowledge_question(question):
225
- prompt = f"""
226
- You are a classifier. Determine if the question below can be answered using general world knowledge, like an encyclopedia or Wikipedia.
227
-
228
- Question: "{question}"
229
-
230
- Answer with "YES" if it is general knowledge. Otherwise answer "NO".
231
- """
232
- try:
233
- response = client.text_generation(prompt, max_new_tokens=10)
234
- return "YES" in response.strip().upper()
235
- except Exception as e:
236
- return False
237
- def get_wikipedia_summary(query, sentences=3):
238
- try:
239
- wikipedia.set_lang("en")
240
- return wikipedia.summary(query, sentences=sentences)
241
- except wikipedia.exceptions.DisambiguationError as e:
242
- return f"Ambiguous question. Possible topics: {', '.join(e.options[:5])}"
243
- except wikipedia.exceptions.PageError:
244
- return "No Wikipedia article found for that topic."
245
- except Exception as e:
246
- return "Error accessing Wikipedia."
247
- # === Semantic Scholar API integration ===
248
- def semantic_scholar_search(query, max_results=5):
249
- params = {
250
- "query": query,
251
- "fields": SEMANTIC_SCHOLAR_FIELDS,
252
- "limit": max_results
253
- }
254
- try:
255
- resp = requests.get(SEMANTIC_SCHOLAR_API, params=params, timeout=10)
256
- resp.raise_for_status()
257
- data = resp.json()
258
- papers = data.get("data", [])
259
- texts = []
260
- urls = []
261
- for p in papers:
262
- title = p.get("title", "")
263
- abstract = p.get("abstract", "")
264
- url = p.get("url", "")
265
- year = p.get("year", "")
266
- authors = ", ".join([a.get("name","") for a in p.get("authors", [])])
267
- entry = f"Title: {title}\nAuthors: {authors}\nYear: {year}\nAbstract: {abstract}\nURL: {url}\n"
268
- texts.append(entry)
269
- if url:
270
- urls.append(url)
271
- if len("\n\n".join(texts)) > MAX_CHARS:
272
- break
273
- context = "\n\n".join(texts)
274
- chunks = chunk_text(context)
275
- save_chunks(query, chunks, urls)
276
- return context, urls
277
- except Exception as e:
278
- logging.warning(f"Semantic Scholar API error: {e}")
279
- return "", []
280
- def is_research_question(question):
281
- # Simple heuristic to detect research/scientific questions
282
- keywords = [
283
- "research", "study", "paper", "findings", "experiment", "scientific", "evidence", "meta-analysis",
284
- "hypothesis", "literature review", "case study", "theory", "framework", "methodology", "analysis",
285
- "data", "observation", "results", "variables", "survey", "questionnaire", "sampling", "experiment design",
286
- "quantitative", "qualitative", "mixed methods", "statistical", "inference", "regression", "correlation",
287
- "interview", "focus group", "coding", "themes", "interpretation", "reliability", "validity", "bias",
288
- "significance", "conclusion", "discussion", "implications", "limitations", "future research", "peer review",
289
- "publication", "citation", "replication", "protocol", "ethics", "IRB", "research question", "objective",
290
- "aim", "problem statement", "gap", "contribution", "novelty", "originality", "dataset", "case", "fieldwork",
291
- "observational", "experimental", "review", "systematic review", "control group", "randomized", "longitudinal",
292
- "cross-sectional", "data analysis", "research design", "conceptual", "empirical", "exploratory", "descriptive",
293
- "causal", "predictive", "construct", "operationalization", "dependent variable", "independent variable",
294
- "mediator", "moderator", "association", "impact", "effect", "relationship", "outcome", "measure", "coding scheme"
295
- ]
296
- q_lower = question.lower()
297
- return any(kw in q_lower for kw in keywords)
298
- def ask(q):
299
- # Check if research/scientific question and use Semantic Scholar
300
- if is_research_question(q):
301
- context, sources = semantic_scholar_search(q)
302
- if context:
303
- answer, sources, _ = answer_from_context(q)
304
- sources_text = "\n".join(f"- {url}" for url in sources)
305
- return answer, sources_text
306
- # fallback to regular web search if semantic scholar fails
307
- context, sources = scrape_and_save(q)
308
- answer, sources, _ = answer_from_context(q)
309
- sources_text = "\n".join(f"- {url}" for url in sources)
310
- return answer, sources_text
311
- # General knowledge questions use Wikipedia
312
- if is_general_knowledge_question(q):
313
- return get_wikipedia_summary(q), "Source: Wikipedia"
314
- # Check if we already have context stored with sufficient similarity
315
- _, _, avg_sim = retrieve_context_from_chunks(q)
316
- # Check if web search is needed or context similarity too low
317
- intent_search = needs_web_search_llm(q)
318
- if intent_search or avg_sim < MIN_CONTEXT_SIMILARITY:
319
- context, sources = scrape_and_save(q)
320
- answer, sources, _ = answer_from_context(q)
321
- sources_text = "\n".join(f"- {url}" for url in sources)
322
- else:
323
- # Use model to answer from prompt only
324
- prompt = f"<|user|>\n Answer and summarize the following question using fullly finish lines end with. , clear, and grammatically correct finish sentences. Ensure that the response is factually accurate, complete, well-organized, finish stances, and easy to understand. Avoid repeating information, unfinish sentences, and keep the response concise while still being informative.:\n{q.strip()}\n<|assistant|>\n"
325
- try:
326
- response = client.text_generation(prompt, max_new_tokens=512)
327
- answer = response.strip().split("<|assistant|>")[-1].strip()
328
- except Exception as e:
329
- answer = f"Error: {e}"
330
- sources_text = ""
331
- return answer, sources_text
332
- # === Gradio UI ===
333
- with gr.Blocks() as demo:
334
- gr.Markdown("""
335
- ## 🤖 LLaMA 3.1 Smart QA Bot
336
- - Uses **Wikipedia** for general knowledge
337
- - Searches **Semantic Scholar** for research-related questions
338
- - Falls back to web search when needed
339
- - Can handle **casual chat** too!
340
- """)
341
- q_input = gr.Textbox(label="Your Question")
342
- submit = gr.Button("Ask")
343
- a_output = gr.Textbox(label="Answer")
344
- s_output = gr.Markdown()
345
- submit.click(ask, inputs=q_input, outputs=[a_output, s_output])
346
- if __name__ == '__main__':
347
- if len(sys.argv) > 1:
348
- question = " ".join(sys.argv[1:])
349
- print(ask(question))
350
- else:
351
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # === Required Libraries ===
2
+ from huggingface_hub import InferenceClient
3
+ import os
4
+ import sys
5
+ import re
6
+ import json
7
+ import requests
8
+ import logging
9
+ from bs4 import BeautifulSoup
10
+ from readability import Document
11
+ from duckduckgo_search import DDGS
12
+ from concurrent.futures import ThreadPoolExecutor
13
+ import gradio as gr
14
+ from datetime import datetime, timedelta
15
+ from sentence_transformers import SentenceTransformer
16
+ import faiss
17
+ import numpy as np
18
+ import wikipedia
19
+
20
+ # === Configuration ===
21
+ HF_TOKEN = os.getenv("HF_TOKEN") or "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"
22
+ MODEL_NAME = "meta-llama/Llama-3.1-8B-Instruct"
23
+ client = InferenceClient(model=MODEL_NAME, token=HF_TOKEN)
24
+
25
+ HEADERS = {"User-Agent": "Mozilla/5.0"}
26
+ MAX_RESULTS = 5
27
+ MAX_CHARS = 5000
28
+ CONTEXT_DIR = "web_contexts"
29
+ CHUNK_STORE = "chunk_store.json"
30
+ LOG_FILE = "qa_log.jsonl"
31
+ EMBED_FILE = "memory_embeddings.json"
32
+ MAX_CHUNK_AGE_DAYS = 3
33
+ MIN_CONTEXT_SIMILARITY = 0.4
34
+
35
+ SEMANTIC_SCHOLAR_API = "https://api.semanticscholar.org/graph/v1/paper/search"
36
+ SEMANTIC_SCHOLAR_FIELDS = "title,abstract,url,authors,year"
37
+
38
+ os.makedirs(CONTEXT_DIR, exist_ok=True)
39
+ logging.basicConfig(level=logging.INFO)
40
+
41
+ # === Embedding Model ===
42
+ EMBED_MODEL = SentenceTransformer("all-MiniLM-L6-v2")
43
+
44
+ def embed(text):
45
+ emb = EMBED_MODEL.encode([text])[0]
46
+ return np.array(emb, dtype=np.float32)
47
+
48
+ def cosine_similarity(a, b):
49
+ return np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b) + 1e-10)
50
+
51
+ def chunk_text(text, max_tokens=200):
52
+ sentences = re.split(r'(?<=[.!?]) +', text)
53
+ chunks, chunk, tokens = [], [], 0
54
+ for sent in sentences:
55
+ sent_tokens = len(sent.split())
56
+ if tokens + sent_tokens > max_tokens:
57
+ chunks.append(" ".join(chunk))
58
+ chunk, tokens = [], 0
59
+ chunk.append(sent)
60
+ tokens += sent_tokens
61
+ if chunk:
62
+ chunks.append(" ".join(chunk))
63
+ return chunks
64
+
65
+ def current_iso_timestamp():
66
+ return datetime.utcnow().isoformat()
67
+
68
+ def save_chunks(query, chunks, urls):
69
+ chunk_data = []
70
+ now = current_iso_timestamp()
71
+ for chunk in chunks:
72
+ chunk_data.append({
73
+ "query": query,
74
+ "chunk": chunk,
75
+ "embedding": embed(chunk).tolist(),
76
+ "sources": urls,
77
+ "timestamp": now
78
+ })
79
+ if os.path.exists(CHUNK_STORE):
80
+ with open(CHUNK_STORE, "r") as f:
81
+ existing = json.load(f)
82
+ cutoff = datetime.utcnow() - timedelta(days=MAX_CHUNK_AGE_DAYS)
83
+ existing = [c for c in existing if datetime.fromisoformat(c.get("timestamp", "1970-01-01T00:00:00")) > cutoff]
84
+ else:
85
+ existing = []
86
+ existing.extend(chunk_data)
87
+ with open(CHUNK_STORE, "w") as f:
88
+ json.dump(existing, f, indent=2)
89
+
90
+ def is_recent_chunk(ts):
91
+ try:
92
+ return (datetime.utcnow() - datetime.fromisoformat(ts)) < timedelta(days=MAX_CHUNK_AGE_DAYS)
93
+ except:
94
+ return False
95
+
96
+ def retrieve_context_from_chunks(question, top_k=4):
97
+ if not os.path.exists(CHUNK_STORE):
98
+ return "", [], 0.0
99
+ with open(CHUNK_STORE, "r") as f:
100
+ data = json.load(f)
101
+ data = [d for d in data if is_recent_chunk(d.get("timestamp", ""))]
102
+ if not data:
103
+ return "", [], 0.0
104
+
105
+ embeddings = np.array([d['embedding'] for d in data]).astype('float32')
106
+ dim = embeddings.shape[1]
107
+ q_emb = embed(question).reshape(1, -1).astype('float32')
108
+ if q_emb.shape[1] != dim:
109
+ os.remove(CHUNK_STORE)
110
+ return "", [], 0.0
111
+
112
+ index = faiss.IndexFlatL2(dim)
113
+ index.add(embeddings)
114
+ distances, I = index.search(q_emb, top_k)
115
+ top_chunks = [data[i]['chunk'] for i in I[0]]
116
+ sources = list({src for i in I[0] for src in data[i]['sources']})
117
+ similarities = 1 / (distances[0] + 1e-6)
118
+ avg_sim = np.mean(similarities)
119
+ return "\n\n".join(top_chunks), sources, avg_sim
120
+
121
+ def fetch_text(url):
122
+ try:
123
+ r = requests.get(url, headers=HEADERS, timeout=10)
124
+ doc = Document(r.text)
125
+ soup = BeautifulSoup(doc.summary(), "html.parser")
126
+ text = " ".join(p.get_text() for p in soup.find_all("p")).strip()
127
+ return text, url
128
+ except Exception as e:
129
+ return "", url
130
+
131
+ def scrape_and_save(query):
132
+ filename = re.sub(r'[^a-zA-Z0-9_-]', '_', query)[:50] + ".json"
133
+ filepath = os.path.join(CONTEXT_DIR, filename)
134
+ if os.path.exists(filepath):
135
+ with open(filepath, "r") as f:
136
+ d = json.load(f)
137
+ return d["context"], d["sources"]
138
+
139
+ with DDGS() as ddgs:
140
+ results = list(ddgs.text(query, max_results=MAX_RESULTS))
141
+
142
+ urls = list({r['href'] for r in results if 'href' in r})
143
+ with ThreadPoolExecutor(max_workers=MAX_RESULTS) as executor:
144
+ fetched = list(executor.map(fetch_text, urls))
145
+
146
+ texts, used_urls, total_chars = [], [], 0
147
+ q_emb = embed(query)
148
+ for text, url in fetched:
149
+ if not text:
150
+ continue
151
+ if query.lower() not in text.lower():
152
+ sim = cosine_similarity(q_emb, embed(text))
153
+ if sim < 0.3:
154
+ continue
155
+ if total_chars + len(text) > MAX_CHARS:
156
+ text = text[:MAX_CHARS - total_chars]
157
+ texts.append(text)
158
+ used_urls.append(url)
159
+ total_chars += len(text)
160
+ if total_chars >= MAX_CHARS:
161
+ break
162
+
163
+ context = "\n\n".join(texts)
164
+ chunks = chunk_text(context)
165
+ save_chunks(query, chunks, used_urls)
166
+ with open(filepath, "w") as f:
167
+ json.dump({"query": query, "context": context, "sources": used_urls}, f, indent=2)
168
+ return context, used_urls
169
+
170
+ def get_similar_memories(question, top_k=3):
171
+ if not os.path.exists(EMBED_FILE):
172
+ return []
173
+ with open(EMBED_FILE, "r") as f:
174
+ data = json.load(f)
175
+ if not data:
176
+ return []
177
+
178
+ embeddings = np.array([m['embedding'] for m in data]).astype('float32')
179
+ dim = embeddings.shape[1]
180
+ q_emb = embed(question).reshape(1, -1).astype('float32')
181
+ if q_emb.shape[1] != dim:
182
+ os.remove(EMBED_FILE)
183
+ return []
184
+
185
+ index = faiss.IndexFlatL2(dim)
186
+ index.add(embeddings)
187
+ _, I = index.search(q_emb, top_k)
188
+ return [data[i] for i in I[0]]
189
+
190
+ def save_embedding_to_store(entry):
191
+ if os.path.exists(EMBED_FILE):
192
+ with open(EMBED_FILE, "r") as f:
193
+ data = json.load(f)
194
+ else:
195
+ data = []
196
+ data.append(entry)
197
+ with open(EMBED_FILE, "w") as f:
198
+ json.dump(data, f, indent=2)
199
+
200
+ def answer_from_context(question):
201
+ memory = get_similar_memories(question)
202
+ memory_prompt = "\n\n".join(f"Q: {m['q']}\nA: {m['a']}" for m in memory)
203
+ context, sources, avg_sim = retrieve_context_from_chunks(question)
204
+
205
+ prompt = f"""
206
+ Today's date is {datetime.utcnow().date()}.
207
+ Use context and memory to answer and summarize the following question using fullly finished lines end with., clear, and grammatically correct finish sentences. Ensure that the response is factually accurate, complete, well-organized, finish sentences and easy to understand. Avoid repeating information,unfinish sentences and keep the response concise while still being informative.
208
+
209
+ [CONTEXT]
210
+ {context}
211
+
212
+ [MEMORY]
213
+ {memory_prompt}
214
+
215
+ [QUESTION]
216
+ Answer and summarize the following question using fullly finish linesens end with., clear, and grammatically correct finish sentences. Ensure that the response is factually accurate, complete, well-organized, finish sentences and easy to understand. Avoid repeating information, unfinish sentences, and keep the response concise while still being informative.
217
+ {question}
218
+
219
+ [ANSWER]
220
+ """
221
+ try:
222
+ response = client.text_generation(prompt, max_new_tokens=512)
223
+ reply = response.strip().split("<|assistant|>")[-1].strip()
224
+ except Exception as e:
225
+ reply = f"Error: {e}"
226
+
227
+ log = {
228
+ "time": str(datetime.utcnow()),
229
+ "q": question,
230
+ "a": reply,
231
+ "sources": sources,
232
+ "embedding": embed(question).tolist()
233
+ }
234
+ with open(LOG_FILE, "a") as f:
235
+ f.write(json.dumps(log) + "\n")
236
+ save_embedding_to_store(log)
237
+ return reply, sources, avg_sim
238
+
239
+ def needs_web_search_llm(question):
240
+ prompt = f"""
241
+ You are a helpful assistant that classifies whether a question requires a web search or external data.
242
+
243
+ Question: "{question}"
244
+
245
+ Answer with only "YES" if a web search is needed or "NO" if not.
246
+ """
247
+ try:
248
+ response = client.text_generation(prompt, max_new_tokens=10)
249
+ return "YES" in response.strip().upper()
250
+ except Exception as e:
251
+ return False
252
+
253
+ def is_general_knowledge_question(question):
254
+ prompt = f"""
255
+ You are a classifier. Determine if the question below can be answered using general world knowledge, like an encyclopedia or Wikipedia.
256
+
257
+ Question: "{question}"
258
+
259
+ Answer with "YES" if it is general knowledge. Otherwise answer "NO".
260
+ """
261
+ try:
262
+ response = client.text_generation(prompt, max_new_tokens=10)
263
+ return "YES" in response.strip().upper()
264
+ except Exception as e:
265
+ return False
266
+
267
+ def get_wikipedia_summary(query, sentences=3):
268
+ try:
269
+ wikipedia.set_lang("en")
270
+ return wikipedia.summary(query, sentences=sentences)
271
+ except wikipedia.exceptions.DisambiguationError as e:
272
+ return f"Ambiguous question. Possible topics: {', '.join(e.options[:5])}"
273
+ except wikipedia.exceptions.PageError:
274
+ return "No Wikipedia article found for that topic."
275
+ except Exception as e:
276
+ return "Error accessing Wikipedia."
277
+
278
+ # === Semantic Scholar API integration ===
279
+ def semantic_scholar_search(query, max_results=5):
280
+ params = {
281
+ "query": query,
282
+ "fields": SEMANTIC_SCHOLAR_FIELDS,
283
+ "limit": max_results
284
+ }
285
+ try:
286
+ resp = requests.get(SEMANTIC_SCHOLAR_API, params=params, timeout=10)
287
+ resp.raise_for_status()
288
+ data = resp.json()
289
+ papers = data.get("data", [])
290
+ texts = []
291
+ urls = []
292
+ for p in papers:
293
+ title = p.get("title", "")
294
+ abstract = p.get("abstract", "")
295
+ url = p.get("url", "")
296
+ year = p.get("year", "")
297
+ authors = ", ".join([a.get("name","") for a in p.get("authors", [])])
298
+ entry = f"Title: {title}\nAuthors: {authors}\nYear: {year}\nAbstract: {abstract}\nURL: {url}\n"
299
+ texts.append(entry)
300
+ if url:
301
+ urls.append(url)
302
+ if len("\n\n".join(texts)) > MAX_CHARS:
303
+ break
304
+ context = "\n\n".join(texts)
305
+ chunks = chunk_text(context)
306
+ save_chunks(query, chunks, urls)
307
+ return context, urls
308
+ except Exception as e:
309
+ logging.warning(f"Semantic Scholar API error: {e}")
310
+ return "", []
311
+
312
+ def is_research_question(question):
313
+ # Simple heuristic to detect research/scientific questions
314
+ keywords = [
315
+ "research", "study", "paper", "findings", "experiment", "scientific", "evidence", "meta-analysis",
316
+ "hypothesis", "literature review", "case study", "theory", "framework", "methodology", "analysis",
317
+ "data", "observation", "results", "variables", "survey", "questionnaire", "sampling", "experiment design",
318
+ "quantitative", "qualitative", "mixed methods", "statistical", "inference", "regression", "correlation",
319
+ "interview", "focus group", "coding", "themes", "interpretation", "reliability", "validity", "bias",
320
+ "significance", "conclusion", "discussion", "implications", "limitations", "future research", "peer review",
321
+ "publication", "citation", "replication", "protocol", "ethics", "IRB", "research question", "objective",
322
+ "aim", "problem statement", "gap", "contribution", "novelty", "originality", "dataset", "case", "fieldwork",
323
+ "observational", "experimental", "review", "systematic review", "control group", "randomized", "longitudinal",
324
+ "cross-sectional", "data analysis", "research design", "conceptual", "empirical", "exploratory", "descriptive",
325
+ "causal", "predictive", "construct", "operationalization", "dependent variable", "independent variable",
326
+ "mediator", "moderator", "association", "impact", "effect", "relationship", "outcome", "measure", "coding scheme"
327
+ ]
328
+
329
+ q_lower = question.lower()
330
+ return any(kw in q_lower for kw in keywords)
331
+
332
+ def ask(q):
333
+ # Check if research/scientific question and use Semantic Scholar
334
+ if is_research_question(q):
335
+ context, sources = semantic_scholar_search(q)
336
+ if context:
337
+ answer, sources, _ = answer_from_context(q)
338
+ sources_text = "\n".join(f"- {url}" for url in sources)
339
+ return answer, sources_text
340
+ # fallback to regular web search if semantic scholar fails
341
+ context, sources = scrape_and_save(q)
342
+ answer, sources, _ = answer_from_context(q)
343
+ sources_text = "\n".join(f"- {url}" for url in sources)
344
+ return answer, sources_text
345
+
346
+ # General knowledge questions use Wikipedia
347
+ if is_general_knowledge_question(q):
348
+ return get_wikipedia_summary(q), "Source: Wikipedia"
349
+
350
+ # Check if we already have context stored with sufficient similarity
351
+ _, _, avg_sim = retrieve_context_from_chunks(q)
352
+
353
+ # Check if web search is needed or context similarity too low
354
+ intent_search = needs_web_search_llm(q)
355
+
356
+ if intent_search or avg_sim < MIN_CONTEXT_SIMILARITY:
357
+ context, sources = scrape_and_save(q)
358
+ answer, sources, _ = answer_from_context(q)
359
+ sources_text = "\n".join(f"- {url}" for url in sources)
360
+ else:
361
+ # Use model to answer from prompt only
362
+ prompt = f"<|user|>\n Answer and summarize the following question using fullly finish lines end with. , clear, and grammatically correct finish sentences. Ensure that the response is factually accurate, complete, well-organized, finish stances, and easy to understand. Avoid repeating information, unfinish sentences, and keep the response concise while still being informative.:\n{q.strip()}\n<|assistant|>\n"
363
+ try:
364
+ response = client.text_generation(prompt, max_new_tokens=512)
365
+ answer = response.strip().split("<|assistant|>")[-1].strip()
366
+ except Exception as e:
367
+ answer = f"Error: {e}"
368
+ sources_text = ""
369
+
370
+ return answer, sources_text
371
+
372
+ # === Gradio UI ===
373
+ with gr.Blocks() as demo:
374
+ gr.Markdown("""
375
+ ## 🤖 LLaMA 3.1 Smart QA Bot
376
+ - Uses **Wikipedia** for general knowledge
377
+ - Searches **Semantic Scholar** for research-related questions
378
+ - Falls back to web search when needed
379
+ - Can handle **casual chat** too!
380
+ """)
381
+
382
+ q_input = gr.Textbox(label="Your Question")
383
+ submit = gr.Button("Ask")
384
+ a_output = gr.Textbox(label="Answer")
385
+ s_output = gr.Markdown()
386
+ submit.click(ask, inputs=q_input, outputs=[a_output, s_output])
387
+
388
+ if __name__ == '__main__':
389
+ if len(sys.argv) > 1:
390
+ question = " ".join(sys.argv[1:])
391
+ print(ask(question))
392
+ else:
393
+ demo.launch()