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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +154 -102
app.py CHANGED
@@ -1,103 +1,155 @@
1
  import gradio as gr
2
- from utils.quiz_generator import generate_quiz
3
- from utils.chatbot import ask_ai
4
- from utils.summarizer import summarize_text, get_youtube_transcript, extract_text_from_pdf
5
- from utils.translator import translate_text
6
- from utils.plagiarism_checker import check_plagiarism
7
- from utils.weakness_analyzer import analyze_weakness
8
- from utils.engagement_predictor import predict_engagement
9
- from utils.badge import assign_badges
10
-
11
- # Chat history for chatbot
12
- chat_history = []
13
-
14
- # ------------------- Gradio UI -------------------
15
-
16
- with gr.Blocks(title="πŸ“š Smart LMS AI Suite") as demo:
17
-
18
- gr.Markdown("# πŸŽ“ Smart LMS AI Suite\nYour AI-powered Learning Assistant πŸš€")
19
-
20
- with gr.Tabs():
21
-
22
- # 1. Quiz Generator
23
- with gr.TabItem("🧠 Quiz Generator"):
24
- with gr.Row():
25
- topic_input = gr.Textbox(label="Paste Topic Content")
26
- num_qs = gr.Slider(1, 10, value=5, label="Number of Questions")
27
- quiz_output = gr.Textbox(label="Generated Quiz")
28
- quiz_button = gr.Button("Generate Quiz")
29
- quiz_button.click(fn=generate_quiz, inputs=[topic_input, num_qs], outputs=quiz_output)
30
-
31
- # 2. AI Teaching Assistant
32
- with gr.TabItem("πŸ€– AI Teaching Assistant"):
33
- with gr.Row():
34
- question_input = gr.Textbox(label="Ask your question")
35
- chatbot_output = gr.Textbox(label="AI Answer")
36
- chat_button = gr.Button("Ask")
37
- def chat_interface(q):
38
- global chat_history
39
- response, chat_history = ask_ai(q, chat_history)
40
- return response
41
- chat_button.click(fn=chat_interface, inputs=question_input, outputs=chatbot_output)
42
-
43
- # 3. Summarizer
44
- with gr.TabItem("πŸ“„ Summarizer"):
45
- with gr.Row():
46
- summarizer_input = gr.Textbox(lines=4, label="Paste Text to Summarize")
47
- yt_url = gr.Textbox(label="Or Enter YouTube Video URL")
48
- pdf_input = gr.File(label="Or Upload PDF", file_types=[".pdf"])
49
- summary_output = gr.Textbox(label="Summary")
50
- summary_button = gr.Button("Summarize")
51
-
52
- def summarize_all(text, url, pdf):
53
- if pdf:
54
- content = extract_text_from_pdf(pdf.name)
55
- elif url:
56
- content = get_youtube_transcript(url)
57
- else:
58
- content = text
59
- return summarize_text(content)
60
-
61
- summary_button.click(fn=summarize_all, inputs=[summarizer_input, yt_url, pdf_input], outputs=summary_output)
62
-
63
- # 4. Translator
64
- with gr.TabItem("🌍 Translator"):
65
- text_input = gr.Textbox(label="Enter English Text")
66
- lang = gr.Dropdown(choices=["te", "hi", "ta", "bn", "kn", "gu", "ur"], label="Target Language")
67
- translated = gr.Textbox(label="Translated Text")
68
- translate_button = gr.Button("Translate")
69
- translate_button.click(fn=translate_text, inputs=[text_input, lang], outputs=translated)
70
-
71
- # 5. Plagiarism Checker
72
- with gr.TabItem("πŸ•΅οΈ Plagiarism Checker"):
73
- with gr.Row():
74
- plag_input1 = gr.Textbox(label="Text 1")
75
- plag_input2 = gr.Textbox(label="Text 2")
76
- plag_output = gr.Textbox(label="Plagiarism Result")
77
- plag_btn = gr.Button("Check")
78
- plag_btn.click(fn=check_plagiarism, inputs=[plag_input1, plag_input2], outputs=plag_output)
79
-
80
- # 6. Weakness Analyzer
81
- with gr.TabItem("πŸ“‰ Weakness Analyzer"):
82
- weakness_file = gr.File(label="Upload Quiz Scores CSV")
83
- weakness_result = gr.Textbox(label="Analysis Result")
84
- weakness_btn = gr.Button("Analyze")
85
- weakness_btn.click(fn=analyze_weakness, inputs=weakness_file, outputs=weakness_result)
86
-
87
- # 7. Engagement Predictor
88
- with gr.TabItem("πŸ“Š Engagement Predictor"):
89
- engagement_file = gr.File(label="Upload Student Log CSV")
90
- engagement_output = gr.Textbox(label="Prediction Report")
91
- engagement_btn = gr.Button("Predict Engagement")
92
- engagement_btn.click(fn=predict_engagement, inputs=engagement_file, outputs=engagement_output)
93
-
94
- # 8. Badge Generator
95
- with gr.TabItem("πŸ… Badge Generator"):
96
- badge_file = gr.File(label="Upload Performance CSV")
97
- badge_output = gr.Textbox(label="Badge Report")
98
- badge_btn = gr.Button("Generate Badges")
99
- badge_btn.click(fn=assign_badges, inputs=badge_file, outputs=badge_output)
100
-
101
-
102
- # πŸ” Launch
103
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 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}}
21
+ response = requests.post(API_URL, headers=headers, json=payload)
22
+ try:
23
+ result = response.json()[0]["generated_text"]
24
+ return f"{num_questions} Sample Questions:\n\n{result}"
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}}
32
+ response = requests.post(API_URL, headers=headers, json=payload)
33
+ try:
34
+ return response.json()[0]["generated_text"].split("AI:")[-1].strip()
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}}
42
+ response = requests.post(API_URL, headers=headers, json=payload)
43
+ try:
44
+ return response.json()[0]["summary_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 = {
52
+ "q": text,
53
+ "source": "en",
54
+ "target": target_lang,
55
+ "format": "text"
56
+ }
57
+ response = requests.post(API_URL, data=payload)
58
+ try:
59
+ return response.json()["translatedText"]
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)
74
+ topic_scores = df.groupby('Topic')['Score'].mean().sort_values()
75
+ weakest = topic_scores.head(3)
76
+ return f"Weak Areas:\n{weakest.to_string()}"
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"
93
+ elif score >= 75:
94
+ return "πŸ₯ˆ Silver Badge"
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()