sathwikabhavaraju2005 commited on
Commit
c3d6c3e
Β·
verified Β·
1 Parent(s): e2224e6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +183 -165
app.py CHANGED
@@ -1,167 +1,185 @@
1
- import gradio as gr
2
- import requests
3
- import os
4
- from dotenv import load_dotenv
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
- prompt = (
19
- f"Generate {num_questions} simple quiz questions from the following text:\n\n"
20
- f"{text}\n\n"
21
- f"Each question should be followed by options A, B, C, D and a correct answer."
22
- )
23
-
24
- API_URL = "https://api-inference.huggingface.co/models/google/flan-t5-small"
25
- payload = {
26
- "inputs": prompt,
27
- "parameters": {"max_new_tokens": 300}
28
- }
29
-
30
- response = requests.post(API_URL, headers=headers, json=payload)
31
-
32
- try:
33
- result = response.json()
34
- if isinstance(result, list) and "generated_text" in result[0]:
35
- output = result[0]["generated_text"].strip()
36
- return output if output else "⚠️ Model returned empty text. Try reducing question count or using a smaller paragraph."
37
- else:
38
- return f"⚠️ Model didn't return expected output. Try fewer questions or simpler content."
39
- except Exception as e:
40
- return f"⚠️ API Error: {e}"
41
-
42
-
43
-
44
-
45
- def get_bot_response(query):
46
- API_URL = "https://api-inference.huggingface.co/models/HuggingFaceH4/zephyr-7b-beta"
47
- payload = {"inputs": f"Student: {query}\nAI:", "parameters": {"max_new_tokens": 150}}
48
- response = requests.post(API_URL, headers=headers, json=payload)
49
- try:
50
- return response.json()[0]["generated_text"].split("AI:")[-1].strip()
51
- except:
52
- return "⚠️ AI Assistant unavailable right now."
53
-
54
- def summarize_text(text):
55
- API_URL = "https://api-inference.huggingface.co/models/facebook/bart-large-cnn"
56
- payload = {"inputs": text, "parameters": {"max_length": 120}}
57
- response = requests.post(API_URL, headers=headers, json=payload)
58
- try:
59
- return response.json()[0]["summary_text"]
60
- except:
61
- return "⚠️ Unable to summarize content."
62
-
63
- def translate_text(text, target_lang="te"):
64
- API_URL = "https://libretranslate.de/translate"
65
- payload = {
66
- "q": text,
67
- "source": "en",
68
- "target": target_lang,
69
- "format": "text"
70
- }
71
- response = requests.post(API_URL, data=payload)
72
- try:
73
- return response.json()["translatedText"]
74
- except:
75
- return "⚠️ Translation failed."
76
-
77
- def check_plagiarism(text1, text2):
78
- model = SentenceTransformer('all-MiniLM-L6-v2')
79
- embeddings = model.encode([text1, text2], convert_to_tensor=True)
80
- similarity = util.pytorch_cos_sim(embeddings[0], embeddings[1]).item()
81
- return f"Similarity Score: {similarity:.2f}\n{('⚠️ Possible Plagiarism' if similarity > 0.75 else 'βœ… No significant overlap')}"
82
-
83
- def analyze_weakness(file):
84
- try:
85
- df = pd.read_csv(file.name)
86
- topic_scores = df.groupby('Topic')['Score'].mean().sort_values()
87
- weakest = topic_scores.head(3)
88
- return f"Weak Areas:\n{weakest.to_string()}"
89
- except:
90
- return "⚠️ Failed to analyze file. Ensure it contains 'Topic' and 'Score' columns."
91
-
92
- def predict_engagement(attendance, login_freq, video_watch):
93
- X = np.array([[attendance, login_freq, video_watch]])
94
- y = [0, 1, 1, 0, 1]
95
- X_train = np.array([[90, 5, 80], [85, 4, 90], [95, 6, 85], [60, 2, 40], [88, 3, 75]])
96
- clf = RandomForestClassifier().fit(X_train, y)
97
- prediction = clf.predict(X)[0]
98
- return "βœ… Likely to be Engaged" if prediction else "⚠️ At Risk of Disengagement"
99
-
100
- def generate_badge(score, speed):
101
- if score >= 90 and speed <= 30:
102
- return "πŸ… Gold Badge"
103
- elif score >= 75:
104
- return "πŸ₯ˆ Silver Badge"
105
- else:
106
- return "πŸ₯‰ Bronze Badge"
107
-
108
- # ----------------- UI -----------------
109
- with gr.Blocks(title="Smart LMS AI Suite") as app:
110
-
111
- with gr.Tab("🧠 Quiz Generator"):
112
- quiz_text = gr.Textbox(label="Paste Topic Content")
113
- quiz_slider = gr.Slider(1, 10, label="Number of Questions", value=3)
114
- quiz_output = gr.Textbox(label="Generated Quiz")
115
- quiz_button = gr.Button("Generate Quiz")
116
- quiz_button.click(fn=generate_quiz, inputs=[quiz_text, quiz_slider], outputs=quiz_output)
117
-
118
- with gr.Tab("πŸ€– AI Teaching Assistant"):
119
- bot_input = gr.Textbox(label="Ask a Question")
120
- bot_output = gr.Textbox(label="AI Answer")
121
- bot_button = gr.Button("Get Answer")
122
- bot_button.click(fn=get_bot_response, inputs=bot_input, outputs=bot_output)
123
-
124
- with gr.Tab("πŸ“„ Summarizer"):
125
- sum_input = gr.Textbox(label="Paste Content")
126
- sum_output = gr.Textbox(label="Summary")
127
- sum_button = gr.Button("Summarize")
128
- sum_button.click(fn=summarize_text, inputs=sum_input, outputs=sum_output)
129
-
130
- with gr.Tab("🌍 Translator"):
131
- trans_input = gr.Textbox(label="Text in English")
132
- lang_dropdown = gr.Dropdown(["te", "hi", "ta", "fr"], value="te", label="Target Language Code")
133
- trans_output = gr.Textbox(label="Translated Text")
134
- trans_button = gr.Button("Translate")
135
- trans_button.click(fn=translate_text, inputs=[trans_input, lang_dropdown], outputs=trans_output)
136
-
137
- with gr.Tab("🧾 Plagiarism Checker"):
138
- plag_1 = gr.Textbox(label="Document 1")
139
- plag_2 = gr.Textbox(label="Document 2")
140
- plag_out = gr.Textbox(label="Result")
141
- plag_btn = gr.Button("Check Plagiarism")
142
- plag_btn.click(fn=check_plagiarism, inputs=[plag_1, plag_2], outputs=plag_out)
143
-
144
- with gr.Tab("πŸ“‰ Weakness Analyzer"):
145
- csv_input = gr.File(label="Upload CSV with 'Topic' and 'Score' Columns")
146
- weak_out = gr.Textbox(label="Weak Topics")
147
- weak_btn = gr.Button("Analyze")
148
- weak_btn.click(fn=analyze_weakness, inputs=csv_input, outputs=weak_out)
149
-
150
- with gr.Tab("πŸ“Š Engagement Predictor"):
151
- att = gr.Slider(0, 100, value=85, label="Attendance %")
152
- login = gr.Slider(0, 10, value=5, label="Login Frequency")
153
- video = gr.Slider(0, 100, value=80, label="Video Watch %")
154
- engage_out = gr.Textbox(label="Prediction")
155
- engage_btn = gr.Button("Predict")
156
- engage_btn.click(fn=predict_engagement, inputs=[att, login, video], outputs=engage_out)
157
-
158
- with gr.Tab("πŸ… Badge Generator"):
159
- score = gr.Slider(0, 100, label="Score")
160
- speed = gr.Slider(0, 60, label="Time Taken (mins)")
161
- badge_out = gr.Textbox(label="Badge Awarded")
162
- badge_btn = gr.Button("Generate Badge")
163
- badge_btn.click(fn=generate_badge, inputs=[score, speed], outputs=badge_out)
164
-
165
- gr.Markdown("πŸš€ Built using Hugging Face, Gradio, and Free APIs")
166
-
167
- app.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ""import gradio as gr
 
 
 
2
  import pandas as pd
3
+ import matplotlib.pyplot as plt
4
+ import torch
5
+ from transformers import T5Tokenizer, T5ForConditionalGeneration
6
+ from sentence\_transformers import SentenceTransformer, util
7
  import numpy as np
8
+
9
+ # ------------------------------
10
+
11
+ # Offline Quiz Generator
12
+
13
+ # ------------------------------
14
+
15
+ model\_qg = T5ForConditionalGeneration.from\_pretrained("t5-base")
16
+ tokenizer\_qg = T5Tokenizer.from\_pretrained("t5-base")
17
+
18
+ def generate\_mcqs(text, num\_questions=3):
19
+ input\_text = f"generate questions: {text}"
20
+ input\_ids = tokenizer\_qg.encode(input\_text, return\_tensors="pt", max\_length=512, truncation=True)
21
+ outputs = model\_qg.generate(input\_ids=input\_ids, max\_length=256, num\_return\_sequences=1)
22
+ return tokenizer\_qg.decode(outputs\[0], skip\_special\_tokens=True).strip()
23
+
24
+ # ------------------------------
25
+
26
+ # Weakness Analyzer
27
+
28
+ # ------------------------------
29
+
30
+ def analyze\_weakness(csv\_file):
31
+ df = pd.read\_csv(csv\_file.name)
32
+ summary = df.groupby("Topic")\["Score"].mean().sort\_values()
33
+ return summary.to\_string()
34
+
35
+ # ------------------------------
36
+
37
+ # Teaching Assistant
38
+
39
+ # ------------------------------
40
+
41
+ def chatbot\_response(message, history):
42
+ return "This is a placeholder response for now. (LLM not integrated)"
43
+
44
+ # ------------------------------
45
+
46
+ # Speech Question Solver
47
+
48
+ # ------------------------------
49
+
50
+ def speech\_answer(audio):
51
+ return "Audio to text transcription + answer generation is not included in offline version."
52
+
53
+ # ------------------------------
54
+
55
+ # PDF/YT Summarizer
56
+
57
+ # ------------------------------
58
+
59
+ def summarize\_text(text):
60
+ input\_text = f"summarize: {text.strip()}"
61
+ input\_ids = tokenizer\_qg.encode(input\_text, return\_tensors="pt", max\_length=512, truncation=True)
62
+ summary\_ids = model\_qg.generate(input\_ids, max\_length=150, min\_length=30, length\_penalty=5., num\_beams=2)
63
+ return tokenizer\_qg.decode(summary\_ids\[0], skip\_special\_tokens=True)
64
+
65
+ # ------------------------------
66
+
67
+ # Engagement Predictor (Mock)
68
+
69
+ # ------------------------------
70
+
71
+ def predict\_engagement(file):
72
+ df = pd.read\_csv(file.name)
73
+ avg\_time = df\['TimeSpent'].mean()
74
+ if avg\_time < 10:
75
+ return "⚠️ Risk of disengagement"
76
+ else:
77
+ return "βœ… Engaged student"
78
+
79
+ # ------------------------------
80
+
81
+ # Badge Generator
82
+
83
+ # ------------------------------
84
+
85
+ def generate\_badge(file):
86
+ df = pd.read\_csv(file.name)
87
+ avg\_score = df\['Score'].mean()
88
+ if avg\_score >= 80:
89
+ return "πŸ… Gold Badge"
90
+ elif avg\_score >= 50:
91
+ return "πŸ₯ˆ Silver Badge"
92
+ else:
93
+ return "πŸ₯‰ Bronze Badge"
94
+
95
+ # ------------------------------
96
+
97
+ # Translator (Mock - offline)
98
+
99
+ # ------------------------------
100
+
101
+ def translate\_text(text, target\_lang):
102
+ return f"(Translated to {target\_lang}) - This is a mock translation."
103
+
104
+ # ------------------------------
105
+
106
+ # Plagiarism Checker
107
+
108
+ # ------------------------------
109
+
110
+ model\_plag = SentenceTransformer('all-MiniLM-L6-v2')
111
+
112
+ def check\_plagiarism(text1, text2):
113
+ emb1 = model\_plag.encode(text1, convert\_to\_tensor=True)
114
+ emb2 = model\_plag.encode(text2, convert\_to\_tensor=True)
115
+ score = util.cos\_sim(emb1, emb2).item()
116
+ return f"Similarity Score: {score:.2f} - {'⚠️ Possible Plagiarism' if score > 0.8 else 'βœ… Looks Original'}"
117
+
118
+ # ------------------------------
119
+
120
+ # Gradio UI
121
+
122
+ # ------------------------------
123
+
124
+ with gr.Blocks() as demo:
125
+ gr.Markdown("# πŸ“š AI-Powered LMS Suite (Offline Mode)")
126
+
127
+ ```
128
+ with gr.Tab("🧠 Quiz Generator"):
129
+ quiz_text = gr.Textbox(label="Content", lines=5)
130
+ quiz_slider = gr.Slider(1, 10, value=3, label="Number of Questions")
131
+ quiz_btn = gr.Button("Generate Quiz")
132
+ quiz_out = gr.Textbox(label="Generated Quiz")
133
+ quiz_btn.click(fn=generate_mcqs, inputs=[quiz_text, quiz_slider], outputs=quiz_out)
134
+
135
+ with gr.Tab("πŸ“‰ Weakness Analyzer"):
136
+ weak_file = gr.File(label="Upload CSV with Topic & Score columns")
137
+ weak_btn = gr.Button("Analyze")
138
+ weak_out = gr.Textbox(label="Analysis")
139
+ weak_btn.click(fn=analyze_weakness, inputs=weak_file, outputs=weak_out)
140
+
141
+ with gr.Tab("πŸ€– Teaching Assistant"):
142
+ chat = gr.ChatInterface(fn=chatbot_response)
143
+
144
+ with gr.Tab("🎀 Speech Q Solver"):
145
+ audio_in = gr.Audio(source="microphone", type="filepath")
146
+ audio_btn = gr.Button("Answer")
147
+ audio_out = gr.Textbox()
148
+ audio_btn.click(fn=speech_answer, inputs=audio_in, outputs=audio_out)
149
+
150
+ with gr.Tab("πŸ“„ Summarizer"):
151
+ sum_text = gr.Textbox(lines=5, label="Paste Text")
152
+ sum_btn = gr.Button("Summarize")
153
+ sum_out = gr.Textbox(label="Summary")
154
+ sum_btn.click(fn=summarize_text, inputs=sum_text, outputs=sum_out)
155
+
156
+ with gr.Tab("πŸ“Š Engagement Predictor"):
157
+ eng_file = gr.File(label="Upload CSV with TimeSpent column")
158
+ eng_btn = gr.Button("Predict")
159
+ eng_out = gr.Textbox()
160
+ eng_btn.click(fn=predict_engagement, inputs=eng_file, outputs=eng_out)
161
+
162
+ with gr.Tab("πŸ… Badge Generator"):
163
+ badge_file = gr.File(label="Upload CSV with Score column")
164
+ badge_btn = gr.Button("Get Badge")
165
+ badge_out = gr.Textbox()
166
+ badge_btn.click(fn=generate_badge, inputs=badge_file, outputs=badge_out)
167
+
168
+ with gr.Tab("🌍 Translator"):
169
+ trans_in = gr.Textbox(label="Enter Text")
170
+ trans_lang = gr.Textbox(label="Target Language")
171
+ trans_btn = gr.Button("Translate")
172
+ trans_out = gr.Textbox()
173
+ trans_btn.click(fn=translate_text, inputs=[trans_in, trans_lang], outputs=trans_out)
174
+
175
+ with gr.Tab("πŸ“‹ Plagiarism Checker"):
176
+ text1 = gr.Textbox(label="Text 1", lines=3)
177
+ text2 = gr.Textbox(label="Text 2", lines=3)
178
+ plag_btn = gr.Button("Check Similarity")
179
+ plag_out = gr.Textbox()
180
+ plag_btn.click(fn=check_plagiarism, inputs=[text1, text2], outputs=plag_out)
181
+ ```
182
+
183
+ # Launch app
184
+
185
+ demo.launch()