sathwikabhavaraju2005 commited on
Commit
481fdd4
Β·
verified Β·
1 Parent(s): 5dfba26

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +64 -70
app.py CHANGED
@@ -5,16 +5,15 @@ from dotenv import load_dotenv
5
  import pandas as pd
6
  import numpy as np
7
  from sklearn.ensemble import RandomForestClassifier
8
- from sklearn.preprocessing import LabelEncoder
9
  from sentence_transformers import SentenceTransformer, util
10
 
11
- # Load environment variables
12
  load_dotenv()
13
  HF_TOKEN = os.getenv("HF_TOKEN")
14
-
15
  headers = {"Authorization": f"Bearer {HF_TOKEN}"}
16
 
17
- # ----------------- QUIZ GENERATOR -----------------
 
18
  def generate_quiz(text, num_questions):
19
  API_URL = "https://api-inference.huggingface.co/models/mrm8488/t5-base-finetuned-question-generation-ap"
20
  payload = {"inputs": f"generate questions: {text}", "parameters": {"max_length": 256}}
@@ -25,7 +24,6 @@ def generate_quiz(text, num_questions):
25
  except:
26
  return "⚠️ Failed to generate quiz. Try again later."
27
 
28
- # ----------------- AI TEACHING ASSISTANT -----------------
29
  def get_bot_response(query):
30
  API_URL = "https://api-inference.huggingface.co/models/HuggingFaceH4/zephyr-7b-beta"
31
  payload = {"inputs": f"Student: {query}\nAI:", "parameters": {"max_new_tokens": 150}}
@@ -35,7 +33,6 @@ def get_bot_response(query):
35
  except:
36
  return "⚠️ AI Assistant unavailable right now."
37
 
38
- # ----------------- SUMMARIZER -----------------
39
  def summarize_text(text):
40
  API_URL = "https://api-inference.huggingface.co/models/facebook/bart-large-cnn"
41
  payload = {"inputs": text, "parameters": {"max_length": 120}}
@@ -45,7 +42,6 @@ def summarize_text(text):
45
  except:
46
  return "⚠️ Unable to summarize content."
47
 
48
- # ----------------- TRANSLATOR -----------------
49
  def translate_text(text, target_lang="te"):
50
  API_URL = "https://libretranslate.de/translate"
51
  payload = {
@@ -60,14 +56,12 @@ def translate_text(text, target_lang="te"):
60
  except:
61
  return "⚠️ Translation failed."
62
 
63
- # ----------------- PLAGIARISM CHECKER -----------------
64
  def check_plagiarism(text1, text2):
65
  model = SentenceTransformer('all-MiniLM-L6-v2')
66
  embeddings = model.encode([text1, text2], convert_to_tensor=True)
67
  similarity = util.pytorch_cos_sim(embeddings[0], embeddings[1]).item()
68
  return f"Similarity Score: {similarity:.2f}\n{('⚠️ Possible Plagiarism' if similarity > 0.75 else 'βœ… No significant overlap')}"
69
 
70
- # ----------------- WEAKNESS ANALYZER -----------------
71
  def analyze_weakness(file):
72
  try:
73
  df = pd.read_csv(file.name)
@@ -77,16 +71,14 @@ def analyze_weakness(file):
77
  except:
78
  return "⚠️ Failed to analyze file. Ensure it contains 'Topic' and 'Score' columns."
79
 
80
- # ----------------- ENGAGEMENT PREDICTOR -----------------
81
  def predict_engagement(attendance, login_freq, video_watch):
82
  X = np.array([[attendance, login_freq, video_watch]])
83
- y = [0, 1, 1, 0, 1] # Mock labels: 1 = Engaged, 0 = Disengaged
84
  X_train = np.array([[90, 5, 80], [85, 4, 90], [95, 6, 85], [60, 2, 40], [88, 3, 75]])
85
  clf = RandomForestClassifier().fit(X_train, y)
86
  prediction = clf.predict(X)[0]
87
  return "βœ… Likely to be Engaged" if prediction else "⚠️ At Risk of Disengagement"
88
 
89
- # ----------------- BADGE GENERATOR -----------------
90
  def generate_badge(score, speed):
91
  if score >= 90 and speed <= 30:
92
  return "πŸ… Gold Badge"
@@ -95,61 +87,63 @@ def generate_badge(score, speed):
95
  else:
96
  return "πŸ₯‰ Bronze Badge"
97
 
98
- # ----------------- INTERFACES -----------------
99
-
100
- with gr.Tab("🧠 Quiz Generator"):
101
- quiz_text = gr.Textbox(label="Paste Topic Content")
102
- quiz_slider = gr.Slider(1, 10, label="Number of Questions", value=3)
103
- quiz_output = gr.Textbox(label="Generated Quiz")
104
- quiz_button = gr.Button("Generate Quiz")
105
- quiz_button.click(fn=generate_quiz, inputs=[quiz_text, quiz_slider], outputs=quiz_output)
106
-
107
- with gr.Tab("πŸ€– AI Teaching Assistant"):
108
- bot_input = gr.Textbox(label="Ask a Question")
109
- bot_output = gr.Textbox(label="AI Answer")
110
- bot_button = gr.Button("Get Answer")
111
- bot_button.click(fn=get_bot_response, inputs=bot_input, outputs=bot_output)
112
-
113
- with gr.Tab("πŸ“„ Summarizer"):
114
- sum_input = gr.Textbox(label="Paste Content")
115
- sum_output = gr.Textbox(label="Summary")
116
- sum_button = gr.Button("Summarize")
117
- sum_button.click(fn=summarize_text, inputs=sum_input, outputs=sum_output)
118
-
119
- with gr.Tab("🌍 Translator"):
120
- trans_input = gr.Textbox(label="Text in English")
121
- lang_dropdown = gr.Dropdown(["te", "hi", "ta", "fr"], value="te", label="Target Language Code")
122
- trans_output = gr.Textbox(label="Translated Text")
123
- trans_button = gr.Button("Translate")
124
- trans_button.click(fn=translate_text, inputs=[trans_input, lang_dropdown], outputs=trans_output)
125
-
126
- with gr.Tab("🧾 Plagiarism Checker"):
127
- plag_1 = gr.Textbox(label="Document 1")
128
- plag_2 = gr.Textbox(label="Document 2")
129
- plag_out = gr.Textbox(label="Result")
130
- plag_btn = gr.Button("Check Plagiarism")
131
- plag_btn.click(fn=check_plagiarism, inputs=[plag_1, plag_2], outputs=plag_out)
132
-
133
- with gr.Tab("πŸ“‰ Weakness Analyzer"):
134
- csv_input = gr.File(label="Upload CSV with 'Topic' and 'Score' Columns")
135
- weak_out = gr.Textbox(label="Weak Topics")
136
- weak_btn = gr.Button("Analyze")
137
- weak_btn.click(fn=analyze_weakness, inputs=csv_input, outputs=weak_out)
138
-
139
- with gr.Tab("πŸ“Š Engagement Predictor"):
140
- att = gr.Slider(0, 100, value=85, label="Attendance %")
141
- login = gr.Slider(0, 10, value=5, label="Login Frequency")
142
- video = gr.Slider(0, 100, value=80, label="Video Watch %")
143
- engage_out = gr.Textbox(label="Prediction")
144
- engage_btn = gr.Button("Predict")
145
- engage_btn.click(fn=predict_engagement, inputs=[att, login, video], outputs=engage_out)
146
-
147
- with gr.Tab("πŸ… Badge Generator"):
148
- score = gr.Slider(0, 100, label="Score")
149
- speed = gr.Slider(0, 60, label="Time Taken (mins)")
150
- badge_out = gr.Textbox(label="Badge Awarded")
151
- badge_btn = gr.Button("Generate Badge")
152
- badge_btn.click(fn=generate_badge, inputs=[score, speed], outputs=badge_out)
153
-
154
- gr.Markdown("πŸš€ Built with Hugging Face, LibreTranslate, Gradio")
155
- gr.launch()
 
 
 
5
  import pandas as pd
6
  import numpy as np
7
  from sklearn.ensemble import RandomForestClassifier
 
8
  from sentence_transformers import SentenceTransformer, util
9
 
10
+ # Load Hugging Face token
11
  load_dotenv()
12
  HF_TOKEN = os.getenv("HF_TOKEN")
 
13
  headers = {"Authorization": f"Bearer {HF_TOKEN}"}
14
 
15
+ # ----------------- FEATURE FUNCTIONS -----------------
16
+
17
  def generate_quiz(text, num_questions):
18
  API_URL = "https://api-inference.huggingface.co/models/mrm8488/t5-base-finetuned-question-generation-ap"
19
  payload = {"inputs": f"generate questions: {text}", "parameters": {"max_length": 256}}
 
24
  except:
25
  return "⚠️ Failed to generate quiz. Try again later."
26
 
 
27
  def get_bot_response(query):
28
  API_URL = "https://api-inference.huggingface.co/models/HuggingFaceH4/zephyr-7b-beta"
29
  payload = {"inputs": f"Student: {query}\nAI:", "parameters": {"max_new_tokens": 150}}
 
33
  except:
34
  return "⚠️ AI Assistant unavailable right now."
35
 
 
36
  def summarize_text(text):
37
  API_URL = "https://api-inference.huggingface.co/models/facebook/bart-large-cnn"
38
  payload = {"inputs": text, "parameters": {"max_length": 120}}
 
42
  except:
43
  return "⚠️ Unable to summarize content."
44
 
 
45
  def translate_text(text, target_lang="te"):
46
  API_URL = "https://libretranslate.de/translate"
47
  payload = {
 
56
  except:
57
  return "⚠️ Translation failed."
58
 
 
59
  def check_plagiarism(text1, text2):
60
  model = SentenceTransformer('all-MiniLM-L6-v2')
61
  embeddings = model.encode([text1, text2], convert_to_tensor=True)
62
  similarity = util.pytorch_cos_sim(embeddings[0], embeddings[1]).item()
63
  return f"Similarity Score: {similarity:.2f}\n{('⚠️ Possible Plagiarism' if similarity > 0.75 else 'βœ… No significant overlap')}"
64
 
 
65
  def analyze_weakness(file):
66
  try:
67
  df = pd.read_csv(file.name)
 
71
  except:
72
  return "⚠️ Failed to analyze file. Ensure it contains 'Topic' and 'Score' columns."
73
 
 
74
  def predict_engagement(attendance, login_freq, video_watch):
75
  X = np.array([[attendance, login_freq, video_watch]])
76
+ y = [0, 1, 1, 0, 1]
77
  X_train = np.array([[90, 5, 80], [85, 4, 90], [95, 6, 85], [60, 2, 40], [88, 3, 75]])
78
  clf = RandomForestClassifier().fit(X_train, y)
79
  prediction = clf.predict(X)[0]
80
  return "βœ… Likely to be Engaged" if prediction else "⚠️ At Risk of Disengagement"
81
 
 
82
  def generate_badge(score, speed):
83
  if score >= 90 and speed <= 30:
84
  return "πŸ… Gold Badge"
 
87
  else:
88
  return "πŸ₯‰ Bronze Badge"
89
 
90
+ # ----------------- UI -----------------
91
+ with gr.Blocks(title="Smart LMS AI Suite") as app:
92
+
93
+ with gr.Tab("🧠 Quiz Generator"):
94
+ quiz_text = gr.Textbox(label="Paste Topic Content")
95
+ quiz_slider = gr.Slider(1, 10, label="Number of Questions", value=3)
96
+ quiz_output = gr.Textbox(label="Generated Quiz")
97
+ quiz_button = gr.Button("Generate Quiz")
98
+ quiz_button.click(fn=generate_quiz, inputs=[quiz_text, quiz_slider], outputs=quiz_output)
99
+
100
+ with gr.Tab("πŸ€– AI Teaching Assistant"):
101
+ bot_input = gr.Textbox(label="Ask a Question")
102
+ bot_output = gr.Textbox(label="AI Answer")
103
+ bot_button = gr.Button("Get Answer")
104
+ bot_button.click(fn=get_bot_response, inputs=bot_input, outputs=bot_output)
105
+
106
+ with gr.Tab("πŸ“„ Summarizer"):
107
+ sum_input = gr.Textbox(label="Paste Content")
108
+ sum_output = gr.Textbox(label="Summary")
109
+ sum_button = gr.Button("Summarize")
110
+ sum_button.click(fn=summarize_text, inputs=sum_input, outputs=sum_output)
111
+
112
+ with gr.Tab("🌍 Translator"):
113
+ trans_input = gr.Textbox(label="Text in English")
114
+ lang_dropdown = gr.Dropdown(["te", "hi", "ta", "fr"], value="te", label="Target Language Code")
115
+ trans_output = gr.Textbox(label="Translated Text")
116
+ trans_button = gr.Button("Translate")
117
+ trans_button.click(fn=translate_text, inputs=[trans_input, lang_dropdown], outputs=trans_output)
118
+
119
+ with gr.Tab("🧾 Plagiarism Checker"):
120
+ plag_1 = gr.Textbox(label="Document 1")
121
+ plag_2 = gr.Textbox(label="Document 2")
122
+ plag_out = gr.Textbox(label="Result")
123
+ plag_btn = gr.Button("Check Plagiarism")
124
+ plag_btn.click(fn=check_plagiarism, inputs=[plag_1, plag_2], outputs=plag_out)
125
+
126
+ with gr.Tab("πŸ“‰ Weakness Analyzer"):
127
+ csv_input = gr.File(label="Upload CSV with 'Topic' and 'Score' Columns")
128
+ weak_out = gr.Textbox(label="Weak Topics")
129
+ weak_btn = gr.Button("Analyze")
130
+ weak_btn.click(fn=analyze_weakness, inputs=csv_input, outputs=weak_out)
131
+
132
+ with gr.Tab("πŸ“Š Engagement Predictor"):
133
+ att = gr.Slider(0, 100, value=85, label="Attendance %")
134
+ login = gr.Slider(0, 10, value=5, label="Login Frequency")
135
+ video = gr.Slider(0, 100, value=80, label="Video Watch %")
136
+ engage_out = gr.Textbox(label="Prediction")
137
+ engage_btn = gr.Button("Predict")
138
+ engage_btn.click(fn=predict_engagement, inputs=[att, login, video], outputs=engage_out)
139
+
140
+ with gr.Tab("πŸ… Badge Generator"):
141
+ score = gr.Slider(0, 100, label="Score")
142
+ speed = gr.Slider(0, 60, label="Time Taken (mins)")
143
+ badge_out = gr.Textbox(label="Badge Awarded")
144
+ badge_btn = gr.Button("Generate Badge")
145
+ badge_btn.click(fn=generate_badge, inputs=[score, speed], outputs=badge_out)
146
+
147
+ gr.Markdown("πŸš€ Built using Hugging Face, Gradio, and Free APIs")
148
+
149
+ app.launch()