abhidgp1978 commited on
Commit
3e89be4
Β·
verified Β·
1 Parent(s): f750108

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +64 -65
app.py CHANGED
@@ -1,121 +1,120 @@
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()
 
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 huggingface_hub import HfApi
11
+ from datasets import DatasetDict
12
  from memory_store import log_chat, build_or_update_index, search_similar
13
 
14
+ # === NLTK Setup ===
15
+ nltk.download("punkt")
16
+ nltk.download("stopwords")
17
+
18
  GOOGLE_API_KEY = "AIzaSyCgOaCQEVvOuNtZhOkrmcnqzuiiPDA6b1Q" # πŸ” Replace this
19
  SEARCH_ENGINE_ID = "17357d675fc704764" # πŸ” Replace this
20
  COURSE_DB_PATH = "mock_courses.json"
21
+ HF_TOKEN = os.getenv("HF_TOKEN")
22
+ DATASET_REPO = "abhidgp1978/agentchat_logs"
23
 
24
+ # === Load LinkedIn Courses ===
 
 
 
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
+ # === Extract Keywords using NLTK ===
 
 
 
 
32
  def extract_keywords(text):
33
  words = word_tokenize(text.lower())
34
+ filtered = [w for w in words if w.isalnum() and w not in stopwords.words("english")]
35
+ return filtered
36
+
37
+ # === Google Search ===
38
+ def google_search(query, num_results=1):
39
+ api_url = f"https://www.googleapis.com/customsearch/v1?key={GOOGLE_API_KEY}&cx={SEARCH_ENGINE_ID}&q={query}"
 
 
 
 
 
 
40
  try:
41
+ response = requests.get(api_url)
42
+ data = response.json()
43
+ items = data.get("items", [])
44
+ if items:
45
+ for item in items:
46
+ url = item.get("link", "")
47
+ if any(x in url for x in ["linkedin.com/learning", "udemy.com", "coursera.org", "edx.org", "bmj.com"]):
48
+ return {"title": item.get("title", "No Title"), "url": url}
49
  except Exception as e:
50
+ print(f"Google Search Error: {e}")
51
  return None
52
 
53
+ # === Course Agent ===
54
  def course_agent(profession, query):
55
  if not query:
56
  return "❗ Please enter a course or topic."
57
 
58
  keywords = extract_keywords(query)
59
  if not keywords:
60
+ return "❗ Could not extract keywords."
 
 
61
 
62
  tech_professions = {"developer", "engineer", "analyst", "manager", "student", "it", "business"}
63
  is_tech = any(p in profession.lower() for p in tech_professions)
64
 
65
+ titles = [course["title"] for course in linkedin_courses]
66
+ match = difflib.get_close_matches(query, titles, n=1, cutoff=0.5)
 
 
 
 
67
  if match:
68
+ course = next(c for c in linkedin_courses if c["title"] == match[0])
69
+ result = f"βœ… Found on LinkedIn:\n{course['title']} - {course['url']}"
 
 
70
  else:
71
+ search_term = " ".join(keywords) + " course"
72
+ g_result = google_search(search_term)
73
+ result = f"🌐 Found via Google:\n{g_result['title']} - {g_result['url']}" if g_result else "❌ No relevant course found."
74
 
 
75
  log_chat(f"[CourseFinder][{profession}] {query}", result)
76
  build_or_update_index(profession, query, result)
 
77
  return result
78
 
79
+ # === Reset Function ===
80
+ def reset_data():
81
+ try:
82
+ if os.path.exists("memory/faiss_index.bin"):
83
+ os.remove("memory/faiss_index.bin")
84
+ DatasetDict({}).push_to_hub(DATASET_REPO, token=HF_TOKEN)
85
+ return "βœ… Logs and FAISS index cleared."
86
+ except Exception as e:
87
+ return f"❌ Reset failed: {str(e)}"
88
+
89
+ # === Chat Mode ===
90
  def chat_with_user(message, history):
91
  answer = f"Echo: {message}"
92
  log_chat(message, answer)
93
+ return history + [
94
+ {"role": "user", "content": message},
95
+ {"role": "assistant", "content": answer}
96
+ ], ""
97
 
98
+ # === UI ===
99
+ with gr.Blocks(title="🧠 AI Course Finder with Reset") as demo:
100
  with gr.Tab("Course Finder"):
101
+ gr.Markdown("## πŸ“š Smart Agent with FAISS Logging")
102
  with gr.Row():
103
+ profession = gr.Dropdown(["Student", "Doctor", "Nurse", "Developer", "Engineer", "Manager", "Other"],
104
+ label="πŸ‘€ Profession", value="Student")
105
+ query = gr.Textbox(label="πŸ” Topic")
 
 
 
106
  search_btn = gr.Button("🎯 Search")
107
  result_box = gr.Textbox(label="πŸ“˜ Result", lines=4)
108
+ search_btn.click(course_agent, [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
+ with gr.Tab("⚠️ Admin"):
116
+ reset_btn = gr.Button("πŸ” Reset Logs and FAISS")
117
+ reset_status = gr.Textbox(label="Reset Status")
118
+ reset_btn.click(reset_data, outputs=reset_status)
119
+
120
  demo.launch()