Spaces:
Sleeping
Sleeping
Update app.py
Browse files
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 |
-
|
|
|
|
|
|
|
| 22 |
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
|
|
|
| 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 |
-
|
| 33 |
-
|
| 34 |
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
return bmj
|
| 38 |
-
|
| 39 |
-
print("β οΈ Fallback to general results")
|
| 40 |
-
return items
|
| 41 |
|
| 42 |
except Exception as e:
|
| 43 |
-
print("
|
| 44 |
return []
|
| 45 |
|
| 46 |
|
| 47 |
# ---------------- SCRAPER ---------------- #
|
| 48 |
def extract_text(url):
|
| 49 |
try:
|
| 50 |
-
|
| 51 |
-
|
|
|
|
| 52 |
|
| 53 |
-
|
| 54 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
|
| 56 |
return text[:3000]
|
| 57 |
-
|
|
|
|
|
|
|
| 58 |
return ""
|
| 59 |
|
| 60 |
|
| 61 |
# ---------------- HF SUMMARY ---------------- #
|
| 62 |
def summarize(text):
|
|
|
|
|
|
|
|
|
|
| 63 |
try:
|
| 64 |
headers = {"Authorization": f"Bearer {HF_TOKEN}"}
|
| 65 |
-
|
| 66 |
-
|
|
|
|
|
|
|
| 67 |
|
| 68 |
-
if isinstance(
|
| 69 |
-
return
|
| 70 |
|
| 71 |
return "Summary not available."
|
| 72 |
-
|
|
|
|
|
|
|
| 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 "β
|
|
|
|
|
|
|
|
|
|
| 80 |
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
print("Search:", search_query)
|
| 84 |
|
| 85 |
-
results =
|
| 86 |
|
| 87 |
if not results:
|
| 88 |
return "β No courses found. Try different keywords."
|
| 89 |
|
| 90 |
-
|
| 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 |
-
|
| 100 |
|
| 101 |
-
|
| 102 |
-
best_text = text
|
| 103 |
-
best_url = url
|
| 104 |
-
best_title = title
|
| 105 |
-
break
|
| 106 |
|
| 107 |
-
|
| 108 |
-
|
| 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 |
-
|
| 115 |
|
| 116 |
-
|
| 117 |
-
### π
|
| 118 |
-
**{best_title}**
|
| 119 |
|
| 120 |
-
|
| 121 |
-
{best_url}
|
| 122 |
|
| 123 |
-
|
| 124 |
-
{summary}
|
| 125 |
"""
|
|
|
|
| 126 |
|
|
|
|
| 127 |
log_interaction({
|
| 128 |
"timestamp": datetime.now(UTC).isoformat(),
|
| 129 |
-
"
|
| 130 |
-
"
|
|
|
|
|
|
|
|
|
|
| 131 |
})
|
| 132 |
|
| 133 |
-
return
|
| 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 (
|
| 160 |
|
| 161 |
with gr.Tab("Course Finder"):
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 167 |
|
|
|
|
| 168 |
output = gr.Markdown()
|
| 169 |
|
| 170 |
-
gr.Button("Find Course")
|
| 171 |
-
|
|
|
|
|
|
|
| 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()
|