abhidgp1978 commited on
Commit
2e78c52
Β·
verified Β·
1 Parent(s): f0fa235

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +57 -50
app.py CHANGED
@@ -1,114 +1,121 @@
1
- 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 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 course list
 
 
 
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
- # === Keyword Extraction ===
 
 
 
 
27
  def extract_keywords(text):
28
  words = word_tokenize(text.lower())
29
- filtered = [w for w in words if w.isalnum() and w not in stopwords.words("english")]
30
- return filtered
31
 
32
- # === Google Custom Search (restricted to course platforms) ===
33
- def google_search(query, num_results=1):
34
  if not GOOGLE_API_KEY or not SEARCH_ENGINE_ID:
35
- print("⚠️ Google API keys not set.")
36
  return None
37
-
38
- api_url = f"https://www.googleapis.com/customsearch/v1?key={GOOGLE_API_KEY}&cx={SEARCH_ENGINE_ID}&q={query}"
 
 
 
 
39
  try:
40
- response = requests.get(api_url)
41
- items = response.json().get("items", [])
42
  for item in items:
43
- url = item.get("link", "").lower()
44
- if any(domain in url for domain in ["linkedin.com/learning", "udemy.com", "coursera.org", "edx.org", "bmj.com", "futurelearn.com"]):
45
- return {"title": item.get("title"), "url": item.get("link")}
46
  except Exception as e:
47
- print(f"Google Search Error: {e}")
48
  return None
49
 
50
- # === Main Logic ===
51
  def course_agent(profession, query):
52
  if not query:
53
  return "❗ Please enter a course or topic."
54
 
55
  keywords = extract_keywords(query)
56
  if not keywords:
57
- return "❗ Could not extract keywords."
 
 
58
 
59
- query_keywords_set = set(keywords)
 
60
 
61
- best_match = None
62
- max_overlap = 0
63
- for course in linkedin_courses:
64
- title_keywords = set(extract_keywords(course["title"]))
65
- overlap = len(query_keywords_set & title_keywords)
66
- if overlap > max_overlap:
67
- max_overlap = overlap
68
- best_match = course
69
 
70
- if best_match and max_overlap >= 2:
71
- result = f"βœ… Found on LinkedIn:\n{best_match['title']} - {best_match['url']}"
 
 
 
 
 
 
72
  else:
73
- search_term = " ".join(keywords) + " course"
74
- g_result = google_search(search_term)
75
  if g_result:
76
  result = f"🌐 Found via Google:\n{g_result['title']} - {g_result['url']}"
77
- else:
78
- result = "❌ No relevant course found."
79
 
 
80
  log_chat(f"[CourseFinder][{profession}] {query}", result)
81
  build_or_update_index(profession, query, result)
 
82
  return result
83
 
84
- # === Chat Response ===
85
  def chat_with_user(message, history):
86
  answer = f"Echo: {message}"
87
  log_chat(message, answer)
88
- return history + [
89
- {"role": "user", "content": message},
90
- {"role": "assistant", "content": answer}
91
- ], ""
92
 
93
  # === Gradio UI ===
94
- with gr.Blocks(title="🧠 AI Course Finder with FAISS + Dataset Logs") as demo:
95
  with gr.Tab("Course Finder"):
96
- gr.Markdown("## πŸ“š Find Relevant Courses by Profession or Topic")
97
  with gr.Row():
98
  profession = gr.Dropdown(
99
  ["Student", "Doctor", "Nurse", "Developer", "Engineer", "Manager", "Other"],
100
- label="πŸ‘€ Profession", value="Student"
 
101
  )
102
- query = gr.Textbox(label="πŸ” Topic")
103
  search_btn = gr.Button("🎯 Search")
104
  result_box = gr.Textbox(label="πŸ“˜ Result", lines=4)
105
 
106
- search_btn.click(fn=course_agent, inputs=[profession, query], outputs=result_box)
107
 
108
  with gr.Tab("Chat"):
109
- gr.Markdown("### πŸ’¬ Simple Echo Chat")
110
  chatbot = gr.Chatbot(label="Chat", type="messages")
111
  txt = gr.Textbox(show_label=False, placeholder="Type your message...")
112
- txt.submit(fn=chat_with_user, inputs=[txt, chatbot], outputs=[chatbot, txt])
113
 
114
  demo.launch()
 
 
 
 
1
  import os
2
+ import json
3
+ import difflib
4
  import re
5
  import requests
6
  import nltk
7
+ import gradio as gr
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
  GOOGLE_API_KEY = "AIzaSyCgOaCQEVvOuNtZhOkrmcnqzuiiPDA6b1Q" # πŸ” Replace this
13
  SEARCH_ENGINE_ID = "17357d675fc704764" # πŸ” Replace this
14
  COURSE_DB_PATH = "mock_courses.json"
15
 
16
+ nltk.download("punkt")
17
+ nltk.download("stopwords")
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
+ STOPWORDS = set(stopwords.words("english")) | {
27
+ "course", "courses", "looking", "searching", "want", "learn", "training", "management"
28
+ }
29
+
30
+ # === Keyword Extraction using NLTK ===
31
  def extract_keywords(text):
32
  words = word_tokenize(text.lower())
33
+ return [w for w in words if w.isalnum() and w not in STOPWORDS]
 
34
 
35
+ # === Google Search Logic (filtered) ===
36
+ def google_search(query):
37
  if not GOOGLE_API_KEY or not SEARCH_ENGINE_ID:
 
38
  return None
39
+ api_url = f"https://www.googleapis.com/customsearch/v1"
40
+ params = {
41
+ "key": GOOGLE_API_KEY,
42
+ "cx": SEARCH_ENGINE_ID,
43
+ "q": query,
44
+ }
45
  try:
46
+ res = requests.get(api_url, params=params)
47
+ items = res.json().get("items", [])
48
  for item in items:
49
+ link = item.get("link", "")
50
+ if any(p in link for p in ["linkedin.com/learning", "coursera.org", "udemy.com", "edx.org", "bmj.com"]):
51
+ return {"title": item.get("title", ""), "url": link}
52
  except Exception as e:
53
+ print("Google Search Error:", e)
54
  return None
55
 
56
+ # === Course Matching Logic ===
57
  def course_agent(profession, query):
58
  if not query:
59
  return "❗ Please enter a course or topic."
60
 
61
  keywords = extract_keywords(query)
62
  if not keywords:
63
+ return "❗ Could not extract keywords from your query."
64
+
65
+ query_keywords_str = " ".join(keywords)
66
 
67
+ tech_professions = {"developer", "engineer", "analyst", "manager", "student", "it", "business"}
68
+ is_tech = any(p in profession.lower() for p in tech_professions)
69
 
70
+ result = "❌ No relevant course found."
71
+ title_match = None
 
 
 
 
 
 
72
 
73
+ # Title similarity check
74
+ titles = [c["title"] for c in linkedin_courses]
75
+ match = difflib.get_close_matches(query_keywords_str, titles, n=1, cutoff=0.5)
76
+ if match:
77
+ title_match = next((c for c in linkedin_courses if c["title"] == match[0]), None)
78
+
79
+ if title_match:
80
+ result = f"βœ… Found on LinkedIn:\n{title_match['title']} - {title_match['url']}"
81
  else:
82
+ g_result = google_search(query_keywords_str + " course")
 
83
  if g_result:
84
  result = f"🌐 Found via Google:\n{g_result['title']} - {g_result['url']}"
 
 
85
 
86
+ # Log and update vector store
87
  log_chat(f"[CourseFinder][{profession}] {query}", result)
88
  build_or_update_index(profession, query, result)
89
+
90
  return result
91
 
92
+ # === Chat Echo ===
93
  def chat_with_user(message, history):
94
  answer = f"Echo: {message}"
95
  log_chat(message, answer)
96
+ history.append({"role": "user", "content": message})
97
+ history.append({"role": "assistant", "content": answer})
98
+ return history, ""
 
99
 
100
  # === Gradio UI ===
101
+ with gr.Blocks(title="🧠 AI Course Finder with Self-Learning") as demo:
102
  with gr.Tab("Course Finder"):
103
+ gr.Markdown("## πŸ“š Smart Agent with FAISS & HuggingFace Logging")
104
  with gr.Row():
105
  profession = gr.Dropdown(
106
  ["Student", "Doctor", "Nurse", "Developer", "Engineer", "Manager", "Other"],
107
+ label="πŸ‘€ Profession",
108
+ value="Student"
109
  )
110
+ query = gr.Textbox(label="πŸ” Course Topic")
111
  search_btn = gr.Button("🎯 Search")
112
  result_box = gr.Textbox(label="πŸ“˜ Result", lines=4)
113
 
114
+ search_btn.click(course_agent, inputs=[profession, query], outputs=result_box)
115
 
116
  with gr.Tab("Chat"):
 
117
  chatbot = gr.Chatbot(label="Chat", type="messages")
118
  txt = gr.Textbox(show_label=False, placeholder="Type your message...")
119
+ txt.submit(chat_with_user, [txt, chatbot], [chatbot, txt])
120
 
121
  demo.launch()