Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -2,28 +2,33 @@ import gradio as gr
|
|
| 2 |
import difflib
|
| 3 |
import json
|
| 4 |
import os
|
| 5 |
-
import re
|
| 6 |
import requests
|
| 7 |
import nltk
|
| 8 |
from nltk.corpus import stopwords
|
| 9 |
from nltk.tokenize import word_tokenize
|
| 10 |
-
from
|
| 11 |
|
| 12 |
nltk.download("punkt")
|
| 13 |
nltk.download("stopwords")
|
| 14 |
|
| 15 |
-
|
| 16 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
COURSE_DB_PATH = "mock_courses.json"
|
|
|
|
| 18 |
|
| 19 |
-
# Load LinkedIn Courses
|
| 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 |
-
#
|
| 27 |
stop_words = set(stopwords.words("english"))
|
| 28 |
custom_stop = {
|
| 29 |
"looking", "need", "want", "searching", "courses", "course", "learn", "training", "online"
|
|
@@ -34,21 +39,50 @@ def extract_keywords(text):
|
|
| 34 |
words = word_tokenize(text.lower())
|
| 35 |
return [w for w in words if w.isalnum() and w not in all_stops]
|
| 36 |
|
| 37 |
-
#
|
| 38 |
-
def
|
| 39 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
try:
|
| 41 |
response = requests.get(api_url)
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
|
|
|
|
|
|
|
|
|
| 47 |
except Exception as e:
|
| 48 |
print(f"Google search failed: {e}")
|
| 49 |
return None
|
| 50 |
|
| 51 |
-
#
|
| 52 |
def course_agent(profession, query):
|
| 53 |
if not query:
|
| 54 |
return "β Please enter a course topic."
|
|
@@ -57,18 +91,21 @@ def course_agent(profession, query):
|
|
| 57 |
if not keywords:
|
| 58 |
return "β Could not extract useful keywords."
|
| 59 |
|
| 60 |
-
# LinkedIn
|
| 61 |
titles = [c["title"] for c in linkedin_courses]
|
| 62 |
match = difflib.get_close_matches(" ".join(keywords), titles, n=1, cutoff=0.45)
|
| 63 |
|
| 64 |
if match:
|
| 65 |
course = next(c for c in linkedin_courses if c["title"] == match[0])
|
| 66 |
-
|
|
|
|
| 67 |
else:
|
|
|
|
| 68 |
search_term = " ".join(keywords) + " course"
|
| 69 |
g_result = google_search(search_term)
|
| 70 |
if g_result:
|
| 71 |
-
|
|
|
|
| 72 |
else:
|
| 73 |
result = "β No relevant course found."
|
| 74 |
|
|
@@ -77,7 +114,7 @@ def course_agent(profession, query):
|
|
| 77 |
build_or_update_index(profession, query, result)
|
| 78 |
return result
|
| 79 |
|
| 80 |
-
#
|
| 81 |
def chat_with_user(message, history):
|
| 82 |
answer = f"Echo: {message}"
|
| 83 |
log_chat(message, answer)
|
|
@@ -86,14 +123,18 @@ def chat_with_user(message, history):
|
|
| 86 |
{"role": "assistant", "content": answer}
|
| 87 |
], ""
|
| 88 |
|
| 89 |
-
#
|
| 90 |
with gr.Blocks(title="π§ AI Course Finder with Self-Learning") as demo:
|
| 91 |
with gr.Tab("Course Finder"):
|
| 92 |
-
gr.Markdown("## π― Smart LinkedIn
|
| 93 |
with gr.Row():
|
| 94 |
-
profession = gr.Dropdown(
|
| 95 |
-
|
| 96 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 97 |
search_btn = gr.Button("Find Course")
|
| 98 |
|
| 99 |
search_btn.click(fn=course_agent, inputs=[profession, query], outputs=result_box)
|
|
@@ -104,4 +145,5 @@ with gr.Blocks(title="π§ AI Course Finder with Self-Learning") as demo:
|
|
| 104 |
txt = gr.Textbox(show_label=False, placeholder="Ask anything...")
|
| 105 |
txt.submit(chat_with_user, [txt, chatbot], [chatbot, txt])
|
| 106 |
|
| 107 |
-
|
|
|
|
|
|
| 2 |
import difflib
|
| 3 |
import json
|
| 4 |
import os
|
|
|
|
| 5 |
import requests
|
| 6 |
import nltk
|
| 7 |
from nltk.corpus import stopwords
|
| 8 |
from nltk.tokenize import word_tokenize
|
| 9 |
+
from datetime import datetime
|
| 10 |
|
| 11 |
nltk.download("punkt")
|
| 12 |
nltk.download("stopwords")
|
| 13 |
|
| 14 |
+
# --- Load keys from environment variables ---
|
| 15 |
+
GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
|
| 16 |
+
SEARCH_ENGINE_ID = os.getenv("SEARCH_ENGINE_ID")
|
| 17 |
+
|
| 18 |
+
if not GOOGLE_API_KEY or not SEARCH_ENGINE_ID:
|
| 19 |
+
raise ValueError("Google API key or Search Engine ID not set in environment variables!")
|
| 20 |
+
|
| 21 |
COURSE_DB_PATH = "mock_courses.json"
|
| 22 |
+
USER_LOG_PATH = "user_query.jsonl" # Simulated dataset log file
|
| 23 |
|
| 24 |
+
# --- Load LinkedIn Courses DB ---
|
| 25 |
if os.path.exists(COURSE_DB_PATH):
|
| 26 |
with open(COURSE_DB_PATH, "r") as f:
|
| 27 |
linkedin_courses = json.load(f)
|
| 28 |
else:
|
| 29 |
linkedin_courses = []
|
| 30 |
|
| 31 |
+
# --- Stop words setup ---
|
| 32 |
stop_words = set(stopwords.words("english"))
|
| 33 |
custom_stop = {
|
| 34 |
"looking", "need", "want", "searching", "courses", "course", "learn", "training", "online"
|
|
|
|
| 39 |
words = word_tokenize(text.lower())
|
| 40 |
return [w for w in words if w.isalnum() and w not in all_stops]
|
| 41 |
|
| 42 |
+
# --- Logging ---
|
| 43 |
+
def log_chat(user_query, bot_response):
|
| 44 |
+
log_entry = {
|
| 45 |
+
"timestamp": datetime.utcnow().isoformat(),
|
| 46 |
+
"query": user_query,
|
| 47 |
+
"response": bot_response
|
| 48 |
+
}
|
| 49 |
+
with open(USER_LOG_PATH, "a") as f:
|
| 50 |
+
f.write(json.dumps(log_entry) + "\n")
|
| 51 |
+
|
| 52 |
+
# --- Placeholder for memory index ---
|
| 53 |
+
def build_or_update_index(profession, query, result):
|
| 54 |
+
pass
|
| 55 |
+
|
| 56 |
+
# --- Mocked free inference API to generate ROI and summary ---
|
| 57 |
+
def generate_roi_and_summary(course_title, course_url):
|
| 58 |
+
# Replace this mock with your real inference API call
|
| 59 |
+
summary = (
|
| 60 |
+
f"Summary for '{course_title}': This course offers comprehensive knowledge valuable "
|
| 61 |
+
"for professionals. Estimated ROI: Improved skills and career growth."
|
| 62 |
+
)
|
| 63 |
+
return summary
|
| 64 |
+
|
| 65 |
+
# --- Google Custom Search API call ---
|
| 66 |
+
def google_search(query, num_results=3):
|
| 67 |
+
api_url = (
|
| 68 |
+
f"https://www.googleapis.com/customsearch/v1?key={GOOGLE_API_KEY}&cx={SEARCH_ENGINE_ID}"
|
| 69 |
+
f"&q={query}&num={num_results}"
|
| 70 |
+
)
|
| 71 |
try:
|
| 72 |
response = requests.get(api_url)
|
| 73 |
+
response.raise_for_status()
|
| 74 |
+
data = response.json()
|
| 75 |
+
items = data.get("items", [])
|
| 76 |
+
# Filter results for BMJ educationindia domain
|
| 77 |
+
filtered_items = [item for item in items if "educationindia.bmj.com" in item.get("link", "")]
|
| 78 |
+
if filtered_items:
|
| 79 |
+
item = filtered_items[0]
|
| 80 |
+
return {"title": item.get("title", ""), "url": item.get("link", "")}
|
| 81 |
except Exception as e:
|
| 82 |
print(f"Google search failed: {e}")
|
| 83 |
return None
|
| 84 |
|
| 85 |
+
# --- Main course agent ---
|
| 86 |
def course_agent(profession, query):
|
| 87 |
if not query:
|
| 88 |
return "β Please enter a course topic."
|
|
|
|
| 91 |
if not keywords:
|
| 92 |
return "β Could not extract useful keywords."
|
| 93 |
|
| 94 |
+
# Try LinkedIn courses first
|
| 95 |
titles = [c["title"] for c in linkedin_courses]
|
| 96 |
match = difflib.get_close_matches(" ".join(keywords), titles, n=1, cutoff=0.45)
|
| 97 |
|
| 98 |
if match:
|
| 99 |
course = next(c for c in linkedin_courses if c["title"] == match[0])
|
| 100 |
+
roi_summary = generate_roi_and_summary(course["title"], course["url"])
|
| 101 |
+
result = f"β
Found on LinkedIn:\n{course['title']} - {course['url']}\n\n{roi_summary}"
|
| 102 |
else:
|
| 103 |
+
# Google BMJ domain search fallback
|
| 104 |
search_term = " ".join(keywords) + " course"
|
| 105 |
g_result = google_search(search_term)
|
| 106 |
if g_result:
|
| 107 |
+
roi_summary = generate_roi_and_summary(g_result["title"], g_result["url"])
|
| 108 |
+
result = f"π Found via Google BMJ Search:\n{g_result['title']} - {g_result['url']}\n\n{roi_summary}"
|
| 109 |
else:
|
| 110 |
result = "β No relevant course found."
|
| 111 |
|
|
|
|
| 114 |
build_or_update_index(profession, query, result)
|
| 115 |
return result
|
| 116 |
|
| 117 |
+
# --- Simple echo chat for demo ---
|
| 118 |
def chat_with_user(message, history):
|
| 119 |
answer = f"Echo: {message}"
|
| 120 |
log_chat(message, answer)
|
|
|
|
| 123 |
{"role": "assistant", "content": answer}
|
| 124 |
], ""
|
| 125 |
|
| 126 |
+
# --- Gradio UI ---
|
| 127 |
with gr.Blocks(title="π§ AI Course Finder with Self-Learning") as demo:
|
| 128 |
with gr.Tab("Course Finder"):
|
| 129 |
+
gr.Markdown("## π― Smart BMJ LinkedIn Course Agent")
|
| 130 |
with gr.Row():
|
| 131 |
+
profession = gr.Dropdown(
|
| 132 |
+
["Student", "Doctor", "Nurse", "Developer", "Engineer", "Manager", "Other"],
|
| 133 |
+
label="Profession",
|
| 134 |
+
value="Student"
|
| 135 |
+
)
|
| 136 |
+
query = gr.Textbox(label="π Search for a course topic")
|
| 137 |
+
result_box = gr.Textbox(label="π Result", lines=6)
|
| 138 |
search_btn = gr.Button("Find Course")
|
| 139 |
|
| 140 |
search_btn.click(fn=course_agent, inputs=[profession, query], outputs=result_box)
|
|
|
|
| 145 |
txt = gr.Textbox(show_label=False, placeholder="Ask anything...")
|
| 146 |
txt.submit(chat_with_user, [txt, chatbot], [chatbot, txt])
|
| 147 |
|
| 148 |
+
if __name__ == "__main__":
|
| 149 |
+
demo.launch()
|