Spaces:
Sleeping
Sleeping
File size: 5,140 Bytes
3e89be4 e716386 4b930d4 2394331 bb6e7a7 e716386 e00ac15 0c65a00 0aecac5 2ddeb0e 3e89be4 8f6dd8d 2ddeb0e 9af01eb 2ddeb0e 9af01eb e716386 2ddeb0e 427a9e8 2ddeb0e 9ad81dc 2ddeb0e 0c65a00 e716386 2ddeb0e e716386 2ddeb0e 0c65a00 2ddeb0e 9af01eb 0c65a00 e00ac15 9af01eb e716386 2ddeb0e e00ac15 2ddeb0e e00ac15 9af01eb 2ddeb0e 9af01eb e716386 0c65a00 9af01eb 2ddeb0e e716386 9af01eb 2ddeb0e bb6e7a7 2ddeb0e bb6e7a7 9af01eb 2ddeb0e 9af01eb bb6e7a7 2ddeb0e 9af01eb 2ddeb0e bb6e7a7 2ddeb0e a36375c 2ddeb0e e00ac15 9af01eb a36375c 2ddeb0e a36375c 9af01eb 2ddeb0e 9af01eb dc388c2 2ddeb0e e716386 2ddeb0e e00ac15 2ddeb0e e00ac15 2ddeb0e e00ac15 2ddeb0e 0c65a00 2ddeb0e bb6e7a7 2ddeb0e e00ac15 2ddeb0e e716386 2ddeb0e e00ac15 2ddeb0e e00ac15 e716386 2ddeb0e 9af01eb e00ac15 9af01eb e00ac15 9af01eb e716386 2ddeb0e e00ac15 0c65a00 e00ac15 9af01eb 2ddeb0e e716386 2ddeb0e 9af01eb 2ddeb0e 9af01eb e716386 2ddeb0e e00ac15 9af01eb e00ac15 e716386 2ddeb0e 9af01eb 2ddeb0e e00ac15 2ddeb0e 30188f3 e00ac15 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 | import os
import json
import requests
import nltk
import re
import gradio as gr
from datetime import datetime, UTC
from bs4 import BeautifulSoup
# ---------------- SETUP ---------------- #
nltk.download("punkt")
nltk.download("stopwords")
HF_TOKEN = os.getenv("HF_TOKEN")
SERPER_API_KEY = os.getenv("SERPER_API_KEY")
HF_API = "https://api-inference.huggingface.co/models/facebook/bart-large-cnn"
LOG_FILE_PATH = "user_query.jsonl"
# ---------------- SERPER SEARCH ---------------- #
def serper_search(query, num_results=5):
url = "https://google.serper.dev/search"
payload = {
"q": query,
"num": num_results
}
headers = {
"X-API-KEY": SERPER_API_KEY,
"Content-Type": "application/json"
}
try:
response = requests.post(url, headers=headers, json=payload)
data = response.json()
results = data.get("organic", [])
return results
except Exception as e:
print("β Serper error:", e)
return []
# ---------------- SCRAPER ---------------- #
def extract_text(url):
try:
response = requests.get(url, timeout=10)
soup = BeautifulSoup(response.text, "html.parser")
# Remove unwanted tags
for tag in soup(["script", "style", "nav", "footer", "header"]):
tag.extract()
text = soup.get_text(separator=" ")
text = re.sub(r"\s+", " ", text)
return text[:3000]
except Exception as e:
print("β Scrape error:", e)
return ""
# ---------------- HF SUMMARY ---------------- #
def summarize(text):
if not HF_TOKEN:
return "β οΈ Missing HF_TOKEN. Cannot generate summary."
try:
headers = {"Authorization": f"Bearer {HF_TOKEN}"}
payload = {"inputs": text}
response = requests.post(HF_API, headers=headers, json=payload)
output = response.json()
if isinstance(output, list) and "summary_text" in output[0]:
return output[0]["summary_text"]
return "Summary not available."
except Exception as e:
print("β HF error:", e)
return "AI summary failed."
# ---------------- LOGGING ---------------- #
def log_interaction(data):
try:
with open(LOG_FILE_PATH, "a") as f:
f.write(json.dumps(data) + "\n")
except Exception as e:
print("β Logging error:", e)
# ---------------- COURSE AGENT ---------------- #
def course_agent(name, email, location, profession, query):
if not query.strip():
return "β Please enter a course topic."
if not SERPER_API_KEY:
return "β SERPER_API_KEY is missing."
search_query = f"{query} course for doctors OR nurses OR healthcare certification"
print("π Search Query:", search_query)
results = serper_search(search_query)
if not results:
return "β No courses found. Try different keywords."
output_blocks = []
for item in results[:3]:
title = item.get("title", "No title")
url = item.get("link", "")
print("β‘οΈ Processing:", url)
text = extract_text(url)
if not text or len(text) < 200:
text = f"{title}. {url}"
summary = summarize(text)
block = f"""
### π {title}
π {url}
π§ {summary}
"""
output_blocks.append(block)
# Log interaction
log_interaction({
"timestamp": datetime.now(UTC).isoformat(),
"name": name,
"email": email,
"location": location,
"profession": profession,
"query": query
})
return "\n\n---\n\n".join(output_blocks)
# ---------------- CHAT ---------------- #
def chat_fn(message, history):
history = history or []
reply = f"Echo: {message}"
history.append({"role": "user", "content": message})
history.append({"role": "assistant", "content": reply})
log_interaction({
"timestamp": datetime.now(UTC).isoformat(),
"role": "chat",
"message": message,
"response": reply
})
return history
# ---------------- UI ---------------- #
with gr.Blocks(title="π§ AI Course Finder (Serper Powered)") as demo:
gr.Markdown("# π§ AI Course Finder (Serper + HF)")
with gr.Tab("Course Finder"):
with gr.Row():
name = gr.Textbox(label="Name")
email = gr.Textbox(label="Email")
location = gr.Textbox(label="Location")
profession = gr.Dropdown(
["Student", "Doctor", "Nurse", "Other"],
value="Student",
label="Profession"
)
query = gr.Textbox(label="Search Course Topic")
output = gr.Markdown()
search_btn = gr.Button("Find Course")
search_btn.click(
fn=course_agent,
inputs=[name, email, location, profession, query],
outputs=output
)
with gr.Tab("Chat"):
gr.Markdown("## π¬ Chat Assistant")
chatbot = gr.Chatbot(type="messages")
msg = gr.Textbox(placeholder="Ask anything...")
msg.submit(chat_fn, inputs=[msg, chatbot], outputs=chatbot)
demo.launch() |