Spaces:
Sleeping
Sleeping
Download app.py from abhidgp1978/agentchat: direct link, hf CLI and curl.
- Browser
- Download file 5.14 kB
-
https://huggingface.co/spaces/abhidgp1978/agentchat/resolve/main/app.py
- Command line
-
hf download hf://spaces/abhidgp1978/agentchat/app.py
-
curl -L -o app.py https://huggingface.co/spaces/abhidgp1978/agentchat/resolve/main/app.py
5.14 kB
| 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() |