abhidgp1978 commited on
Commit
feaeab1
Β·
verified Β·
1 Parent(s): 06ce4f5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +44 -39
app.py CHANGED
@@ -1,25 +1,22 @@
1
  import gradio as gr
 
2
  import json
3
  import os
4
  import re
5
  import requests
6
- import difflib
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 Setup ===
13
  nltk.download("punkt")
14
  nltk.download("stopwords")
15
- STOPWORDS = set(stopwords.words("english"))
16
 
17
- # === Google Search Config ===
18
  GOOGLE_API_KEY = "AIzaSyCgOaCQEVvOuNtZhOkrmcnqzuiiPDA6b1Q" # πŸ” Replace this
19
  SEARCH_ENGINE_ID = "17357d675fc704764" # πŸ” Replace this
20
  COURSE_DB_PATH = "mock_courses.json"
21
 
22
- # === Load Local Course DB ===
23
  if os.path.exists(COURSE_DB_PATH):
24
  with open(COURSE_DB_PATH, "r") as f:
25
  linkedin_courses = json.load(f)
@@ -29,47 +26,52 @@ else:
29
  # === Keyword Extraction ===
30
  def extract_keywords(text):
31
  words = word_tokenize(text.lower())
32
- return [w for w in words if w.isalnum() and w not in STOPWORDS]
 
33
 
34
- # === Google Search with Course Filter ===
35
- def google_search(query):
36
- allowed_domains = ["linkedin.com", "udemy.com", "coursera.org", "edx.org", "bmj.com", "futurelearn.com"]
37
- api_url = f"https://www.googleapis.com/customsearch/v1?key={GOOGLE_API_KEY}&cx={SEARCH_ENGINE_ID}&q={query}"
 
38
 
 
39
  try:
40
- res = requests.get(api_url).json()
41
- for item in res.get("items", []):
42
- link = item.get("link", "")
43
- if any(domain in link for domain in allowed_domains):
44
- return {
45
- "title": item.get("title", "No Title"),
46
- "url": link
47
- }
48
  except Exception as e:
49
- print("❌ Google Search Error:", e)
50
  return None
51
 
52
- # === Main Agent Logic ===
53
  def course_agent(profession, query):
54
  if not query:
55
  return "❗ Please enter a course or topic."
56
 
57
  keywords = extract_keywords(query)
58
  if not keywords:
59
- return "❗ No useful keywords found."
60
 
61
- tech_professions = {"developer", "engineer", "analyst", "student", "it", "business", "manager"}
62
- is_tech = any(p in profession.lower() for p in tech_professions)
63
 
64
- titles = [course["title"] for course in linkedin_courses]
65
- title_match = difflib.get_close_matches(" ".join(keywords), titles, n=1, cutoff=0.5)
 
 
 
 
 
 
66
 
67
- if title_match:
68
- course = next(c for c in linkedin_courses if c["title"] == title_match[0])
69
- result = f"βœ… Found on LinkedIn:\n{course['title']} - {course['url']}"
70
  else:
71
- search_query = " ".join(keywords) + " course"
72
- g_result = google_search(search_query)
73
  if g_result:
74
  result = f"🌐 Found via Google:\n{g_result['title']} - {g_result['url']}"
75
  else:
@@ -79,7 +81,7 @@ def course_agent(profession, query):
79
  build_or_update_index(profession, query, result)
80
  return result
81
 
82
- # === Chatbot Echo Logic ===
83
  def chat_with_user(message, history):
84
  answer = f"Echo: {message}"
85
  log_chat(message, answer)
@@ -89,21 +91,24 @@ def chat_with_user(message, history):
89
  ], ""
90
 
91
  # === Gradio UI ===
92
- with gr.Blocks(title="🧠 AI Course Finder with Logging") as demo:
93
  with gr.Tab("Course Finder"):
94
- gr.Markdown("## πŸ” Find Relevant Online Courses")
95
  with gr.Row():
96
- profession = gr.Dropdown(["Student", "Doctor", "Nurse", "Developer", "Engineer", "Manager", "Other"],
97
- label="Profession", value="Student")
98
- query = gr.Textbox(label="Course Topic")
99
- search_btn = gr.Button("Search")
100
- result_box = gr.Textbox(label="Result", lines=3)
 
 
101
 
102
  search_btn.click(fn=course_agent, inputs=[profession, query], outputs=result_box)
103
 
104
  with gr.Tab("Chat"):
 
105
  chatbot = gr.Chatbot(label="Chat", type="messages")
106
  txt = gr.Textbox(show_label=False, placeholder="Type your message...")
107
- txt.submit(chat_with_user, [txt, chatbot], [chatbot, txt])
108
 
109
  demo.launch()
 
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)
 
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:
 
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)
 
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()