abhidgp1978 commited on
Commit
2102c3a
Β·
verified Β·
1 Parent(s): 6b40699

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +49 -58
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
- # === NLTK Setup ===
15
- NLTK_DATA_DIR = "/home/user/nltk_data"
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
- # === Config ===
22
- GOOGLE_API_KEY = os.getenv("AIzaSyCgOaCQEVvOuNtZhOkrmcnqzuiiPDA6b1Q", "") # Add in Space secrets
23
- SEARCH_ENGINE_ID = os.getenv("17357d675fc704764", "") # Add in Space secrets
24
  COURSE_DB_PATH = "mock_courses.json"
25
 
26
- # === Load Local Courses ===
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
- # === Keyword Extraction ===
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
- # === Google Search with Filtering ===
40
- def google_search(query, num_results=1):
41
  if not GOOGLE_API_KEY or not SEARCH_ENGINE_ID:
42
- return None # fail silently if keys are missing
43
-
44
- # Restrict to educational platforms
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
- if items:
63
- top = items[0]
64
- return {
65
- "title": top.get("title", "No Title"),
66
- "url": top.get("link", "No URL")
67
- }
 
68
  except Exception as e:
69
  print(f"Google Search Error: {e}")
70
-
71
  return None
72
 
73
- # === Agent Logic ===
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
- titles = [course["title"] for course in linkedin_courses]
83
- match = difflib.get_close_matches(" ".join(keywords), titles, n=1, cutoff=0.6)
84
-
85
- if match:
86
- course = next(c for c in linkedin_courses if c["title"] == match[0])
87
- result = f"βœ… Found on LinkedIn:\n{course['title']} - {course['url']}"
88
- else:
89
- search_term = " ".join(keywords) + " course"
90
- g_result = google_search(search_term)
91
- result = f"🌐 Found via Google:\n{g_result['title']} - {g_result['url']}" if g_result else "❌ No relevant course found."
 
 
 
 
 
 
 
 
92
 
93
  log_chat(f"[CourseFinder][{profession}] {query}", result)
94
  build_or_update_index(profession, query, result)
95
  return result
96
 
97
- # === Basic Chat Logic ===
98
  def chat_with_user(message, history):
99
  answer = f"Echo: {message}"
100
  log_chat(message, answer)
101
- return history + [
102
- {"role": "user", "content": message},
103
- {"role": "assistant", "content": answer}
104
- ], ""
105
 
106
- # === UI ===
107
- with gr.Blocks(title="🧠 AI Course Finder with Self-Learning") as demo:
108
  with gr.Tab("Course Finder"):
109
- gr.Markdown("## πŸ“š Smart Agent with FAISS Logging and Google+LinkedIn Search")
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
- search_btn.click(course_agent, [profession, query], result_box)
 
 
 
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
- demo.launch()
 
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()