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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +351 -264
app.py CHANGED
@@ -1,264 +1,351 @@
1
- # === Required Libraries ===
2
- from huggingface_hub import InferenceClient
3
- import os, sys, re, json, requests, logging
4
- from bs4 import BeautifulSoup
5
- from readability import Document
6
- from duckduckgo_search import DDGS
7
- from concurrent.futures import ThreadPoolExecutor
8
- import gradio as gr
9
- from datetime import datetime, timedelta
10
- from sentence_transformers import SentenceTransformer
11
- import faiss, numpy as np, wikipedia
12
-
13
- # === Configuration ===
14
- HF_TOKEN = os.getenv("HF")
15
- MODEL_NAME = "meta-llama/Llama-3.1-8B-Instruct"
16
- client = InferenceClient(model=MODEL_NAME, token=HF_TOKEN)
17
-
18
- HEADERS = {"User-Agent": "Mozilla/5.0"}
19
- MAX_RESULTS = 5
20
- MAX_CHARS = 5000
21
- CONTEXT_DIR = "web_contexts"
22
- CHUNK_STORE = "chunk_store.json"
23
- LOG_FILE = "qa_log.jsonl"
24
- EMBED_FILE = "memory_embeddings.json"
25
- MAX_CHUNK_AGE_DAYS = 3
26
- MIN_CONTEXT_SIMILARITY = 0.4
27
-
28
- SEMANTIC_SCHOLAR_API = "https://api.semanticscholar.org/graph/v1/paper/search"
29
- SEMANTIC_SCHOLAR_FIELDS = "title,abstract,url,authors,year"
30
-
31
- os.makedirs(CONTEXT_DIR, exist_ok=True)
32
- logging.basicConfig(level=logging.INFO)
33
-
34
- # === Embedding Model ===
35
- EMBED_MODEL = SentenceTransformer("all-MiniLM-L6-v2")
36
-
37
- def embed(text):
38
- emb = EMBED_MODEL.encode([text])[0]
39
- return np.array(emb, dtype=np.float32)
40
-
41
- def cosine_similarity(a, b):
42
- return np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b) + 1e-10)
43
-
44
- def chunk_text(text, max_tokens=200):
45
- sentences = re.split(r'(?<=[.!?]) +', text)
46
- chunks, chunk, tokens = [], [], 0
47
- for sent in sentences:
48
- sent_tokens = len(sent.split())
49
- if tokens + sent_tokens > max_tokens:
50
- chunks.append(" ".join(chunk))
51
- chunk, tokens = [], 0
52
- chunk.append(sent)
53
- tokens += sent_tokens
54
- if chunk:
55
- chunks.append(" ".join(chunk))
56
- return chunks
57
-
58
- def current_iso_timestamp():
59
- return datetime.utcnow().isoformat()
60
-
61
- def save_chunks(query, chunks, urls):
62
- chunk_data, now = [], current_iso_timestamp()
63
- for chunk in chunks:
64
- chunk_data.append({
65
- "query": query, "chunk": chunk,
66
- "embedding": embed(chunk).tolist(),
67
- "sources": urls, "timestamp": now
68
- })
69
- existing = []
70
- if os.path.exists(CHUNK_STORE):
71
- with open(CHUNK_STORE, "r") as f:
72
- existing = [c for c in json.load(f)
73
- if datetime.fromisoformat(c.get("timestamp","1970-01-01T00:00:00"))
74
- > datetime.utcnow() - timedelta(days=MAX_CHUNK_AGE_DAYS)]
75
- existing.extend(chunk_data)
76
- with open(CHUNK_STORE,"w") as f:
77
- json.dump(existing, f, indent=2)
78
-
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
-
85
- def retrieve_context_from_chunks(question, top_k=4):
86
- if not os.path.exists(CHUNK_STORE):
87
- return "", [], 0.0
88
- with open(CHUNK_STORE,"r") as f:
89
- data = [d for d in json.load(f) 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
- avg_sim = np.mean(1 / (distances[0] + 1e-6))
104
- return "\n\n".join(top_chunks), sources, avg_sim
105
-
106
- def fetch_text(url):
107
- try:
108
- r = requests.get(url, headers=HEADERS, timeout=10)
109
- doc = Document(r.text)
110
- text = " ".join(p.get_text() for p in BeautifulSoup(doc.summary(), "html.parser").find_all("p"))
111
- return text.strip(), url
112
- except:
113
- return "", url
114
-
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
- d = json.load(open(filepath,"r"))
120
- return d["context"], d["sources"]
121
- with DDGS() as ddgs:
122
- results = list(ddgs.text(query, max_results=MAX_RESULTS))
123
- urls = list({r['href'] for r in results if 'href' in r})
124
- fetched = ThreadPoolExecutor(MAX_RESULTS).map(fetch_text, urls)
125
- texts, used_urls, total_chars = [], [], 0
126
- q_emb = embed(query)
127
- for text, url in fetched:
128
- if not text:
129
- continue
130
- if query.lower() not in text.lower():
131
- if cosine_similarity(q_emb, embed(text)) < 0.3:
132
- continue
133
- if total_chars + len(text) > MAX_CHARS:
134
- text = text[:MAX_CHARS-total_chars]
135
- texts.append(text); used_urls.append(url)
136
- total_chars += len(text)
137
- if total_chars >= MAX_CHARS:
138
- break
139
- context = "\n\n".join(texts)
140
- save_chunks(query, chunk_text(context), used_urls)
141
- open(filepath,"w").write(json.dumps({"query":query,"context":context,"sources":used_urls}, indent=2))
142
- return context, used_urls
143
-
144
- def get_similar_memories(question, top_k=3):
145
- if not os.path.exists(EMBED_FILE):
146
- return []
147
- data = json.load(open(EMBED_FILE,"r"))
148
- if not data:
149
- return []
150
- embeddings = np.array([m['embedding'] for m in data]).astype('float32')
151
- q_emb = embed(question).reshape(1, -1).astype('float32')
152
- if q_emb.shape[1] != embeddings.shape[1]:
153
- os.remove(EMBED_FILE)
154
- return []
155
- index = faiss.IndexFlatL2(embeddings.shape[1])
156
- index.add(embeddings)
157
- _, I = index.search(q_emb, top_k)
158
- return [data[i] for i in I[0]]
159
-
160
- def save_embedding_to_store(entry):
161
- data = json.load(open(EMBED_FILE,"r")) if os.path.exists(EMBED_FILE) else []
162
- data.append(entry)
163
- open(EMBED_FILE,"w").write(json.dumps(data, indent=2))
164
-
165
- def call_conversational(messages, max_new_tokens):
166
- resp = client.conversational(messages=messages, max_new_tokens=max_new_tokens)
167
- return resp[-1]["content"].strip()
168
-
169
- def answer_from_context(question):
170
- memory = get_similar_memories(question)
171
- memory_prompt = "\n\n".join(f"Q: {m['q']}\nA: {m['a']}" for m in memory)
172
- context, sources, avg_sim = retrieve_context_from_chunks(question)
173
- prompt = f"Today's date is {datetime.utcnow().date()}.\n\nContext:\n{context}\n\nMemory:\n{memory_prompt}\n\nQuestion:\n{question}\n\nAnswer concisely, clearly, and grammatically:"
174
- reply = call_conversational([{"role":"user","content":prompt}], max_new_tokens=512)
175
- log = {"time":str(datetime.utcnow()), "q":question, "a":reply, "sources":sources, "embedding":embed(question).tolist()}
176
- open(LOG_FILE,"a").write(json.dumps(log)+"\n")
177
- save_embedding_to_store(log)
178
- return reply, sources, avg_sim
179
-
180
- def needs_web_search_llm(question):
181
- prompt = f'Does this need a web search? "{question}" Answer only YES or NO.'
182
- resp = call_conversational([{"role":"user","content":prompt}], max_new_tokens=10)
183
- return "YES" in resp.upper()
184
-
185
- def is_general_knowledge_question(question):
186
- prompt = f'Can this be answered with general knowledge (e.g., encyclopedia)? "{question}" YES or NO.'
187
- resp = call_conversational([{"role":"user","content":prompt}], max_new_tokens=10)
188
- return "YES" in resp.upper()
189
-
190
- def semantic_scholar_search(query, max_results=5):
191
- params = {"query":query, "fields":SEMANTIC_SCHOLAR_FIELDS, "limit":max_results}
192
- try:
193
- resp = requests.get(SEMANTIC_SCHOLAR_API, params=params, timeout=10); resp.raise_for_status()
194
- texts, urls = [], []
195
- for p in resp.json().get("data", []):
196
- entry = f"Title: {p.get('title','')}\nAuthors: {', '.join(a['name'] for a in p.get('authors',[]))}\nYear: {p.get('year','')}\nAbstract: {p.get('abstract','')}\nURL: {p.get('url','')}"
197
- texts.append(entry); urls.append(p.get('url',''))
198
- if len("\n\n".join(texts)) > MAX_CHARS:
199
- break
200
- save_chunks(query, chunk_text("\n\n".join(texts)), urls)
201
- return "\n\n".join(texts), urls
202
- except Exception:
203
- logging.warning("Semantic Scholar API error")
204
- return "", []
205
-
206
- def is_research_question(question):
207
- keywords = [
208
- "research", "study", "paper", "findings", "experiment", "scientific", "evidence", "meta-analysis",
209
- "hypothesis", "literature review", "case study", "theory", "framework", "methodology", "analysis",
210
- "data", "observation", "results", "variables", "survey", "questionnaire", "sampling", "experiment design",
211
- "quantitative", "qualitative", "mixed methods", "statistical", "inference", "regression", "correlation",
212
- "interview", "focus group", "coding", "themes", "interpretation", "reliability", "validity", "bias",
213
- "significance", "conclusion", "discussion", "implications", "limitations", "future research", "peer review",
214
- "publication", "citation", "replication", "protocol", "ethics", "IRB", "research question", "objective",
215
- "aim", "problem statement", "gap", "contribution", "novelty", "originality", "dataset", "case", "fieldwork",
216
- "observational", "experimental", "review", "systematic review", "control group", "randomized", "longitudinal",
217
- "cross-sectional", "data analysis", "research design", "conceptual", "empirical", "exploratory", "descriptive",
218
- "causal", "predictive", "construct", "operationalization", "dependent variable", "independent variable",
219
- "mediator", "moderator", "association", "impact", "effect", "relationship", "outcome", "measure", "coding scheme"
220
- ]
221
-
222
- return any(kw in question.lower() for kw in keywords)
223
-
224
- def ask(q):
225
- if is_research_question(q):
226
- context, sources = semantic_scholar_search(q)
227
- if context:
228
- answer, sources_used, _ = answer_from_context(q)
229
- else:
230
- context, sources = scrape_and_save(q)
231
- answer, sources_used, _ = answer_from_context(q)
232
- return answer, "\n".join(f"- {u}" for u in sources_used)
233
- if is_general_knowledge_question(q):
234
- return wikipedia.summary(q, sentences=3), "Source: Wikipedia"
235
- _, _, avg_sim = retrieve_context_from_chunks(q)
236
- if needs_web_search_llm(q) or avg_sim < MIN_CONTEXT_SIMILARITY:
237
- scrape_context, sources = scrape_and_save(q)
238
- answer, sources_used, _ = answer_from_context(q)
239
- return answer, "\n".join(f"- {u}" for u in sources_used)
240
- prompt = q.strip()
241
- answer = call_conversational([{"role":"user","content":prompt}], max_new_tokens=512)
242
- return answer, ""
243
-
244
- # === Gradio UI ===
245
- with gr.Blocks() as demo:
246
- gr.Markdown("""
247
- ## 🤖 LLaMA 3.1 Smart QA Bot
248
- - Uses **Wikipedia** for general knowledge
249
- - Searches **Semantic Scholar** for research
250
- - Falls back to web search when needed
251
- - Supports casual chat!
252
- """)
253
- q_input = gr.Textbox(label="Your Question")
254
- submit = gr.Button("Ask")
255
- a_output = gr.Textbox(label="Answer")
256
- s_output = gr.Markdown()
257
- submit.click(ask, inputs=q_input, outputs=[a_output, s_output])
258
-
259
- if __name__ == "__main__":
260
- if len(sys.argv) > 1:
261
- question = " ".join(sys.argv[1:])
262
- print(ask(question))
263
- else:
264
- 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
+ # === 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()