NCTCMumbai commited on
Commit
1d15e10
·
verified ·
1 Parent(s): 5137cc5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +328 -139
app.py CHANGED
@@ -4,15 +4,11 @@ import gradio as gr
4
  from pathlib import Path
5
  from pptx import Presentation
6
  from gradio_client import Client, handle_file
7
- from tempfile import NamedTemporaryFile
8
  import os
9
  import logging
10
  from phi.agent import Agent
11
  from phi.model.groq import Groq
12
 
13
- # Constants
14
- proj_dir = Path.cwd()
15
-
16
  # Set up logging
17
  logging.basicConfig(level=logging.INFO)
18
  logger = logging.getLogger(__name__)
@@ -59,7 +55,7 @@ def extract_text_from_ppt(file_path):
59
  gr.Info("Extracting text from PPT/PPTX file...")
60
  presentation = Presentation(file_path)
61
  text_content = ""
62
- for slide in presentation.slides: # Fixed: Changed 'presentation' to 'presentation.slides'
63
  for shape in slide.shapes:
64
  if hasattr(shape, "text"):
65
  text_content += shape.text + " "
@@ -72,36 +68,6 @@ def system_instructions(question_difficulty, topic, documents_str):
72
  return f"""You are a great teacher and your task is to create 10 questions with 4 multiple-choice options with {question_difficulty} difficulty about the topic "{topic}" only from the provided document: {documents_str}.
73
  Then create answers. Output in JSON format, indexing questions as "Q#":"" to "Q#":"", the four choices as "Q#:C1":"" to "Q#:C4":"", and the answers as "A#":"Q#:C#" to "A#":"Q#:C#". Example: 'A10':'Q10:C3'"""
74
 
75
- # Function to convert JSON to Excel
76
- def json_to_excel(output_json):
77
- gr.Info("Converting JSON response to Excel format...")
78
- data = []
79
- for i in range(1, 11):
80
- question_key = f"Q{i}"
81
- answer_key = f"A{i}"
82
- question = output_json.get(question_key, '')
83
- correct_answer_key = output_json.get(answer_key, '')
84
- correct_answer = correct_answer_key.split(':')[-1].replace('C', '').strip() if correct_answer_key else ''
85
- option_keys = [f"{question_key}:C{i}" for i in range(1, 5)]
86
- options = [output_json.get(key, '') for key in option_keys]
87
-
88
- data.append([
89
- question, "Multiple Choice",
90
- options[0], options[1], options[2], options[3],
91
- "", correct_answer, 30, ''
92
- ])
93
-
94
- df = pd.DataFrame(data, columns=[
95
- "Question Text", "Question Type", "Option 1", "Option 2",
96
- "Option 3", "Option 4", "Option 5", "Correct Answer",
97
- "Time in seconds", "Image Link"
98
- ])
99
-
100
- temp_file = NamedTemporaryFile(delete=False, suffix=".xlsx")
101
- df.to_excel(temp_file.name, index=False)
102
- gr.Info("Excel file generated successfully.")
103
- return temp_file.name
104
-
105
  # Define theme
106
  colorful_theme = gr.themes.Default(primary_hue="cyan", secondary_hue="yellow", neutral_hue="purple")
107
 
@@ -119,12 +85,9 @@ with gr.Blocks(title="Quiz Maker", theme=colorful_theme) as QUIZBOT:
119
  </center>
120
  """)
121
 
122
- topic = gr.Textbox(label="(Optional)Enter the Topic for Quiz", placeholder="Any specific area in ppt")
123
  file_upload = gr.File(label="Upload PPT/PPTX or PDF File", type="filepath")
124
- with gr.Row():
125
- difficulty_radio = gr.Radio(["easy", "average", "hard"], value='easy', label="How difficult should the quiz be?")
126
- model_radio = gr.Radio(choices=['(ACCURATE) BGE reranker', '(HIGH ACCURATE) ColBERT'],
127
- value='(ACCURATE) BGE reranker', label="Embeddings", visible=False)
128
 
129
  # State to store output_json
130
  output_json_state = gr.State(value={})
@@ -132,11 +95,10 @@ with gr.Blocks(title="Quiz Maker", theme=colorful_theme) as QUIZBOT:
132
  generate_quiz_btn = gr.Button("Generate Quiz!🚀")
133
  quiz_msg = gr.Textbox()
134
  question_radios = [gr.Radio(visible=False) for _ in range(10)]
135
- excel_output = gr.File(label="Download Excel")
136
 
137
- def generate_quiz(question_difficulty, topic, cross_encoder, file_upload, output_json_state):
138
  if not file_upload:
139
- return ["Error: No file uploaded. Please upload a valid PPT, PPTX, or PDF file."], output_json_state, [None] * 10, None
140
 
141
  gr.Info("Detecting file type and extracting text...")
142
  if file_upload.lower().endswith('.pptx') or file_upload.lower().endswith('.ppt'):
@@ -144,7 +106,7 @@ with gr.Blocks(title="Quiz Maker", theme=colorful_theme) as QUIZBOT:
144
  elif file_upload.lower().endswith('.pdf'):
145
  text_from_file = extract_text_from_pdf(file_upload)
146
  else:
147
- return ["Error: Unsupported file type. Please upload a PPT, PPTX, or PDF file."], output_json_state, [None] * 10, None
148
 
149
  gr.Info("Preparing documents for quiz generation...")
150
  documents = [text_from_file]
@@ -159,12 +121,11 @@ with gr.Blocks(title="Quiz Maker", theme=colorful_theme) as QUIZBOT:
159
  start_index = response_text.find('{')
160
  end_index = response_text.rfind('}')
161
  if start_index == -1 or end_index == -1:
162
- return ["Error: Invalid JSON response from Groq Agent."], output_json_state, [None] * 10, None
163
  cleaned_response = response_text[start_index:end_index + 1]
164
  output_json = json.loads(cleaned_response)
165
  gr.Info("JSON response successfully processed.")
166
 
167
- excel_file = json_to_excel(output_json)
168
  question_radio_list = []
169
  for question_num in range(1, 11):
170
  question_key = f"Q{question_num}"
@@ -175,14 +136,14 @@ with gr.Blocks(title="Quiz Maker", theme=colorful_theme) as QUIZBOT:
175
  question_radio_list.append(radio)
176
 
177
  gr.Info("Quiz generation completed successfully.")
178
- return ['Quiz Generated!'], output_json, question_radio_list, excel_file
179
 
180
  except json.JSONDecodeError as e:
181
  gr.Info("Error in processing JSON response.")
182
- return [f"Error: Failed to decode JSON response. {e}"], output_json_state, [None] * 10, None
183
  except Exception as e:
184
  gr.Info("Error in quiz generation.")
185
- return [f"Error: {str(e)}"], output_json_state, [None] * 10, None
186
 
187
  def compare_answers(*user_answers, output_json_state):
188
  user_answer_list = list(user_answers)
@@ -194,9 +155,11 @@ with gr.Blocks(title="Quiz Maker", theme=colorful_theme) as QUIZBOT:
194
  answer = output_json_state.get(answer_key)
195
  if not answer:
196
  break
197
- answers_list.append(answer)
 
 
198
 
199
- score = sum(1 for item in user_answer_list if item in answers_list)
200
 
201
  if score > 7:
202
  message = f"### Excellent! You got {score} out of 10!"
@@ -208,11 +171,11 @@ with gr.Blocks(title="Quiz Maker", theme=colorful_theme) as QUIZBOT:
208
  gr.Info("Score calculation completed.")
209
  return message
210
 
211
- # Assign event handlers without decorators
212
  generate_quiz_btn.click(
213
  fn=generate_quiz,
214
- inputs=[difficulty_radio, topic, model_radio, file_upload, output_json_state],
215
- outputs=[quiz_msg, output_json_state] + question_radios + [excel_output]
216
  )
217
 
218
  check_button = gr.Button("Check Score")
@@ -228,81 +191,75 @@ QUIZBOT.launch(debug=True)# import pandas as pd
228
  # import json
229
  # import gradio as gr
230
  # from pathlib import Path
231
- # from pptx import Presentation # Library to handle PPTX files
232
- # import PyPDF2 # Library to handle PDF files
233
- # #from ragatouille import RAGPretrainedModel
234
- # from gradio_client import Client,handle_file
235
  # from tempfile import NamedTemporaryFile
236
- # #from sentence_transformers import CrossEncoder
237
- # import numpy as np
238
- # #from backend.semantic_search import table, retriever
 
239
 
240
  # # Constants
241
- # VECTOR_COLUMN_NAME = "vector"
242
- # TEXT_COLUMN_NAME = "text"
243
  # proj_dir = Path.cwd()
244
 
245
  # # Set up logging
246
- # import logging
247
  # logging.basicConfig(level=logging.INFO)
248
  # logger = logging.getLogger(__name__)
249
 
250
- # # Replace Mixtral client with Qwen Client
251
- # client = Client("Qwen/Qwen1.5-110B-Chat-demo")
252
-
253
- # # # Function to extract text from PPT/PPTX
254
- # def extract_text_from_ppt(file_path):
255
- # gr.Info("Extracting text from PPT/PPTX file...")
256
- # presentation = Presentation(file_path)
257
- # text_content = ""
258
- # for slide in presentation.slides:
259
- # for shape in slide.shapes:
260
- # if hasattr(shape, "text"):
261
- # text_content += shape.text + " "
262
- # gr.Info("Text extraction from PPT/PPTX completed.")
263
- # return text_content.strip()
264
- # from gradio_client import Client, handle_file
265
-
 
 
 
 
 
 
 
 
 
266
  # def extract_text_from_pdf(file_path):
267
- # """
268
- # Extracts text from a PDF using the HuggingChat API for PDF-to-Markdown conversion.
269
-
270
- # :param file_path: Path to the PDF file.
271
- # :return: Extracted text from the PDF.
272
- # """
273
  # client = Client("huggingchat/pdf-to-markdown")
274
-
275
  # try:
276
- # result = client.predict(
277
- # pdf_file=handle_file(file_path),
278
- # api_name="/predict"
279
- # )
280
-
281
- # # The extracted text is in result[0], metadata is in result[1]
282
  # extracted_text = result[0] if isinstance(result, (list, tuple)) and len(result) > 0 else ""
283
  # print(extracted_text)
284
  # return extracted_text.strip()
285
-
286
  # except Exception as e:
287
  # print(f"Error extracting text from PDF: {e}")
288
  # return ""
289
 
290
- # # # Function to extract text from PDF
291
- # # def extract_text_from_pdf(file_path):
292
- # # gr.Info("Extracting text from PDF file...")
293
- # # text_content = ""
294
- # # with open(file_path, 'rb') as pdf_file:
295
- # # pdf_reader = PyPDF2.PdfReader(pdf_file)
296
- # # for page in pdf_reader.pages:
297
- # # text_content += page.extract_text() or ""
298
- # # gr.Info("Text extraction from PDF completed.")
299
- # # return text_content.strip()
 
300
 
301
  # # Function to define instructions for quiz generation
302
  # def system_instructions(question_difficulty, topic, documents_str):
303
- # gr.Info("Preparing instructions for Qwen API...")
304
- # return f"""<s> [INST] You are a great teacher and your task is to create 10 questions with 4 choices with {question_difficulty} difficulty about the topic \"{topic}\" only from the below documents: {documents_str}.
305
- # Then create answers. Index in JSON format, the questions as \"Q#\":\"\" to \"Q#\":\"\", the four choices as \"Q#:C1\":\"\" to \"Q#:C4\":\"\", and the answers as \"A#\":\"Q#:C#\" to \"A#\":\"Q#:C#\". Example: 'A10':'Q10:C3' [/INST]"""
306
 
307
  # # Function to convert JSON to Excel
308
  # def json_to_excel(output_json):
@@ -314,14 +271,13 @@ QUIZBOT.launch(debug=True)# import pandas as pd
314
  # question = output_json.get(question_key, '')
315
  # correct_answer_key = output_json.get(answer_key, '')
316
  # correct_answer = correct_answer_key.split(':')[-1].replace('C', '').strip() if correct_answer_key else ''
317
- # option_keys = [f"{question_key}:C{i}" for i in range(1, 6)]
318
  # options = [output_json.get(key, '') for key in option_keys]
319
 
320
  # data.append([
321
  # question, "Multiple Choice",
322
- # options[0], options[1], options[2] if len(options) > 2 else '',
323
- # options[3] if len(options) > 3 else '', options[4] if len(options) > 4 else '',
324
- # correct_answer, 30, ''
325
  # ])
326
 
327
  # df = pd.DataFrame(data, columns=[
@@ -354,78 +310,77 @@ QUIZBOT.launch(debug=True)# import pandas as pd
354
 
355
  # topic = gr.Textbox(label="(Optional)Enter the Topic for Quiz", placeholder="Any specific area in ppt")
356
  # file_upload = gr.File(label="Upload PPT/PPTX or PDF File", type="filepath")
357
-
358
  # with gr.Row():
359
- # difficulty_radio = gr.Radio(["easy", "average", "hard"],value='easy', label="How difficult should the quiz be?")#,visible=False)
360
  # model_radio = gr.Radio(choices=['(ACCURATE) BGE reranker', '(HIGH ACCURATE) ColBERT'],
361
- # value='(ACCURATE) BGE reranker', label="Embeddings",visible=False)
 
 
 
362
 
363
  # generate_quiz_btn = gr.Button("Generate Quiz!🚀")
364
  # quiz_msg = gr.Textbox()
365
  # question_radios = [gr.Radio(visible=False) for _ in range(10)]
 
366
 
367
- # @generate_quiz_btn.click(inputs=[difficulty_radio, topic, model_radio, file_upload], outputs=[quiz_msg] + question_radios + [gr.File(label="Download Excel")])
368
- # def generate_quiz(question_difficulty, topic, cross_encoder, file_upload):
369
  # if not file_upload:
370
- # return ["Error: No file uploaded. Please upload a valid PPT, PPTX, or PDF file."]
371
 
372
- # # Detect file type and extract text accordingly
373
  # gr.Info("Detecting file type and extracting text...")
374
  # if file_upload.lower().endswith('.pptx') or file_upload.lower().endswith('.ppt'):
375
  # text_from_file = extract_text_from_ppt(file_upload)
376
  # elif file_upload.lower().endswith('.pdf'):
377
  # text_from_file = extract_text_from_pdf(file_upload)
378
  # else:
379
- # return ["Error: Unsupported file type. Please upload a PPT, PPTX, or PDF file."]
380
 
381
  # gr.Info("Preparing documents for quiz generation...")
382
  # documents = [text_from_file]
383
-
384
  # formatted_prompt = system_instructions(question_difficulty, topic, '\n'.join(documents))
385
 
386
  # try:
387
- # gr.Info("Sending request to Qwen API for quiz generation...")
388
- # response = client.predict(query=formatted_prompt, history=[], system="You are a helpful assistant.", api_name="/model_chat")
389
- # response1 = response[1][0][1]
390
-
391
- # gr.Info("Processing response from Qwen API...")
392
- # start_index = response1.find('{')
393
- # end_index = response1.rfind('}')
394
- # cleaned_response = response1[start_index:end_index + 1] if start_index != -1 and end_index != -1 else ''
 
 
395
  # output_json = json.loads(cleaned_response)
396
  # gr.Info("JSON response successfully processed.")
397
 
398
  # excel_file = json_to_excel(output_json)
399
-
400
  # question_radio_list = []
401
  # for question_num in range(1, 11):
402
  # question_key = f"Q{question_num}"
403
  # question = output_json.get(question_key)
404
  # choice_keys = [f"{question_key}:C{i}" for i in range(1, 5)]
405
  # choice_list = [output_json.get(choice_key, "Choice not found") for choice_key in choice_keys]
406
-
407
  # radio = gr.Radio(choices=choice_list, label=question, visible=True, interactive=True)
408
  # question_radio_list.append(radio)
409
 
410
  # gr.Info("Quiz generation completed successfully.")
411
- # return ['Quiz Generated!'] + question_radio_list + [excel_file]
412
 
413
  # except json.JSONDecodeError as e:
414
  # gr.Info("Error in processing JSON response.")
415
- # return [f"Error: Failed to decode JSON response. {e}"]
416
-
417
- # check_button = gr.Button("Check Score")
418
- # score_textbox = gr.Markdown()
419
 
420
- # @check_button.click(inputs=question_radios, outputs=score_textbox)
421
- # def compare_answers(*user_answers):
422
  # user_answer_list = list(user_answers)
423
  # answers_list = []
424
 
425
  # gr.Info("Comparing user answers with correct answers...")
426
  # for question_num in range(1, 11):
427
  # answer_key = f"A{question_num}"
428
- # answer = quiz_data.get(quiz_data.get(answer_key))
429
  # if not answer:
430
  # break
431
  # answers_list.append(answer)
@@ -442,5 +397,239 @@ QUIZBOT.launch(debug=True)# import pandas as pd
442
  # gr.Info("Score calculation completed.")
443
  # return message
444
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
445
  # QUIZBOT.queue()
446
- # QUIZBOT.launch(debug=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
  from pathlib import Path
5
  from pptx import Presentation
6
  from gradio_client import Client, handle_file
 
7
  import os
8
  import logging
9
  from phi.agent import Agent
10
  from phi.model.groq import Groq
11
 
 
 
 
12
  # Set up logging
13
  logging.basicConfig(level=logging.INFO)
14
  logger = logging.getLogger(__name__)
 
55
  gr.Info("Extracting text from PPT/PPTX file...")
56
  presentation = Presentation(file_path)
57
  text_content = ""
58
+ for slide in presentation.slides:
59
  for shape in slide.shapes:
60
  if hasattr(shape, "text"):
61
  text_content += shape.text + " "
 
68
  return f"""You are a great teacher and your task is to create 10 questions with 4 multiple-choice options with {question_difficulty} difficulty about the topic "{topic}" only from the provided document: {documents_str}.
69
  Then create answers. Output in JSON format, indexing questions as "Q#":"" to "Q#":"", the four choices as "Q#:C1":"" to "Q#:C4":"", and the answers as "A#":"Q#:C#" to "A#":"Q#:C#". Example: 'A10':'Q10:C3'"""
70
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71
  # Define theme
72
  colorful_theme = gr.themes.Default(primary_hue="cyan", secondary_hue="yellow", neutral_hue="purple")
73
 
 
85
  </center>
86
  """)
87
 
88
+ topic = gr.Textbox(label="Enter the Topic for Quiz (Optional)", placeholder="Any specific area in ppt")
89
  file_upload = gr.File(label="Upload PPT/PPTX or PDF File", type="filepath")
90
+ difficulty_radio = gr.Radio(["easy", "average", "hard"], value='easy', label="How difficult should the quiz be?")
 
 
 
91
 
92
  # State to store output_json
93
  output_json_state = gr.State(value={})
 
95
  generate_quiz_btn = gr.Button("Generate Quiz!🚀")
96
  quiz_msg = gr.Textbox()
97
  question_radios = [gr.Radio(visible=False) for _ in range(10)]
 
98
 
99
+ def generate_quiz(question_difficulty, topic, file_upload, output_json_state):
100
  if not file_upload:
101
+ return ["Error: No file uploaded. Please upload a valid PPT, PPTX, or PDF file."], output_json_state, [None] * 10
102
 
103
  gr.Info("Detecting file type and extracting text...")
104
  if file_upload.lower().endswith('.pptx') or file_upload.lower().endswith('.ppt'):
 
106
  elif file_upload.lower().endswith('.pdf'):
107
  text_from_file = extract_text_from_pdf(file_upload)
108
  else:
109
+ return ["Error: Unsupported file type. Please upload a PPT, PPTX, or PDF file."], output_json_state, [None] * 10
110
 
111
  gr.Info("Preparing documents for quiz generation...")
112
  documents = [text_from_file]
 
121
  start_index = response_text.find('{')
122
  end_index = response_text.rfind('}')
123
  if start_index == -1 or end_index == -1:
124
+ return ["Error: Invalid JSON response from Groq Agent."], output_json_state, [None] * 10
125
  cleaned_response = response_text[start_index:end_index + 1]
126
  output_json = json.loads(cleaned_response)
127
  gr.Info("JSON response successfully processed.")
128
 
 
129
  question_radio_list = []
130
  for question_num in range(1, 11):
131
  question_key = f"Q{question_num}"
 
136
  question_radio_list.append(radio)
137
 
138
  gr.Info("Quiz generation completed successfully.")
139
+ return ['Quiz Generated!'], output_json, question_radio_list
140
 
141
  except json.JSONDecodeError as e:
142
  gr.Info("Error in processing JSON response.")
143
+ return [f"Error: Failed to decode JSON response. {e}"], output_json_state, [None] * 10
144
  except Exception as e:
145
  gr.Info("Error in quiz generation.")
146
+ return [f"Error: {str(e)}"], output_json_state, [None] * 10
147
 
148
  def compare_answers(*user_answers, output_json_state):
149
  user_answer_list = list(user_answers)
 
155
  answer = output_json_state.get(answer_key)
156
  if not answer:
157
  break
158
+ # Extract the choice text for comparison
159
+ choice_key = output_json_state.get(answer, "")
160
+ answers_list.append(choice_key)
161
 
162
+ score = sum(1 for user, correct in zip(user_answer_list, answers_list) if user == correct)
163
 
164
  if score > 7:
165
  message = f"### Excellent! You got {score} out of 10!"
 
171
  gr.Info("Score calculation completed.")
172
  return message
173
 
174
+ # Assign event handlers
175
  generate_quiz_btn.click(
176
  fn=generate_quiz,
177
+ inputs=[difficulty_radio, topic, file_upload, output_json_state],
178
+ outputs=[quiz_msg, output_json_state] + question_radios
179
  )
180
 
181
  check_button = gr.Button("Check Score")
 
191
  # import json
192
  # import gradio as gr
193
  # from pathlib import Path
194
+ # from pptx import Presentation
195
+ # from gradio_client import Client, handle_file
 
 
196
  # from tempfile import NamedTemporaryFile
197
+ # import os
198
+ # import logging
199
+ # from phi.agent import Agent
200
+ # from phi.model.groq import Groq
201
 
202
  # # Constants
 
 
203
  # proj_dir = Path.cwd()
204
 
205
  # # Set up logging
 
206
  # logging.basicConfig(level=logging.INFO)
207
  # logger = logging.getLogger(__name__)
208
 
209
+ # # Groq API Key setup
210
+ # api_key = os.getenv("GROQ_API_KEY")
211
+ # if not api_key:
212
+ # gr.Warning("GROQ_API_KEY not found. Set it in 'Repository secrets'.")
213
+ # logger.error("GROQ_API_KEY not found.")
214
+ # api_key = ""
215
+ # else:
216
+ # os.environ["GROQ_API_KEY"] = api_key
217
+
218
+ # # Initialize Groq Agent
219
+ # agent = Agent(
220
+ # name="Quiz Generator",
221
+ # role="You are an expert teacher creating quizzes for classroom evaluation.",
222
+ # instructions=[
223
+ # "You are a great teacher specializing in generating quizzes based on provided documents.",
224
+ # "Create accurate and relevant questions with four multiple-choice options.",
225
+ # "Ensure questions align with the specified difficulty level and topic.",
226
+ # "Provide responses in JSON format as specified in the prompt.",
227
+ # "Use only the provided document content for question generation."
228
+ # ],
229
+ # model=Groq(model_id="llama3-70b-8192", api_key=api_key),
230
+ # markdown=True
231
+ # )
232
+
233
+ # # Function to extract text from PDF using HuggingChat API
234
  # def extract_text_from_pdf(file_path):
235
+ # gr.Info("Extracting text from PDF file...")
 
 
 
 
 
236
  # client = Client("huggingchat/pdf-to-markdown")
 
237
  # try:
238
+ # result = client.predict(pdf_file=handle_file(file_path), api_name="/predict")
 
 
 
 
 
239
  # extracted_text = result[0] if isinstance(result, (list, tuple)) and len(result) > 0 else ""
240
  # print(extracted_text)
241
  # return extracted_text.strip()
 
242
  # except Exception as e:
243
  # print(f"Error extracting text from PDF: {e}")
244
  # return ""
245
 
246
+ # # Function to extract text from PPT/PPTX
247
+ # def extract_text_from_ppt(file_path):
248
+ # gr.Info("Extracting text from PPT/PPTX file...")
249
+ # presentation = Presentation(file_path)
250
+ # text_content = ""
251
+ # for slide in presentation.slides: # Fixed: Changed 'presentation' to 'presentation.slides'
252
+ # for shape in slide.shapes:
253
+ # if hasattr(shape, "text"):
254
+ # text_content += shape.text + " "
255
+ # gr.Info("Text extraction from PPT/PPTX completed.")
256
+ # return text_content.strip()
257
 
258
  # # Function to define instructions for quiz generation
259
  # def system_instructions(question_difficulty, topic, documents_str):
260
+ # gr.Info("Preparing instructions for Groq Agent...")
261
+ # return f"""You are a great teacher and your task is to create 10 questions with 4 multiple-choice options with {question_difficulty} difficulty about the topic "{topic}" only from the provided document: {documents_str}.
262
+ # Then create answers. Output in JSON format, indexing questions as "Q#":"" to "Q#":"", the four choices as "Q#:C1":"" to "Q#:C4":"", and the answers as "A#":"Q#:C#" to "A#":"Q#:C#". Example: 'A10':'Q10:C3'"""
263
 
264
  # # Function to convert JSON to Excel
265
  # def json_to_excel(output_json):
 
271
  # question = output_json.get(question_key, '')
272
  # correct_answer_key = output_json.get(answer_key, '')
273
  # correct_answer = correct_answer_key.split(':')[-1].replace('C', '').strip() if correct_answer_key else ''
274
+ # option_keys = [f"{question_key}:C{i}" for i in range(1, 5)]
275
  # options = [output_json.get(key, '') for key in option_keys]
276
 
277
  # data.append([
278
  # question, "Multiple Choice",
279
+ # options[0], options[1], options[2], options[3],
280
+ # "", correct_answer, 30, ''
 
281
  # ])
282
 
283
  # df = pd.DataFrame(data, columns=[
 
310
 
311
  # topic = gr.Textbox(label="(Optional)Enter the Topic for Quiz", placeholder="Any specific area in ppt")
312
  # file_upload = gr.File(label="Upload PPT/PPTX or PDF File", type="filepath")
 
313
  # with gr.Row():
314
+ # difficulty_radio = gr.Radio(["easy", "average", "hard"], value='easy', label="How difficult should the quiz be?")
315
  # model_radio = gr.Radio(choices=['(ACCURATE) BGE reranker', '(HIGH ACCURATE) ColBERT'],
316
+ # value='(ACCURATE) BGE reranker', label="Embeddings", visible=False)
317
+
318
+ # # State to store output_json
319
+ # output_json_state = gr.State(value={})
320
 
321
  # generate_quiz_btn = gr.Button("Generate Quiz!🚀")
322
  # quiz_msg = gr.Textbox()
323
  # question_radios = [gr.Radio(visible=False) for _ in range(10)]
324
+ # excel_output = gr.File(label="Download Excel")
325
 
326
+ # def generate_quiz(question_difficulty, topic, cross_encoder, file_upload, output_json_state):
 
327
  # if not file_upload:
328
+ # return ["Error: No file uploaded. Please upload a valid PPT, PPTX, or PDF file."], output_json_state, [None] * 10, None
329
 
 
330
  # gr.Info("Detecting file type and extracting text...")
331
  # if file_upload.lower().endswith('.pptx') or file_upload.lower().endswith('.ppt'):
332
  # text_from_file = extract_text_from_ppt(file_upload)
333
  # elif file_upload.lower().endswith('.pdf'):
334
  # text_from_file = extract_text_from_pdf(file_upload)
335
  # else:
336
+ # return ["Error: Unsupported file type. Please upload a PPT, PPTX, or PDF file."], output_json_state, [None] * 10, None
337
 
338
  # gr.Info("Preparing documents for quiz generation...")
339
  # documents = [text_from_file]
 
340
  # formatted_prompt = system_instructions(question_difficulty, topic, '\n'.join(documents))
341
 
342
  # try:
343
+ # gr.Info("Sending request to Groq Agent for quiz generation...")
344
+ # response = agent.run(formatted_prompt)
345
+ # response_text = response.content if hasattr(response, 'content') else str(response)
346
+
347
+ # gr.Info("Processing response from Groq Agent...")
348
+ # start_index = response_text.find('{')
349
+ # end_index = response_text.rfind('}')
350
+ # if start_index == -1 or end_index == -1:
351
+ # return ["Error: Invalid JSON response from Groq Agent."], output_json_state, [None] * 10, None
352
+ # cleaned_response = response_text[start_index:end_index + 1]
353
  # output_json = json.loads(cleaned_response)
354
  # gr.Info("JSON response successfully processed.")
355
 
356
  # excel_file = json_to_excel(output_json)
 
357
  # question_radio_list = []
358
  # for question_num in range(1, 11):
359
  # question_key = f"Q{question_num}"
360
  # question = output_json.get(question_key)
361
  # choice_keys = [f"{question_key}:C{i}" for i in range(1, 5)]
362
  # choice_list = [output_json.get(choice_key, "Choice not found") for choice_key in choice_keys]
 
363
  # radio = gr.Radio(choices=choice_list, label=question, visible=True, interactive=True)
364
  # question_radio_list.append(radio)
365
 
366
  # gr.Info("Quiz generation completed successfully.")
367
+ # return ['Quiz Generated!'], output_json, question_radio_list, excel_file
368
 
369
  # except json.JSONDecodeError as e:
370
  # gr.Info("Error in processing JSON response.")
371
+ # return [f"Error: Failed to decode JSON response. {e}"], output_json_state, [None] * 10, None
372
+ # except Exception as e:
373
+ # gr.Info("Error in quiz generation.")
374
+ # return [f"Error: {str(e)}"], output_json_state, [None] * 10, None
375
 
376
+ # def compare_answers(*user_answers, output_json_state):
 
377
  # user_answer_list = list(user_answers)
378
  # answers_list = []
379
 
380
  # gr.Info("Comparing user answers with correct answers...")
381
  # for question_num in range(1, 11):
382
  # answer_key = f"A{question_num}"
383
+ # answer = output_json_state.get(answer_key)
384
  # if not answer:
385
  # break
386
  # answers_list.append(answer)
 
397
  # gr.Info("Score calculation completed.")
398
  # return message
399
 
400
+ # # Assign event handlers without decorators
401
+ # generate_quiz_btn.click(
402
+ # fn=generate_quiz,
403
+ # inputs=[difficulty_radio, topic, model_radio, file_upload, output_json_state],
404
+ # outputs=[quiz_msg, output_json_state] + question_radios + [excel_output]
405
+ # )
406
+
407
+ # check_button = gr.Button("Check Score")
408
+ # score_textbox = gr.Markdown()
409
+ # check_button.click(
410
+ # fn=compare_answers,
411
+ # inputs=question_radios + [output_json_state],
412
+ # outputs=score_textbox
413
+ # )
414
+
415
  # QUIZBOT.queue()
416
+ # QUIZBOT.launch(debug=True)# import pandas as pd
417
+ # # import json
418
+ # # import gradio as gr
419
+ # # from pathlib import Path
420
+ # # from pptx import Presentation # Library to handle PPTX files
421
+ # # import PyPDF2 # Library to handle PDF files
422
+ # # #from ragatouille import RAGPretrainedModel
423
+ # # from gradio_client import Client,handle_file
424
+ # # from tempfile import NamedTemporaryFile
425
+ # # #from sentence_transformers import CrossEncoder
426
+ # # import numpy as np
427
+ # # #from backend.semantic_search import table, retriever
428
+
429
+ # # # Constants
430
+ # # VECTOR_COLUMN_NAME = "vector"
431
+ # # TEXT_COLUMN_NAME = "text"
432
+ # # proj_dir = Path.cwd()
433
+
434
+ # # # Set up logging
435
+ # # import logging
436
+ # # logging.basicConfig(level=logging.INFO)
437
+ # # logger = logging.getLogger(__name__)
438
+
439
+ # # # Replace Mixtral client with Qwen Client
440
+ # # client = Client("Qwen/Qwen1.5-110B-Chat-demo")
441
+
442
+ # # # # Function to extract text from PPT/PPTX
443
+ # # def extract_text_from_ppt(file_path):
444
+ # # gr.Info("Extracting text from PPT/PPTX file...")
445
+ # # presentation = Presentation(file_path)
446
+ # # text_content = ""
447
+ # # for slide in presentation.slides:
448
+ # # for shape in slide.shapes:
449
+ # # if hasattr(shape, "text"):
450
+ # # text_content += shape.text + " "
451
+ # # gr.Info("Text extraction from PPT/PPTX completed.")
452
+ # # return text_content.strip()
453
+ # # from gradio_client import Client, handle_file
454
+
455
+ # # def extract_text_from_pdf(file_path):
456
+ # # """
457
+ # # Extracts text from a PDF using the HuggingChat API for PDF-to-Markdown conversion.
458
+
459
+ # # :param file_path: Path to the PDF file.
460
+ # # :return: Extracted text from the PDF.
461
+ # # """
462
+ # # client = Client("huggingchat/pdf-to-markdown")
463
+
464
+ # # try:
465
+ # # result = client.predict(
466
+ # # pdf_file=handle_file(file_path),
467
+ # # api_name="/predict"
468
+ # # )
469
+
470
+ # # # The extracted text is in result[0], metadata is in result[1]
471
+ # # extracted_text = result[0] if isinstance(result, (list, tuple)) and len(result) > 0 else ""
472
+ # # print(extracted_text)
473
+ # # return extracted_text.strip()
474
+
475
+ # # except Exception as e:
476
+ # # print(f"Error extracting text from PDF: {e}")
477
+ # # return ""
478
+
479
+ # # # # Function to extract text from PDF
480
+ # # # def extract_text_from_pdf(file_path):
481
+ # # # gr.Info("Extracting text from PDF file...")
482
+ # # # text_content = ""
483
+ # # # with open(file_path, 'rb') as pdf_file:
484
+ # # # pdf_reader = PyPDF2.PdfReader(pdf_file)
485
+ # # # for page in pdf_reader.pages:
486
+ # # # text_content += page.extract_text() or ""
487
+ # # # gr.Info("Text extraction from PDF completed.")
488
+ # # # return text_content.strip()
489
+
490
+ # # # Function to define instructions for quiz generation
491
+ # # def system_instructions(question_difficulty, topic, documents_str):
492
+ # # gr.Info("Preparing instructions for Qwen API...")
493
+ # # return f"""<s> [INST] You are a great teacher and your task is to create 10 questions with 4 choices with {question_difficulty} difficulty about the topic \"{topic}\" only from the below documents: {documents_str}.
494
+ # # Then create answers. Index in JSON format, the questions as \"Q#\":\"\" to \"Q#\":\"\", the four choices as \"Q#:C1\":\"\" to \"Q#:C4\":\"\", and the answers as \"A#\":\"Q#:C#\" to \"A#\":\"Q#:C#\". Example: 'A10':'Q10:C3' [/INST]"""
495
+
496
+ # # # Function to convert JSON to Excel
497
+ # # def json_to_excel(output_json):
498
+ # # gr.Info("Converting JSON response to Excel format...")
499
+ # # data = []
500
+ # # for i in range(1, 11):
501
+ # # question_key = f"Q{i}"
502
+ # # answer_key = f"A{i}"
503
+ # # question = output_json.get(question_key, '')
504
+ # # correct_answer_key = output_json.get(answer_key, '')
505
+ # # correct_answer = correct_answer_key.split(':')[-1].replace('C', '').strip() if correct_answer_key else ''
506
+ # # option_keys = [f"{question_key}:C{i}" for i in range(1, 6)]
507
+ # # options = [output_json.get(key, '') for key in option_keys]
508
+
509
+ # # data.append([
510
+ # # question, "Multiple Choice",
511
+ # # options[0], options[1], options[2] if len(options) > 2 else '',
512
+ # # options[3] if len(options) > 3 else '', options[4] if len(options) > 4 else '',
513
+ # # correct_answer, 30, ''
514
+ # # ])
515
+
516
+ # # df = pd.DataFrame(data, columns=[
517
+ # # "Question Text", "Question Type", "Option 1", "Option 2",
518
+ # # "Option 3", "Option 4", "Option 5", "Correct Answer",
519
+ # # "Time in seconds", "Image Link"
520
+ # # ])
521
+
522
+ # # temp_file = NamedTemporaryFile(delete=False, suffix=".xlsx")
523
+ # # df.to_excel(temp_file.name, index=False)
524
+ # # gr.Info("Excel file generated successfully.")
525
+ # # return temp_file.name
526
+
527
+ # # # Define theme
528
+ # # colorful_theme = gr.themes.Default(primary_hue="cyan", secondary_hue="yellow", neutral_hue="purple")
529
+
530
+ # # # Define the Gradio interface
531
+ # # with gr.Blocks(title="Quiz Maker", theme=colorful_theme) as QUIZBOT:
532
+ # # with gr.Row():
533
+ # # with gr.Column(scale=2):
534
+ # # gr.Image(value='logo.png', height=200, width=200)
535
+ # # with gr.Column(scale=6):
536
+ # # gr.HTML("""
537
+ # # <center>
538
+ # # <h1><span style="color: purple;">ADWITIYA</span> NACIN PPT Quizbot</h1>
539
+ # # <h2>Generative AI-powered Capacity building for Training Officers</h2>
540
+ # # <i>⚠️ NACIN Faculties create quiz dynamically for classroom evaluation! ⚠️</i>
541
+ # # </center>
542
+ # # """)
543
+
544
+ # # topic = gr.Textbox(label="(Optional)Enter the Topic for Quiz", placeholder="Any specific area in ppt")
545
+ # # file_upload = gr.File(label="Upload PPT/PPTX or PDF File", type="filepath")
546
+
547
+ # # with gr.Row():
548
+ # # difficulty_radio = gr.Radio(["easy", "average", "hard"],value='easy', label="How difficult should the quiz be?")#,visible=False)
549
+ # # model_radio = gr.Radio(choices=['(ACCURATE) BGE reranker', '(HIGH ACCURATE) ColBERT'],
550
+ # # value='(ACCURATE) BGE reranker', label="Embeddings",visible=False)
551
+
552
+ # # generate_quiz_btn = gr.Button("Generate Quiz!🚀")
553
+ # # quiz_msg = gr.Textbox()
554
+ # # question_radios = [gr.Radio(visible=False) for _ in range(10)]
555
+
556
+ # # @generate_quiz_btn.click(inputs=[difficulty_radio, topic, model_radio, file_upload], outputs=[quiz_msg] + question_radios + [gr.File(label="Download Excel")])
557
+ # # def generate_quiz(question_difficulty, topic, cross_encoder, file_upload):
558
+ # # if not file_upload:
559
+ # # return ["Error: No file uploaded. Please upload a valid PPT, PPTX, or PDF file."]
560
+
561
+ # # # Detect file type and extract text accordingly
562
+ # # gr.Info("Detecting file type and extracting text...")
563
+ # # if file_upload.lower().endswith('.pptx') or file_upload.lower().endswith('.ppt'):
564
+ # # text_from_file = extract_text_from_ppt(file_upload)
565
+ # # elif file_upload.lower().endswith('.pdf'):
566
+ # # text_from_file = extract_text_from_pdf(file_upload)
567
+ # # else:
568
+ # # return ["Error: Unsupported file type. Please upload a PPT, PPTX, or PDF file."]
569
+
570
+ # # gr.Info("Preparing documents for quiz generation...")
571
+ # # documents = [text_from_file]
572
+
573
+ # # formatted_prompt = system_instructions(question_difficulty, topic, '\n'.join(documents))
574
+
575
+ # # try:
576
+ # # gr.Info("Sending request to Qwen API for quiz generation...")
577
+ # # response = client.predict(query=formatted_prompt, history=[], system="You are a helpful assistant.", api_name="/model_chat")
578
+ # # response1 = response[1][0][1]
579
+
580
+ # # gr.Info("Processing response from Qwen API...")
581
+ # # start_index = response1.find('{')
582
+ # # end_index = response1.rfind('}')
583
+ # # cleaned_response = response1[start_index:end_index + 1] if start_index != -1 and end_index != -1 else ''
584
+ # # output_json = json.loads(cleaned_response)
585
+ # # gr.Info("JSON response successfully processed.")
586
+
587
+ # # excel_file = json_to_excel(output_json)
588
+
589
+ # # question_radio_list = []
590
+ # # for question_num in range(1, 11):
591
+ # # question_key = f"Q{question_num}"
592
+ # # question = output_json.get(question_key)
593
+ # # choice_keys = [f"{question_key}:C{i}" for i in range(1, 5)]
594
+ # # choice_list = [output_json.get(choice_key, "Choice not found") for choice_key in choice_keys]
595
+
596
+ # # radio = gr.Radio(choices=choice_list, label=question, visible=True, interactive=True)
597
+ # # question_radio_list.append(radio)
598
+
599
+ # # gr.Info("Quiz generation completed successfully.")
600
+ # # return ['Quiz Generated!'] + question_radio_list + [excel_file]
601
+
602
+ # # except json.JSONDecodeError as e:
603
+ # # gr.Info("Error in processing JSON response.")
604
+ # # return [f"Error: Failed to decode JSON response. {e}"]
605
+
606
+ # # check_button = gr.Button("Check Score")
607
+ # # score_textbox = gr.Markdown()
608
+
609
+ # # @check_button.click(inputs=question_radios, outputs=score_textbox)
610
+ # # def compare_answers(*user_answers):
611
+ # # user_answer_list = list(user_answers)
612
+ # # answers_list = []
613
+
614
+ # # gr.Info("Comparing user answers with correct answers...")
615
+ # # for question_num in range(1, 11):
616
+ # # answer_key = f"A{question_num}"
617
+ # # answer = quiz_data.get(quiz_data.get(answer_key))
618
+ # # if not answer:
619
+ # # break
620
+ # # answers_list.append(answer)
621
+
622
+ # # score = sum(1 for item in user_answer_list if item in answers_list)
623
+
624
+ # # if score > 7:
625
+ # # message = f"### Excellent! You got {score} out of 10!"
626
+ # # elif score > 5:
627
+ # # message = f"### Good! You got {score} out of 10!"
628
+ # # else:
629
+ # # message = f"### You got {score} out of 10! Don't worry. You can prepare well and try better next time!"
630
+
631
+ # # gr.Info("Score calculation completed.")
632
+ # # return message
633
+
634
+ # # QUIZBOT.queue()
635
+ # # QUIZBOT.launch(debug=True)