abhidgp1978 commited on
Commit
2ddeb0e
Β·
verified Β·
1 Parent(s): 9af01eb

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +107 -83
app.py CHANGED
@@ -3,143 +3,150 @@ import json
3
  import requests
4
  import nltk
5
  import re
6
- from nltk.corpus import stopwords
7
- from nltk.tokenize import word_tokenize, sent_tokenize
8
  import gradio as gr
9
  from datetime import datetime, UTC
10
  from bs4 import BeautifulSoup
11
 
 
12
  nltk.download("punkt")
13
  nltk.download("stopwords")
14
 
15
  HF_TOKEN = os.getenv("HF_TOKEN")
 
 
16
  HF_API = "https://api-inference.huggingface.co/models/facebook/bart-large-cnn"
 
17
 
18
- GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
19
- SEARCH_ENGINE_ID = os.getenv("SEARCH_ENGINE_ID")
20
 
21
- LOG_FILE_PATH = "user_query.jsonl"
 
 
22
 
23
- stop_words = set(stopwords.words("english"))
24
- custom_stop = {"looking", "need", "want", "searching", "course", "learn"}
25
- all_stops = stop_words.union(custom_stop)
 
26
 
 
 
 
 
27
 
28
- # ---------------- SEARCH ---------------- #
29
- def google_search(query, num_results=5):
30
- url = f"https://www.googleapis.com/customsearch/v1?key={GOOGLE_API_KEY}&cx={SEARCH_ENGINE_ID}&q={query}&num={num_results}"
31
  try:
32
- res = requests.get(url).json()
33
- items = res.get("items", [])
34
 
35
- bmj = [i for i in items if "educationindia.bmj.com" in i.get("link", "")]
36
- if bmj:
37
- return bmj
38
-
39
- print("⚠️ Fallback to general results")
40
- return items
41
 
42
  except Exception as e:
43
- print("Search error:", e)
44
  return []
45
 
46
 
47
  # ---------------- SCRAPER ---------------- #
48
  def extract_text(url):
49
  try:
50
- r = requests.get(url, timeout=10)
51
- soup = BeautifulSoup(r.text, "html.parser")
 
52
 
53
- paragraphs = soup.find_all("p")
54
- text = " ".join(p.get_text(strip=True) for p in paragraphs)
 
 
 
 
55
 
56
  return text[:3000]
57
- except:
 
 
58
  return ""
59
 
60
 
61
  # ---------------- HF SUMMARY ---------------- #
62
  def summarize(text):
 
 
 
63
  try:
64
  headers = {"Authorization": f"Bearer {HF_TOKEN}"}
65
- res = requests.post(HF_API, headers=headers, json={"inputs": text})
66
- out = res.json()
 
 
67
 
68
- if isinstance(out, list) and "summary_text" in out[0]:
69
- return out[0]["summary_text"]
70
 
71
  return "Summary not available."
72
- except:
 
 
73
  return "AI summary failed."
74
 
75
 
 
 
 
 
 
 
 
 
 
76
  # ---------------- COURSE AGENT ---------------- #
77
  def course_agent(name, email, location, profession, query):
78
  if not query.strip():
79
- return "❗ Enter a course topic."
 
 
 
80
 
81
- # βœ… Better query (no over-filtering)
82
- search_query = f"{query} medical course BMJ OR healthcare training"
83
- print("Search:", search_query)
84
 
85
- results = google_search(search_query)
86
 
87
  if not results:
88
  return "❌ No courses found. Try different keywords."
89
 
90
- best_text = ""
91
- best_url = ""
92
- best_title = ""
93
 
94
- # βœ… Try top 3 results
95
  for item in results[:3]:
 
96
  url = item.get("link", "")
97
- title = item.get("title", "")
98
 
99
- text = extract_text(url)
100
 
101
- if text and len(text) > 200:
102
- best_text = text
103
- best_url = url
104
- best_title = title
105
- break
106
 
107
- # βœ… Fallback if scraping fails
108
- if not best_text:
109
- item = results[0]
110
- best_url = item.get("link", "")
111
- best_title = item.get("title", "")
112
- best_text = f"{best_title} {best_url}"
113
 
114
- summary = summarize(best_text)
115
 
116
- result = f"""
117
- ### πŸ“˜ Course
118
- **{best_title}**
119
 
120
- ### πŸ”— Link
121
- {best_url}
122
 
123
- ### 🧠 Summary & ROI
124
- {summary}
125
  """
 
126
 
 
127
  log_interaction({
128
  "timestamp": datetime.now(UTC).isoformat(),
129
- "query": query,
130
- "result": result
 
 
 
131
  })
132
 
133
- return result
134
-
135
-
136
- # ---------------- LOGGING ---------------- #
137
- def log_interaction(data):
138
- try:
139
- with open(LOG_FILE_PATH, "a") as f:
140
- f.write(json.dumps(data) + "\n")
141
- except:
142
- pass
143
 
144
 
145
  # ---------------- CHAT ---------------- #
@@ -151,32 +158,49 @@ def chat_fn(message, history):
151
  history.append({"role": "user", "content": message})
152
  history.append({"role": "assistant", "content": reply})
153
 
 
 
 
 
 
 
 
154
  return history
155
 
156
 
157
  # ---------------- UI ---------------- #
158
- with gr.Blocks(title="AI Course Finder") as demo:
159
- gr.Markdown("# 🧠 AI Course Finder (Reliable Version)")
160
 
161
  with gr.Tab("Course Finder"):
162
- name = gr.Textbox(label="Name")
163
- email = gr.Textbox(label="Email")
164
- location = gr.Textbox(label="Location")
165
- profession = gr.Dropdown(["Student", "Doctor", "Nurse", "Other"], value="Student")
166
- query = gr.Textbox(label="Search Course")
 
 
 
 
 
167
 
 
168
  output = gr.Markdown()
169
 
170
- gr.Button("Find Course").click(
171
- course_agent,
 
 
172
  inputs=[name, email, location, profession, query],
173
  outputs=output
174
  )
175
 
176
  with gr.Tab("Chat"):
 
 
177
  chatbot = gr.Chatbot(type="messages")
178
- msg = gr.Textbox()
179
 
180
- msg.submit(chat_fn, [msg, chatbot], chatbot)
181
 
182
  demo.launch()
 
3
  import requests
4
  import nltk
5
  import re
 
 
6
  import gradio as gr
7
  from datetime import datetime, UTC
8
  from bs4 import BeautifulSoup
9
 
10
+ # ---------------- SETUP ---------------- #
11
  nltk.download("punkt")
12
  nltk.download("stopwords")
13
 
14
  HF_TOKEN = os.getenv("HF_TOKEN")
15
+ SERPER_API_KEY = os.getenv("SERPER_API_KEY")
16
+
17
  HF_API = "https://api-inference.huggingface.co/models/facebook/bart-large-cnn"
18
+ LOG_FILE_PATH = "user_query.jsonl"
19
 
 
 
20
 
21
+ # ---------------- SERPER SEARCH ---------------- #
22
+ def serper_search(query, num_results=5):
23
+ url = "https://google.serper.dev/search"
24
 
25
+ payload = {
26
+ "q": query,
27
+ "num": num_results
28
+ }
29
 
30
+ headers = {
31
+ "X-API-KEY": SERPER_API_KEY,
32
+ "Content-Type": "application/json"
33
+ }
34
 
 
 
 
35
  try:
36
+ response = requests.post(url, headers=headers, json=payload)
37
+ data = response.json()
38
 
39
+ results = data.get("organic", [])
40
+ return results
 
 
 
 
41
 
42
  except Exception as e:
43
+ print("❌ Serper error:", e)
44
  return []
45
 
46
 
47
  # ---------------- SCRAPER ---------------- #
48
  def extract_text(url):
49
  try:
50
+ response = requests.get(url, timeout=10)
51
+
52
+ soup = BeautifulSoup(response.text, "html.parser")
53
 
54
+ # Remove unwanted tags
55
+ for tag in soup(["script", "style", "nav", "footer", "header"]):
56
+ tag.extract()
57
+
58
+ text = soup.get_text(separator=" ")
59
+ text = re.sub(r"\s+", " ", text)
60
 
61
  return text[:3000]
62
+
63
+ except Exception as e:
64
+ print("❌ Scrape error:", e)
65
  return ""
66
 
67
 
68
  # ---------------- HF SUMMARY ---------------- #
69
  def summarize(text):
70
+ if not HF_TOKEN:
71
+ return "⚠️ Missing HF_TOKEN. Cannot generate summary."
72
+
73
  try:
74
  headers = {"Authorization": f"Bearer {HF_TOKEN}"}
75
+ payload = {"inputs": text}
76
+
77
+ response = requests.post(HF_API, headers=headers, json=payload)
78
+ output = response.json()
79
 
80
+ if isinstance(output, list) and "summary_text" in output[0]:
81
+ return output[0]["summary_text"]
82
 
83
  return "Summary not available."
84
+
85
+ except Exception as e:
86
+ print("❌ HF error:", e)
87
  return "AI summary failed."
88
 
89
 
90
+ # ---------------- LOGGING ---------------- #
91
+ def log_interaction(data):
92
+ try:
93
+ with open(LOG_FILE_PATH, "a") as f:
94
+ f.write(json.dumps(data) + "\n")
95
+ except Exception as e:
96
+ print("❌ Logging error:", e)
97
+
98
+
99
  # ---------------- COURSE AGENT ---------------- #
100
  def course_agent(name, email, location, profession, query):
101
  if not query.strip():
102
+ return "❗ Please enter a course topic."
103
+
104
+ if not SERPER_API_KEY:
105
+ return "❌ SERPER_API_KEY is missing."
106
 
107
+ search_query = f"{query} course for doctors OR nurses OR healthcare certification"
108
+ print("πŸ” Search Query:", search_query)
 
109
 
110
+ results = serper_search(search_query)
111
 
112
  if not results:
113
  return "❌ No courses found. Try different keywords."
114
 
115
+ output_blocks = []
 
 
116
 
 
117
  for item in results[:3]:
118
+ title = item.get("title", "No title")
119
  url = item.get("link", "")
 
120
 
121
+ print("➑️ Processing:", url)
122
 
123
+ text = extract_text(url)
 
 
 
 
124
 
125
+ if not text or len(text) < 200:
126
+ text = f"{title}. {url}"
 
 
 
 
127
 
128
+ summary = summarize(text)
129
 
130
+ block = f"""
131
+ ### πŸ“˜ {title}
 
132
 
133
+ πŸ”— {url}
 
134
 
135
+ 🧠 {summary}
 
136
  """
137
+ output_blocks.append(block)
138
 
139
+ # Log interaction
140
  log_interaction({
141
  "timestamp": datetime.now(UTC).isoformat(),
142
+ "name": name,
143
+ "email": email,
144
+ "location": location,
145
+ "profession": profession,
146
+ "query": query
147
  })
148
 
149
+ return "\n\n---\n\n".join(output_blocks)
 
 
 
 
 
 
 
 
 
150
 
151
 
152
  # ---------------- CHAT ---------------- #
 
158
  history.append({"role": "user", "content": message})
159
  history.append({"role": "assistant", "content": reply})
160
 
161
+ log_interaction({
162
+ "timestamp": datetime.now(UTC).isoformat(),
163
+ "role": "chat",
164
+ "message": message,
165
+ "response": reply
166
+ })
167
+
168
  return history
169
 
170
 
171
  # ---------------- UI ---------------- #
172
+ with gr.Blocks(title="🧠 AI Course Finder (Serper Powered)") as demo:
173
+ gr.Markdown("# 🧠 AI Course Finder (Serper + HF)")
174
 
175
  with gr.Tab("Course Finder"):
176
+ with gr.Row():
177
+ name = gr.Textbox(label="Name")
178
+ email = gr.Textbox(label="Email")
179
+ location = gr.Textbox(label="Location")
180
+
181
+ profession = gr.Dropdown(
182
+ ["Student", "Doctor", "Nurse", "Other"],
183
+ value="Student",
184
+ label="Profession"
185
+ )
186
 
187
+ query = gr.Textbox(label="Search Course Topic")
188
  output = gr.Markdown()
189
 
190
+ search_btn = gr.Button("Find Course")
191
+
192
+ search_btn.click(
193
+ fn=course_agent,
194
  inputs=[name, email, location, profession, query],
195
  outputs=output
196
  )
197
 
198
  with gr.Tab("Chat"):
199
+ gr.Markdown("## πŸ’¬ Chat Assistant")
200
+
201
  chatbot = gr.Chatbot(type="messages")
202
+ msg = gr.Textbox(placeholder="Ask anything...")
203
 
204
+ msg.submit(chat_fn, inputs=[msg, chatbot], outputs=chatbot)
205
 
206
  demo.launch()