nharshavardhana commited on
Commit
239b9ce
Β·
1 Parent(s): d9b89ac
Files changed (2) hide show
  1. app.py +235 -0
  2. requirements.txt +9 -0
app.py ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing_extensions import Literal
2
+ import operator
3
+ from typing import Annotated, List, Literal, TypedDict, Any
4
+ from langgraph.graph import END, START, StateGraph
5
+ from langgraph.types import Command, interrupt
6
+ import os
7
+ import json
8
+ import re
9
+ from typing import TypedDict, List, Dict, Optional
10
+ import base64
11
+ import requests
12
+ from langchain_mistralai import ChatMistralAI
13
+ import requests
14
+ from tavily import TavilyClient
15
+ import gradio as gr
16
+
17
+
18
+ MISTRAL_API_KEY = os.getenv("MISTRAL_API_KEY")
19
+ TAVILY_API_KEY = os.getenv("TAVILY_API_KEY")
20
+
21
+
22
+
23
+ # Step 1 pipeline: Tavily search -> categorize -> (optional) summarize top items -> format output
24
+ # Requirements:
25
+ # pip install tavily-python langgraph requests
26
+
27
+ import os
28
+ import re
29
+ from typing import TypedDict, List, Dict, Any
30
+ import requests
31
+ from tavily import TavilyClient
32
+
33
+ # --- State definition for query-based pipeline ---
34
+ class State(TypedDict):
35
+ query: str
36
+ max_results: int
37
+ raw_results: List[Dict[str, Any]] # raw items returned by Tavily
38
+ categorized: Dict[str, List[Dict[str, Any]]] # buckets -> list of items
39
+ summaries: Dict[str, List[Dict[str, str]]] # bucket -> list of {url, title, summary}
40
+ final_output: str
41
+
42
+ # --- Helpers: simple domain and keyword heuristics for categorization ---
43
+ RESEARCH_DOMAINS = [
44
+ r"\.edu$", r"arxiv\.org", r"nature\.com", r"sciencemag\.org", r"ieeexplore\.ieee\.org",
45
+ r"acm\.org", r"pubmed\.ncbi\.nlm\.nih\.gov"
46
+ ]
47
+ NEWS_DOMAINS = [r"\.com$", r"\.news$", r"nytimes\.com", r"theguardian\.com", r"reuters\.com", r"bbc\.co"]
48
+ BLOG_KEYWORDS = ["blog", "opinion", "medium.com", "substack", "dev.to"]
49
+ BEGINNER_KEYWORDS = ["introduction", "what is", "beginner", "tutorial", "guide", "overview"]
50
+
51
+ def domain_matches(url: str, patterns: List[str]) -> bool:
52
+ for p in patterns:
53
+ if re.search(p, url):
54
+ return True
55
+ return False
56
+
57
+ def score_item_for_buckets(item: Dict[str, Any]) -> str:
58
+ # item expected to contain 'url' and optional 'title' and 'snippet'
59
+ url = item.get("url", "")
60
+ title = (item.get("title") or "").lower()
61
+ snippet = (item.get("snippet") or "").lower()
62
+
63
+ # research heuristics
64
+ if domain_matches(url, RESEARCH_DOMAINS) or "pdf" in url or "arxiv" in url:
65
+ return "🧠 Research / Academic"
66
+
67
+ # news heuristics
68
+ if domain_matches(url, NEWS_DOMAINS) and any(word in title+snippet for word in ["news", "breaking", "report", "update"]):
69
+ return "πŸ“° Recent News / Updates"
70
+
71
+ # blog / opinion heuristics
72
+ if any(k in url for k in BLOG_KEYWORDS) or any(k in title+snippet for k in ["opinion", "column", "blog", "i think"]):
73
+ return "πŸ’¬ Opinion / Blog / Casual"
74
+
75
+ # beginner heuristics
76
+ if any(k in title+snippet for k in BEGINNER_KEYWORDS) or "wikipedia.org" in url:
77
+ return "🌐 General / Beginner"
78
+
79
+ # fallback: decide based on domain (news-like domains often news)
80
+ if domain_matches(url, NEWS_DOMAINS):
81
+ return "πŸ“° Recent News / Updates"
82
+
83
+ # fallback default
84
+ return "🌐 General / Beginner"
85
+
86
+ # --- Node: perform Tavily search ---
87
+ def perform_search(state: State) -> State:
88
+ api_key = os.getenv("TAVILY_API_KEY")
89
+ if not api_key:
90
+ raise EnvironmentError("TAVILY_API_KEY is required in environment")
91
+
92
+ client = TavilyClient(api_key)
93
+
94
+ # βœ… Use fallback value safely
95
+ max_results = state.get("max_results", 10)
96
+
97
+ # βœ… Use the local variable instead of state["max_results"]
98
+ resp = client.search(query=state["query"], max_results=max_results)
99
+
100
+ # The exact shape depends on Tavily client; adapt below if fields differ
101
+ items: List[Dict[str, Any]] = []
102
+ for r in resp.get("results", resp)[:max_results]:
103
+ url = r.get("url") or r.get("link") or r.get("document_url") or r.get("source")
104
+ title = r.get("title") or r.get("headline") or ""
105
+ snippet = r.get("snippet") or r.get("summary") or r.get("excerpt") or r.get("text") or ""
106
+ items.append({"url": url, "title": title, "snippet": snippet, "raw": r})
107
+
108
+ return {**state, "raw_results": items}
109
+
110
+ # --- Node: categorize results into the four buckets ---
111
+ def categorize_results(state: State) -> State:
112
+ buckets = {
113
+ "🧠 Research / Academic": [],
114
+ "🌐 General / Beginner": [],
115
+ "πŸ“° Recent News / Updates": [],
116
+ "πŸ’¬ Opinion / Blog / Casual": []
117
+ }
118
+ for item in state["raw_results"]:
119
+ bucket = score_item_for_buckets(item)
120
+ buckets.setdefault(bucket, []).append(item)
121
+ return {**state, "categorized": buckets}
122
+
123
+ # --- Node: summarize top N items per bucket using Mistral ---
124
+ MISTRAL_API_KEY = os.getenv("MISTRAL_API_KEY")
125
+ MISTRAL_MODEL = "mistral-large-latest"
126
+
127
+ def summarize_top_items(state: State, top_n: int = 3) -> State:
128
+ if not MISTRAL_API_KEY:
129
+ # If no key, gracefully skip summarization and return empty summaries
130
+ return {**state, "summaries": {k: [{"url": it["url"], "title": it["title"], "summary": ""} for it in v[:top_n]] for k,v in state["categorized"].items()}}
131
+
132
+ headers = {
133
+ "Authorization": f"Bearer {MISTRAL_API_KEY}",
134
+ "Content-Type": "application/json"
135
+ }
136
+
137
+ summaries: Dict[str, List[Dict[str,str]]] = {}
138
+ for bucket, items in state["categorized"].items():
139
+ bucket_summaries = []
140
+ for it in items[:top_n]:
141
+ prompt = f"""
142
+ You are an assistant that summarizes webpages. Provide a short (1-2 sentence) summary for the following item.
143
+ Return only JSON with keys: title, url, summary.
144
+
145
+ Title: {it.get('title')}
146
+ URL: {it.get('url')}
147
+ Snippet/Excerpt: {it.get('snippet')}
148
+
149
+ If snippet is missing, make a short summary that says "no snippet available".
150
+ """
151
+ body = {
152
+ "model": MISTRAL_MODEL,
153
+ "messages": [{"role": "user", "content": prompt}],
154
+ "temperature": 0.0,
155
+ "max_tokens": 200
156
+ }
157
+ try:
158
+ r = requests.post("https://api.mistral.ai/v1/chat/completions", headers=headers, json=body, timeout=15)
159
+ r.raise_for_status()
160
+ content = r.json()["choices"][0]["message"]["content"]
161
+ # Expecting JSON back; be conservative with parsing:
162
+ try:
163
+ parsed = eval(content) if content.strip().startswith("{") else {"title": it.get("title"), "url": it.get("url"), "summary": content.strip()}
164
+ except Exception:
165
+ parsed = {"title": it.get("title"), "url": it.get("url"), "summary": content.strip()}
166
+ except Exception as e:
167
+ parsed = {"title": it.get("title"), "url": it.get("url"), "summary": f"(summary failed: {e})"}
168
+ bucket_summaries.append(parsed)
169
+ summaries[bucket] = bucket_summaries
170
+ return {**state, "summaries": summaries}
171
+
172
+ # --- Node: format final output ---
173
+ def format_output(state: State) -> State:
174
+ out_lines = [f"πŸ”Ž Query: {state['query']}", ""]
175
+ for bucket, items in state["categorized"].items():
176
+ out_lines.append(f"## {bucket} β€” {len(items)} results")
177
+ summaries = state.get("summaries", {}).get(bucket, [])
178
+ if summaries:
179
+ for s in summaries:
180
+ title = s.get("title") or "(no title)"
181
+ url = s.get("url") or "(no url)"
182
+ summary = s.get("summary") or ""
183
+ out_lines.append(f"- {title}\n {url}\n {summary}")
184
+ else:
185
+ # fall back to listing basic items
186
+ for it in items[:5]:
187
+ out_lines.append(f"- {it.get('title') or '(no title)'} β€” {it.get('url')}\n {it.get('snippet') or ''}")
188
+ out_lines.append("")
189
+ final = "\n".join(out_lines)
190
+ return {**state, "final_output": final}
191
+
192
+ # --- LangGraph wiring (example, mimic your earlier code) ---
193
+ # If you use langgraph exactly as in your example, adapt this snippet:
194
+
195
+ builder = StateGraph(State)
196
+ builder.add_node("perform_search", perform_search)
197
+ builder.add_node("categorize_results", categorize_results)
198
+ builder.add_node("summarize_top_items", summarize_top_items)
199
+ builder.add_node("format_output", format_output)
200
+ builder.set_entry_point("perform_search")
201
+ builder.add_edge("perform_search", "categorize_results")
202
+ builder.add_edge("categorize_results", "summarize_top_items")
203
+ builder.add_edge("summarize_top_items", "format_output")
204
+
205
+ graph = builder.compile()
206
+
207
+ def analyze_text(input_text: str):
208
+ try:
209
+ state = {"query": input_text}
210
+ result = graph.invoke(state)
211
+
212
+ if "error" in result:
213
+ return f"❌ Error: {result['error']}"
214
+
215
+ if "final_output" in result:
216
+ return result["final_output"]
217
+
218
+ return "⚠️ No summary generated. Please check the input text and try again."
219
+ except Exception as e:
220
+ return f"⚠️ Exception: {str(e)}"
221
+
222
+
223
+ iface = gr.Interface(
224
+ fn=analyze_text,
225
+ inputs=gr.Textbox(label="πŸ”— Enter any text that you need information"),
226
+ outputs=gr.Textbox(label="πŸ“‹ search Summary", lines=15),
227
+ title="πŸ€– InfoSort",
228
+ description="searches, sorts, summarizes."
229
+ )
230
+ iface.launch(share=True)
231
+
232
+
233
+
234
+
235
+
requirements.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ gradio
2
+ requests
3
+ langchain
4
+ langgraph
5
+ langchain_community
6
+ langchain_mistralai
7
+ mistralai
8
+ typing_extensions
9
+ tavily