abhidgp1978 commited on
Commit
05b8df3
Β·
verified Β·
1 Parent(s): 2394331

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +52 -83
app.py CHANGED
@@ -1,117 +1,86 @@
1
  import gradio as gr
2
  import os
3
- import json
4
- import datetime
5
  import requests
6
- from nltk.tokenize import word_tokenize
7
- from nltk.corpus import stopwords
8
- from huggingface_hub import HfApi, Repository
9
- import tempfile
10
  import nltk
11
- nltk.download("punkt")
12
- nltk.download("stopwords")
13
 
14
  nltk.download("punkt")
15
  nltk.download("stopwords")
16
 
17
  HF_TOKEN = os.getenv("HF_TOKEN")
18
  HF_INFERENCE_API = "https://api-inference.huggingface.co/models/facebook/bart-large-cnn"
19
- DATASET_REPO_ID = "abhidgp1978/agentchat_logs"
20
- LOG_FILE = "user_query.jsonl"
21
 
22
  stop_words = set(stopwords.words("english"))
23
- custom_stop = {"looking", "need", "want", "searching", "courses", "course", "learn", "training", "online"}
 
 
24
  all_stops = stop_words.union(custom_stop)
25
 
26
  def extract_keywords(text):
27
  words = word_tokenize(text.lower())
28
  return [w for w in words if w.isalnum() and w not in all_stops]
29
 
30
- def google_search(query, num_results=3):
31
- # (your google search code here, or simplified for BMJ domain)
32
- # return list of dicts with "title" and "link"
33
- pass
34
-
35
- def generate_text_with_model(prompt):
36
  headers = {
37
  "Authorization": f"Bearer {HF_TOKEN}",
38
  "Content-Type": "application/json"
39
  }
40
  payload = {"inputs": prompt}
41
- try:
42
- response = requests.post(HF_INFERENCE_API, headers=headers, json=payload)
43
- response.raise_for_status()
44
- output = response.json()
45
- if isinstance(output, list) and len(output) > 0 and "summary_text" in output[0]:
46
- return output[0]["summary_text"]
47
- return "No text generated."
48
- except Exception as e:
49
- print(f"Inference API call failed: {e}")
50
- return "Failed to generate text."
51
-
52
- def log_interaction_to_hf(data):
53
- with tempfile.TemporaryDirectory() as tmpdir:
54
- repo = Repository(local_dir=tmpdir, clone_from=DATASET_REPO_ID, use_auth_token=HF_TOKEN)
55
- log_path = os.path.join(tmpdir, LOG_FILE)
56
- with open(log_path, "a", encoding="utf-8") as f:
57
- f.write(json.dumps(data) + "\n")
58
- repo.git_add(LOG_FILE)
59
- repo.git_commit("Add new user query log")
60
- repo.git_push()
61
-
62
- def course_agent(name, email, location, profession, query):
63
- if not query.strip():
64
- return "❗ Please enter a course topic."
65
 
66
  keywords = extract_keywords(query)
67
  if not keywords:
68
- return "❗ Could not extract useful keywords."
69
-
70
- search_term = " ".join(keywords) + " site:educationindia.bmj.com"
71
- search_results = google_search(search_term)
72
- if not search_results:
73
- result = "❌ No relevant BMJ course found."
74
- else:
75
- first_result = search_results[0]
76
- course_url = first_result.get("link", "")
77
- course_title = first_result.get("title", "")
78
-
79
- summary_prompt = f"Summarize the following course in 3-4 paragraphs:\nTitle: {course_title}\nURL: {course_url}\nSummary:"
80
- summary = generate_text_with_model(summary_prompt)
81
-
82
- roi_prompt = f"Generate a detailed 3-4 paragraph explanation of the Return on Investment (ROI) for the following course:\nTitle: {course_title}\nURL: {course_url}\nROI:"
83
- roi = generate_text_with_model(roi_prompt)
84
-
85
- result = (
86
- f"**{course_title}**\n{course_url}\n\n"
87
- f"### Course Summary:\n{summary}\n\n"
88
- f"### Estimated ROI:\n{roi}"
89
- )
90
 
91
- log_data = {
92
- "timestamp": datetime.datetime.utcnow().isoformat(),
93
- "name": name,
94
- "email": email,
95
- "location": location,
96
- "profession": profession,
97
- "query": query,
98
- "result": result
99
- }
100
- log_interaction_to_hf(log_data)
101
 
102
- return result
 
103
 
104
- with gr.Blocks(title="🧠 AI Course Finder with ROI & Summary") as demo:
105
- gr.Markdown("## 🎯 BMJ Education India Course Finder")
 
 
 
 
 
 
106
  with gr.Row():
107
- name = gr.Textbox(label="Name", placeholder="Your full name")
108
- email = gr.Textbox(label="Email", placeholder="Your email address")
109
- location = gr.Textbox(label="Location", placeholder="Your city or country")
110
- profession = gr.Dropdown(["Student", "Doctor", "Nurse", "Developer", "Engineer", "Manager", "Other"], label="Profession", value="Student")
111
- query = gr.Textbox(label="πŸ” Search for a course topic", lines=2)
112
- result_box = gr.Textbox(label="πŸ“˜ Result", lines=15)
 
 
113
  search_btn = gr.Button("Find Course")
114
 
115
- search_btn.click(fn=course_agent, inputs=[name, email, location, profession, query], outputs=result_box)
116
 
117
  demo.launch()
 
1
  import gradio as gr
2
  import os
 
 
3
  import requests
 
 
 
 
4
  import nltk
5
+ from nltk.corpus import stopwords
6
+ from nltk.tokenize import word_tokenize
7
 
8
  nltk.download("punkt")
9
  nltk.download("stopwords")
10
 
11
  HF_TOKEN = os.getenv("HF_TOKEN")
12
  HF_INFERENCE_API = "https://api-inference.huggingface.co/models/facebook/bart-large-cnn"
 
 
13
 
14
  stop_words = set(stopwords.words("english"))
15
+ custom_stop = {
16
+ "looking", "need", "want", "searching", "courses", "course", "learn", "training", "online"
17
+ }
18
  all_stops = stop_words.union(custom_stop)
19
 
20
  def extract_keywords(text):
21
  words = word_tokenize(text.lower())
22
  return [w for w in words if w.isalnum() and w not in all_stops]
23
 
24
+ def call_hf_inference_api(prompt):
 
 
 
 
 
25
  headers = {
26
  "Authorization": f"Bearer {HF_TOKEN}",
27
  "Content-Type": "application/json"
28
  }
29
  payload = {"inputs": prompt}
30
+ response = requests.post(HF_INFERENCE_API, headers=headers, json=payload)
31
+ if response.status_code == 200:
32
+ result = response.json()
33
+ if isinstance(result, list) and "summary_text" in result[0]:
34
+ return result[0]["summary_text"]
35
+ return "❌ Failed to generate response from AI."
36
+
37
+ def generate_roi_and_summary(course_title):
38
+ # Create detailed prompts for summary and ROI
39
+ summary_prompt = (
40
+ f"Write a detailed 3-4 paragraph summary about the course titled '{course_title}'."
41
+ )
42
+ roi_prompt = (
43
+ f"Write a detailed 3-4 paragraph explanation of the Return On Investment (ROI) for taking the course titled '{course_title}'."
44
+ )
45
+
46
+ summary = call_hf_inference_api(summary_prompt)
47
+ roi = call_hf_inference_api(roi_prompt)
48
+ return summary, roi
49
+
50
+ def course_agent(profession, query):
51
+ if not query:
52
+ return "❗ Please enter a course topic.", ""
 
53
 
54
  keywords = extract_keywords(query)
55
  if not keywords:
56
+ return "❗ Could not extract useful keywords.", ""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57
 
58
+ search_term = " ".join(keywords) + " course site:educationindia.bmj.com"
59
+ # For simplicity, just create a URL search string instead of Google API
60
+ course_url = f"https://educationindia.bmj.com/search?q={'+'.join(keywords)}"
 
 
 
 
 
 
 
61
 
62
+ # Generate AI summary and ROI
63
+ summary, roi = generate_roi_and_summary(" ".join(keywords))
64
 
65
+ result_text = f"πŸ”— Course Search URL:\n{course_url}\n\n"
66
+ result_text += f"πŸ“˜ Course Summary:\n{summary}\n\n"
67
+ result_text += f"πŸ’° Course ROI:\n{roi}\n"
68
+
69
+ return result_text, course_url
70
+
71
+ with gr.Blocks(title="🧠 AI Course Finder with Summary and ROI") as demo:
72
+ gr.Markdown("## 🎯 Course Search with AI-Generated Summary & ROI")
73
  with gr.Row():
74
+ profession = gr.Dropdown(
75
+ ["Student", "Doctor", "Nurse", "Developer", "Engineer", "Manager", "Other"],
76
+ label="Profession",
77
+ value="Student",
78
+ )
79
+ query = gr.Textbox(label="πŸ” Search for a course topic")
80
+ result_box = gr.Textbox(label="πŸ“˜ Course Details", lines=20)
81
+ course_link = gr.Textbox(label="πŸ”— Course Search URL")
82
  search_btn = gr.Button("Find Course")
83
 
84
+ search_btn.click(fn=course_agent, inputs=[profession, query], outputs=[result_box, course_link])
85
 
86
  demo.launch()