Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -5,72 +5,53 @@ import os
|
|
| 5 |
import re
|
| 6 |
import requests
|
| 7 |
import nltk
|
| 8 |
-
|
| 9 |
from nltk.corpus import stopwords
|
| 10 |
from nltk.tokenize import word_tokenize
|
| 11 |
-
|
| 12 |
from memory_store import log_chat, build_or_update_index, search_similar
|
| 13 |
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
os.makedirs(NLTK_DATA_DIR, exist_ok=True)
|
| 17 |
-
nltk.download("punkt", download_dir=NLTK_DATA_DIR, force=True)
|
| 18 |
-
nltk.download("stopwords", download_dir=NLTK_DATA_DIR, force=True)
|
| 19 |
-
nltk.data.path = [NLTK_DATA_DIR]
|
| 20 |
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
SEARCH_ENGINE_ID = os.getenv("17357d675fc704764", "") # Add in Space secrets
|
| 24 |
COURSE_DB_PATH = "mock_courses.json"
|
| 25 |
|
| 26 |
-
#
|
| 27 |
if os.path.exists(COURSE_DB_PATH):
|
| 28 |
with open(COURSE_DB_PATH, "r") as f:
|
| 29 |
linkedin_courses = json.load(f)
|
| 30 |
else:
|
| 31 |
linkedin_courses = []
|
| 32 |
|
| 33 |
-
#
|
| 34 |
def extract_keywords(text):
|
| 35 |
stop_words = set(stopwords.words("english"))
|
| 36 |
words = word_tokenize(text.lower())
|
| 37 |
return [w for w in words if w.isalnum() and w not in stop_words]
|
| 38 |
|
| 39 |
-
#
|
| 40 |
-
def google_search(query, num_results=
|
| 41 |
if not GOOGLE_API_KEY or not SEARCH_ENGINE_ID:
|
| 42 |
-
return None
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
course_sites = [
|
| 46 |
-
"site:linkedin.com/learning",
|
| 47 |
-
"site:udemy.com",
|
| 48 |
-
"site:edx.org",
|
| 49 |
-
"site:coursera.org",
|
| 50 |
-
"site:bmj.com",
|
| 51 |
-
"site:futurelearn.com"
|
| 52 |
-
]
|
| 53 |
-
filter_query = " OR ".join(course_sites)
|
| 54 |
-
final_query = f"{query} ({filter_query})"
|
| 55 |
-
|
| 56 |
-
api_url = f"https://www.googleapis.com/customsearch/v1?key={GOOGLE_API_KEY}&cx={SEARCH_ENGINE_ID}&q={final_query}"
|
| 57 |
|
| 58 |
try:
|
| 59 |
response = requests.get(api_url)
|
| 60 |
data = response.json()
|
| 61 |
items = data.get("items", [])
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
"
|
| 66 |
-
"
|
| 67 |
-
|
|
|
|
| 68 |
except Exception as e:
|
| 69 |
print(f"Google Search Error: {e}")
|
| 70 |
-
|
| 71 |
return None
|
| 72 |
|
| 73 |
-
#
|
| 74 |
def course_agent(profession, query):
|
| 75 |
if not query:
|
| 76 |
return "β Please enter a course or topic."
|
|
@@ -79,34 +60,41 @@ def course_agent(profession, query):
|
|
| 79 |
if not keywords:
|
| 80 |
return "β Could not extract keywords."
|
| 81 |
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
|
| 93 |
log_chat(f"[CourseFinder][{profession}] {query}", result)
|
| 94 |
build_or_update_index(profession, query, result)
|
| 95 |
return result
|
| 96 |
|
| 97 |
-
#
|
| 98 |
def chat_with_user(message, history):
|
| 99 |
answer = f"Echo: {message}"
|
| 100 |
log_chat(message, answer)
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
], ""
|
| 105 |
|
| 106 |
-
# === UI ===
|
| 107 |
-
with gr.Blocks(title="π§ AI Course Finder with
|
| 108 |
with gr.Tab("Course Finder"):
|
| 109 |
-
gr.Markdown("## π Smart Agent with FAISS
|
| 110 |
with gr.Row():
|
| 111 |
profession = gr.Dropdown(["Student", "Doctor", "Nurse", "Developer", "Engineer", "Manager", "Other"],
|
| 112 |
label="π€ Profession", value="Student")
|
|
@@ -114,11 +102,14 @@ with gr.Blocks(title="π§ AI Course Finder with Self-Learning") as demo:
|
|
| 114 |
search_btn = gr.Button("π― Search")
|
| 115 |
result_box = gr.Textbox(label="π Result", lines=4)
|
| 116 |
|
| 117 |
-
|
|
|
|
|
|
|
|
|
|
| 118 |
|
| 119 |
with gr.Tab("Chat"):
|
| 120 |
chatbot = gr.Chatbot(label="Chat", type="messages")
|
| 121 |
txt = gr.Textbox(show_label=False, placeholder="Type your message...")
|
| 122 |
txt.submit(chat_with_user, [txt, chatbot], [chatbot, txt])
|
| 123 |
|
| 124 |
-
|
|
|
|
| 5 |
import re
|
| 6 |
import requests
|
| 7 |
import nltk
|
|
|
|
| 8 |
from nltk.corpus import stopwords
|
| 9 |
from nltk.tokenize import word_tokenize
|
|
|
|
| 10 |
from memory_store import log_chat, build_or_update_index, search_similar
|
| 11 |
|
| 12 |
+
nltk.download("punkt")
|
| 13 |
+
nltk.download("stopwords")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
|
| 15 |
+
GOOGLE_API_KEY = "AIzaSyCgOaCQEVvOuNtZhOkrmcnqzuiiPDA6b1Q" # π Replace this
|
| 16 |
+
SEARCH_ENGINE_ID = "17357d675fc704764" # π Replace this
|
|
|
|
| 17 |
COURSE_DB_PATH = "mock_courses.json"
|
| 18 |
|
| 19 |
+
# Load local LinkedIn course data
|
| 20 |
if os.path.exists(COURSE_DB_PATH):
|
| 21 |
with open(COURSE_DB_PATH, "r") as f:
|
| 22 |
linkedin_courses = json.load(f)
|
| 23 |
else:
|
| 24 |
linkedin_courses = []
|
| 25 |
|
| 26 |
+
# NLTK-based keyword extraction
|
| 27 |
def extract_keywords(text):
|
| 28 |
stop_words = set(stopwords.words("english"))
|
| 29 |
words = word_tokenize(text.lower())
|
| 30 |
return [w for w in words if w.isalnum() and w not in stop_words]
|
| 31 |
|
| 32 |
+
# Google search (then filter)
|
| 33 |
+
def google_search(query, num_results=5):
|
| 34 |
if not GOOGLE_API_KEY or not SEARCH_ENGINE_ID:
|
| 35 |
+
return None
|
| 36 |
+
|
| 37 |
+
api_url = f"https://www.googleapis.com/customsearch/v1?key={GOOGLE_API_KEY}&cx={SEARCH_ENGINE_ID}&q={query}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
|
| 39 |
try:
|
| 40 |
response = requests.get(api_url)
|
| 41 |
data = response.json()
|
| 42 |
items = data.get("items", [])
|
| 43 |
+
for item in items[:num_results]:
|
| 44 |
+
link = item.get("link", "")
|
| 45 |
+
if any(domain in link for domain in [
|
| 46 |
+
"linkedin.com/learning", "udemy.com", "edx.org",
|
| 47 |
+
"coursera.org", "bmj.com", "futurelearn.com"
|
| 48 |
+
]):
|
| 49 |
+
return {"title": item.get("title", "No Title"), "url": link}
|
| 50 |
except Exception as e:
|
| 51 |
print(f"Google Search Error: {e}")
|
|
|
|
| 52 |
return None
|
| 53 |
|
| 54 |
+
# Core course agent
|
| 55 |
def course_agent(profession, query):
|
| 56 |
if not query:
|
| 57 |
return "β Please enter a course or topic."
|
|
|
|
| 60 |
if not keywords:
|
| 61 |
return "β Could not extract keywords."
|
| 62 |
|
| 63 |
+
is_tech = any(p in profession.lower() for p in [
|
| 64 |
+
"developer", "engineer", "analyst", "manager", "student", "it", "business"
|
| 65 |
+
])
|
| 66 |
+
|
| 67 |
+
result = None
|
| 68 |
+
if is_tech:
|
| 69 |
+
titles = [course["title"] for course in linkedin_courses]
|
| 70 |
+
match = difflib.get_close_matches(" ".join(keywords), titles, n=1, cutoff=0.4)
|
| 71 |
+
if match:
|
| 72 |
+
course = next(c for c in linkedin_courses if c["title"] == match[0])
|
| 73 |
+
result = f"β
Found on LinkedIn:\n{course['title']} - {course['url']}"
|
| 74 |
+
|
| 75 |
+
if not result:
|
| 76 |
+
g_result = google_search(" ".join(keywords) + " course")
|
| 77 |
+
if g_result:
|
| 78 |
+
result = f"π Found via Google:\n{g_result['title']} - {g_result['url']}"
|
| 79 |
+
else:
|
| 80 |
+
result = "β No relevant course found."
|
| 81 |
|
| 82 |
log_chat(f"[CourseFinder][{profession}] {query}", result)
|
| 83 |
build_or_update_index(profession, query, result)
|
| 84 |
return result
|
| 85 |
|
| 86 |
+
# General chat fallback
|
| 87 |
def chat_with_user(message, history):
|
| 88 |
answer = f"Echo: {message}"
|
| 89 |
log_chat(message, answer)
|
| 90 |
+
history.append({"role": "user", "content": message})
|
| 91 |
+
history.append({"role": "assistant", "content": answer})
|
| 92 |
+
return history, ""
|
|
|
|
| 93 |
|
| 94 |
+
# === Gradio UI ===
|
| 95 |
+
with gr.Blocks(title="π§ AI Course Finder with FAISS & NLTK") as demo:
|
| 96 |
with gr.Tab("Course Finder"):
|
| 97 |
+
gr.Markdown("## π Smart Agent with FAISS + Google Fallback + Keyword AI")
|
| 98 |
with gr.Row():
|
| 99 |
profession = gr.Dropdown(["Student", "Doctor", "Nurse", "Developer", "Engineer", "Manager", "Other"],
|
| 100 |
label="π€ Profession", value="Student")
|
|
|
|
| 102 |
search_btn = gr.Button("π― Search")
|
| 103 |
result_box = gr.Textbox(label="π Result", lines=4)
|
| 104 |
|
| 105 |
+
def handle_search(p, q):
|
| 106 |
+
return course_agent(p, q)
|
| 107 |
+
|
| 108 |
+
search_btn.click(handle_search, [profession, query], result_box)
|
| 109 |
|
| 110 |
with gr.Tab("Chat"):
|
| 111 |
chatbot = gr.Chatbot(label="Chat", type="messages")
|
| 112 |
txt = gr.Textbox(show_label=False, placeholder="Type your message...")
|
| 113 |
txt.submit(chat_with_user, [txt, chatbot], [chatbot, txt])
|
| 114 |
|
| 115 |
+
demo.launch()
|