Spaces:
Sleeping
Sleeping
Download app.py from NCTCMumbai/NACIN_PPT_Quizbot: direct link, hf CLI and curl.
- Browser
- Download file 28.9 kB
-
https://huggingface.co/spaces/NCTCMumbai/NACIN_PPT_Quizbot/resolve/main/app.py
- Command line
-
hf download hf://spaces/NCTCMumbai/NACIN_PPT_Quizbot/app.py
-
curl -L -o app.py https://huggingface.co/spaces/NCTCMumbai/NACIN_PPT_Quizbot/resolve/main/app.py
28.9 kB
| import pandas as pd | |
| import json | |
| import gradio as gr | |
| from pathlib import Path | |
| from pptx import Presentation | |
| from gradio_client import Client, handle_file | |
| import os | |
| import logging | |
| from phi.agent import Agent | |
| from phi.model.groq import Groq | |
| # Set up logging | |
| logging.basicConfig(level=logging.INFO) | |
| logger = logging.getLogger(__name__) | |
| # Groq API Key setup | |
| api_key = os.getenv("GROQ_API_KEY") | |
| if not api_key: | |
| gr.Warning("GROQ_API_KEY not found. Set it in 'Repository secrets'.") | |
| logger.error("GROQ_API_KEY not found.") | |
| api_key = "" | |
| else: | |
| os.environ["GROQ_API_KEY"] = api_key | |
| # Initialize Groq Agent | |
| agent = Agent( | |
| name="Quiz Generator", | |
| role="You are an expert teacher creating quizzes for classroom evaluation.", | |
| instructions=[ | |
| "You are a great teacher specializing in generating quizzes based on provided documents.", | |
| "Create accurate and relevant questions with four multiple-choice options.", | |
| "Ensure questions align with the specified difficulty level and topic.", | |
| "Provide responses in JSON format as specified in the prompt.", | |
| "Use only the provided document content for question generation." | |
| ], | |
| model=Groq(model_id="llama3-70b-8192", api_key=api_key), | |
| markdown=True | |
| ) | |
| # Function to extract text from PDF using HuggingChat API | |
| def extract_text_from_pdf(file_path): | |
| gr.Info("Extracting text from PDF file...") | |
| client = Client("huggingchat/pdf-to-markdown") | |
| try: | |
| result = client.predict(pdf_file=handle_file(file_path), api_name="/predict") | |
| extracted_text = result[0] if isinstance(result, (list, tuple)) and len(result) > 0 else "" | |
| print(extracted_text) | |
| return extracted_text.strip() | |
| except Exception as e: | |
| print(f"Error extracting text from PDF: {e}") | |
| return "" | |
| # Function to extract text from PPT/PPTX | |
| def extract_text_from_ppt(file_path): | |
| gr.Info("Extracting text from PPT/PPTX file...") | |
| presentation = Presentation(file_path) | |
| text_content = "" | |
| for slide in presentation.slides: | |
| for shape in slide.shapes: | |
| if hasattr(shape, "text"): | |
| text_content += shape.text + " " | |
| gr.Info("Text extraction from PPT/PPTX completed.") | |
| return text_content.strip() | |
| # Function to define instructions for quiz generation | |
| def system_instructions(question_difficulty, topic, documents_str): | |
| gr.Info("Preparing instructions for Groq Agent...") | |
| 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}. | |
| 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'""" | |
| # Define theme | |
| colorful_theme = gr.themes.Default(primary_hue="cyan", secondary_hue="yellow", neutral_hue="purple") | |
| # Define the Gradio interface | |
| with gr.Blocks(title="Quiz Maker", theme=colorful_theme) as QUIZBOT: | |
| with gr.Row(): | |
| with gr.Column(scale=2): | |
| gr.Image(value='logo.png', height=200, width=200) | |
| with gr.Column(scale=6): | |
| gr.HTML(""" | |
| <center> | |
| <h1><span style="color: purple;">ADWITIYA</span> NACIN PPT Quizbot</h1> | |
| <h2>Generative AI-powered Capacity building for Training Officers</h2> | |
| <i>⚠️ NACIN Faculties create quiz dynamically for classroom evaluation! ⚠️</i> | |
| </center> | |
| """) | |
| topic = gr.Textbox(label="Enter the Topic for Quiz (Optional)", placeholder="Any specific area in ppt") | |
| file_upload = gr.File(label="Upload PPT/PPTX or PDF File", type="filepath") | |
| difficulty_radio = gr.Radio(["easy", "average", "hard"], value='easy', label="How difficult should the quiz be?") | |
| # State to store output_json | |
| output_json_state = gr.State(value={}) | |
| generate_quiz_btn = gr.Button("Generate Quiz!🚀") | |
| quiz_msg = gr.Textbox() | |
| question_radios = [gr.Radio(visible=False) for _ in range(10)] | |
| def generate_quiz(question_difficulty, topic, file_upload, output_json_state): | |
| if not file_upload: | |
| return ["Error: No file uploaded. Please upload a valid PPT, PPTX, or PDF file."], output_json_state, [None] * 10 | |
| gr.Info("Detecting file type and extracting text...") | |
| if file_upload.lower().endswith('.pptx') or file_upload.lower().endswith('.ppt'): | |
| text_from_file = extract_text_from_ppt(file_upload) | |
| elif file_upload.lower().endswith('.pdf'): | |
| text_from_file = extract_text_from_pdf(file_upload) | |
| else: | |
| return ["Error: Unsupported file type. Please upload a PPT, PPTX, or PDF file."], output_json_state, [None] * 10 | |
| gr.Info("Preparing documents for quiz generation...") | |
| documents = [text_from_file] | |
| formatted_prompt = system_instructions(question_difficulty, topic, '\n'.join(documents)) | |
| try: | |
| gr.Info("Sending request to Groq Agent for quiz generation...") | |
| response = agent.run(formatted_prompt) | |
| response_text = response.content if hasattr(response, 'content') else str(response) | |
| gr.Info("Processing response from Groq Agent...") | |
| start_index = response_text.find('{') | |
| end_index = response_text.rfind('}') | |
| if start_index == -1 or end_index == -1: | |
| return ["Error: Invalid JSON response from Groq Agent."], output_json_state, [None] * 10 | |
| cleaned_response = response_text[start_index:end_index + 1] | |
| output_json = json.loads(cleaned_response) | |
| gr.Info("JSON response successfully processed.") | |
| question_radio_list = [] | |
| for question_num in range(1, 11): | |
| question_key = f"Q{question_num}" | |
| question = output_json.get(question_key) | |
| choice_keys = [f"{question_key}:C{i}" for i in range(1, 5)] | |
| choice_list = [output_json.get(choice_key, "Choice not found") for choice_key in choice_keys] | |
| radio = gr.Radio(choices=choice_list, label=question, visible=True, interactive=True) | |
| question_radio_list.append(radio) | |
| gr.Info("Quiz generation completed successfully.") | |
| return ['Quiz Generated!'], output_json, question_radio_list | |
| except json.JSONDecodeError as e: | |
| gr.Info("Error in processing JSON response.") | |
| return [f"Error: Failed to decode JSON response. {e}"], output_json_state, [None] * 10 | |
| except Exception as e: | |
| gr.Info("Error in quiz generation.") | |
| return [f"Error: {str(e)}"], output_json_state, [None] * 10 | |
| def compare_answers(*user_answers, output_json_state): | |
| user_answer_list = list(user_answers) | |
| answers_list = [] | |
| gr.Info("Comparing user answers with correct answers...") | |
| for question_num in range(1, 11): | |
| answer_key = f"A{question_num}" | |
| answer = output_json_state.get(answer_key) | |
| if not answer: | |
| break | |
| # Extract the choice text for comparison | |
| choice_key = output_json_state.get(answer, "") | |
| answers_list.append(choice_key) | |
| score = sum(1 for user, correct in zip(user_answer_list, answers_list) if user == correct) | |
| if score > 7: | |
| message = f"### Excellent! You got {score} out of 10!" | |
| elif score > 5: | |
| message = f"### Good! You got {score} out of 10!" | |
| else: | |
| message = f"### You got {score} out of 10! Don't worry. You can prepare well and try better next time!" | |
| gr.Info("Score calculation completed.") | |
| return message | |
| # Assign event handlers | |
| generate_quiz_btn.click( | |
| fn=generate_quiz, | |
| inputs=[difficulty_radio, topic, file_upload, output_json_state], | |
| outputs=[quiz_msg, output_json_state] + question_radios | |
| ) | |
| check_button = gr.Button("Check Score") | |
| score_textbox = gr.Markdown() | |
| check_button.click( | |
| fn=compare_answers, | |
| inputs=question_radios + [output_json_state], | |
| outputs=score_textbox | |
| ) | |
| QUIZBOT.queue() | |
| QUIZBOT.launch(debug=True)# import pandas as pd | |
| # import json | |
| # import gradio as gr | |
| # from pathlib import Path | |
| # from pptx import Presentation | |
| # from gradio_client import Client, handle_file | |
| # from tempfile import NamedTemporaryFile | |
| # import os | |
| # import logging | |
| # from phi.agent import Agent | |
| # from phi.model.groq import Groq | |
| # # Constants | |
| # proj_dir = Path.cwd() | |
| # # Set up logging | |
| # logging.basicConfig(level=logging.INFO) | |
| # logger = logging.getLogger(__name__) | |
| # # Groq API Key setup | |
| # api_key = os.getenv("GROQ_API_KEY") | |
| # if not api_key: | |
| # gr.Warning("GROQ_API_KEY not found. Set it in 'Repository secrets'.") | |
| # logger.error("GROQ_API_KEY not found.") | |
| # api_key = "" | |
| # else: | |
| # os.environ["GROQ_API_KEY"] = api_key | |
| # # Initialize Groq Agent | |
| # agent = Agent( | |
| # name="Quiz Generator", | |
| # role="You are an expert teacher creating quizzes for classroom evaluation.", | |
| # instructions=[ | |
| # "You are a great teacher specializing in generating quizzes based on provided documents.", | |
| # "Create accurate and relevant questions with four multiple-choice options.", | |
| # "Ensure questions align with the specified difficulty level and topic.", | |
| # "Provide responses in JSON format as specified in the prompt.", | |
| # "Use only the provided document content for question generation." | |
| # ], | |
| # model=Groq(model_id="llama3-70b-8192", api_key=api_key), | |
| # markdown=True | |
| # ) | |
| # # Function to extract text from PDF using HuggingChat API | |
| # def extract_text_from_pdf(file_path): | |
| # gr.Info("Extracting text from PDF file...") | |
| # client = Client("huggingchat/pdf-to-markdown") | |
| # try: | |
| # result = client.predict(pdf_file=handle_file(file_path), api_name="/predict") | |
| # extracted_text = result[0] if isinstance(result, (list, tuple)) and len(result) > 0 else "" | |
| # print(extracted_text) | |
| # return extracted_text.strip() | |
| # except Exception as e: | |
| # print(f"Error extracting text from PDF: {e}") | |
| # return "" | |
| # # Function to extract text from PPT/PPTX | |
| # def extract_text_from_ppt(file_path): | |
| # gr.Info("Extracting text from PPT/PPTX file...") | |
| # presentation = Presentation(file_path) | |
| # text_content = "" | |
| # for slide in presentation.slides: # Fixed: Changed 'presentation' to 'presentation.slides' | |
| # for shape in slide.shapes: | |
| # if hasattr(shape, "text"): | |
| # text_content += shape.text + " " | |
| # gr.Info("Text extraction from PPT/PPTX completed.") | |
| # return text_content.strip() | |
| # # Function to define instructions for quiz generation | |
| # def system_instructions(question_difficulty, topic, documents_str): | |
| # gr.Info("Preparing instructions for Groq Agent...") | |
| # 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}. | |
| # 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'""" | |
| # # Function to convert JSON to Excel | |
| # def json_to_excel(output_json): | |
| # gr.Info("Converting JSON response to Excel format...") | |
| # data = [] | |
| # for i in range(1, 11): | |
| # question_key = f"Q{i}" | |
| # answer_key = f"A{i}" | |
| # question = output_json.get(question_key, '') | |
| # correct_answer_key = output_json.get(answer_key, '') | |
| # correct_answer = correct_answer_key.split(':')[-1].replace('C', '').strip() if correct_answer_key else '' | |
| # option_keys = [f"{question_key}:C{i}" for i in range(1, 5)] | |
| # options = [output_json.get(key, '') for key in option_keys] | |
| # data.append([ | |
| # question, "Multiple Choice", | |
| # options[0], options[1], options[2], options[3], | |
| # "", correct_answer, 30, '' | |
| # ]) | |
| # df = pd.DataFrame(data, columns=[ | |
| # "Question Text", "Question Type", "Option 1", "Option 2", | |
| # "Option 3", "Option 4", "Option 5", "Correct Answer", | |
| # "Time in seconds", "Image Link" | |
| # ]) | |
| # temp_file = NamedTemporaryFile(delete=False, suffix=".xlsx") | |
| # df.to_excel(temp_file.name, index=False) | |
| # gr.Info("Excel file generated successfully.") | |
| # return temp_file.name | |
| # # Define theme | |
| # colorful_theme = gr.themes.Default(primary_hue="cyan", secondary_hue="yellow", neutral_hue="purple") | |
| # # Define the Gradio interface | |
| # with gr.Blocks(title="Quiz Maker", theme=colorful_theme) as QUIZBOT: | |
| # with gr.Row(): | |
| # with gr.Column(scale=2): | |
| # gr.Image(value='logo.png', height=200, width=200) | |
| # with gr.Column(scale=6): | |
| # gr.HTML(""" | |
| # <center> | |
| # <h1><span style="color: purple;">ADWITIYA</span> NACIN PPT Quizbot</h1> | |
| # <h2>Generative AI-powered Capacity building for Training Officers</h2> | |
| # <i>⚠️ NACIN Faculties create quiz dynamically for classroom evaluation! ⚠️</i> | |
| # </center> | |
| # """) | |
| # topic = gr.Textbox(label="(Optional)Enter the Topic for Quiz", placeholder="Any specific area in ppt") | |
| # file_upload = gr.File(label="Upload PPT/PPTX or PDF File", type="filepath") | |
| # with gr.Row(): | |
| # difficulty_radio = gr.Radio(["easy", "average", "hard"], value='easy', label="How difficult should the quiz be?") | |
| # model_radio = gr.Radio(choices=['(ACCURATE) BGE reranker', '(HIGH ACCURATE) ColBERT'], | |
| # value='(ACCURATE) BGE reranker', label="Embeddings", visible=False) | |
| # # State to store output_json | |
| # output_json_state = gr.State(value={}) | |
| # generate_quiz_btn = gr.Button("Generate Quiz!🚀") | |
| # quiz_msg = gr.Textbox() | |
| # question_radios = [gr.Radio(visible=False) for _ in range(10)] | |
| # excel_output = gr.File(label="Download Excel") | |
| # def generate_quiz(question_difficulty, topic, cross_encoder, file_upload, output_json_state): | |
| # if not file_upload: | |
| # return ["Error: No file uploaded. Please upload a valid PPT, PPTX, or PDF file."], output_json_state, [None] * 10, None | |
| # gr.Info("Detecting file type and extracting text...") | |
| # if file_upload.lower().endswith('.pptx') or file_upload.lower().endswith('.ppt'): | |
| # text_from_file = extract_text_from_ppt(file_upload) | |
| # elif file_upload.lower().endswith('.pdf'): | |
| # text_from_file = extract_text_from_pdf(file_upload) | |
| # else: | |
| # return ["Error: Unsupported file type. Please upload a PPT, PPTX, or PDF file."], output_json_state, [None] * 10, None | |
| # gr.Info("Preparing documents for quiz generation...") | |
| # documents = [text_from_file] | |
| # formatted_prompt = system_instructions(question_difficulty, topic, '\n'.join(documents)) | |
| # try: | |
| # gr.Info("Sending request to Groq Agent for quiz generation...") | |
| # response = agent.run(formatted_prompt) | |
| # response_text = response.content if hasattr(response, 'content') else str(response) | |
| # gr.Info("Processing response from Groq Agent...") | |
| # start_index = response_text.find('{') | |
| # end_index = response_text.rfind('}') | |
| # if start_index == -1 or end_index == -1: | |
| # return ["Error: Invalid JSON response from Groq Agent."], output_json_state, [None] * 10, None | |
| # cleaned_response = response_text[start_index:end_index + 1] | |
| # output_json = json.loads(cleaned_response) | |
| # gr.Info("JSON response successfully processed.") | |
| # excel_file = json_to_excel(output_json) | |
| # question_radio_list = [] | |
| # for question_num in range(1, 11): | |
| # question_key = f"Q{question_num}" | |
| # question = output_json.get(question_key) | |
| # choice_keys = [f"{question_key}:C{i}" for i in range(1, 5)] | |
| # choice_list = [output_json.get(choice_key, "Choice not found") for choice_key in choice_keys] | |
| # radio = gr.Radio(choices=choice_list, label=question, visible=True, interactive=True) | |
| # question_radio_list.append(radio) | |
| # gr.Info("Quiz generation completed successfully.") | |
| # return ['Quiz Generated!'], output_json, question_radio_list, excel_file | |
| # except json.JSONDecodeError as e: | |
| # gr.Info("Error in processing JSON response.") | |
| # return [f"Error: Failed to decode JSON response. {e}"], output_json_state, [None] * 10, None | |
| # except Exception as e: | |
| # gr.Info("Error in quiz generation.") | |
| # return [f"Error: {str(e)}"], output_json_state, [None] * 10, None | |
| # def compare_answers(*user_answers, output_json_state): | |
| # user_answer_list = list(user_answers) | |
| # answers_list = [] | |
| # gr.Info("Comparing user answers with correct answers...") | |
| # for question_num in range(1, 11): | |
| # answer_key = f"A{question_num}" | |
| # answer = output_json_state.get(answer_key) | |
| # if not answer: | |
| # break | |
| # answers_list.append(answer) | |
| # score = sum(1 for item in user_answer_list if item in answers_list) | |
| # if score > 7: | |
| # message = f"### Excellent! You got {score} out of 10!" | |
| # elif score > 5: | |
| # message = f"### Good! You got {score} out of 10!" | |
| # else: | |
| # message = f"### You got {score} out of 10! Don't worry. You can prepare well and try better next time!" | |
| # gr.Info("Score calculation completed.") | |
| # return message | |
| # # Assign event handlers without decorators | |
| # generate_quiz_btn.click( | |
| # fn=generate_quiz, | |
| # inputs=[difficulty_radio, topic, model_radio, file_upload, output_json_state], | |
| # outputs=[quiz_msg, output_json_state] + question_radios + [excel_output] | |
| # ) | |
| # check_button = gr.Button("Check Score") | |
| # score_textbox = gr.Markdown() | |
| # check_button.click( | |
| # fn=compare_answers, | |
| # inputs=question_radios + [output_json_state], | |
| # outputs=score_textbox | |
| # ) | |
| # QUIZBOT.queue() | |
| # QUIZBOT.launch(debug=True)# import pandas as pd | |
| # # import json | |
| # # import gradio as gr | |
| # # from pathlib import Path | |
| # # from pptx import Presentation # Library to handle PPTX files | |
| # # import PyPDF2 # Library to handle PDF files | |
| # # #from ragatouille import RAGPretrainedModel | |
| # # from gradio_client import Client,handle_file | |
| # # from tempfile import NamedTemporaryFile | |
| # # #from sentence_transformers import CrossEncoder | |
| # # import numpy as np | |
| # # #from backend.semantic_search import table, retriever | |
| # # # Constants | |
| # # VECTOR_COLUMN_NAME = "vector" | |
| # # TEXT_COLUMN_NAME = "text" | |
| # # proj_dir = Path.cwd() | |
| # # # Set up logging | |
| # # import logging | |
| # # logging.basicConfig(level=logging.INFO) | |
| # # logger = logging.getLogger(__name__) | |
| # # # Replace Mixtral client with Qwen Client | |
| # # client = Client("Qwen/Qwen1.5-110B-Chat-demo") | |
| # # # # Function to extract text from PPT/PPTX | |
| # # def extract_text_from_ppt(file_path): | |
| # # gr.Info("Extracting text from PPT/PPTX file...") | |
| # # presentation = Presentation(file_path) | |
| # # text_content = "" | |
| # # for slide in presentation.slides: | |
| # # for shape in slide.shapes: | |
| # # if hasattr(shape, "text"): | |
| # # text_content += shape.text + " " | |
| # # gr.Info("Text extraction from PPT/PPTX completed.") | |
| # # return text_content.strip() | |
| # # from gradio_client import Client, handle_file | |
| # # def extract_text_from_pdf(file_path): | |
| # # """ | |
| # # Extracts text from a PDF using the HuggingChat API for PDF-to-Markdown conversion. | |
| # # :param file_path: Path to the PDF file. | |
| # # :return: Extracted text from the PDF. | |
| # # """ | |
| # # client = Client("huggingchat/pdf-to-markdown") | |
| # # try: | |
| # # result = client.predict( | |
| # # pdf_file=handle_file(file_path), | |
| # # api_name="/predict" | |
| # # ) | |
| # # # The extracted text is in result[0], metadata is in result[1] | |
| # # extracted_text = result[0] if isinstance(result, (list, tuple)) and len(result) > 0 else "" | |
| # # print(extracted_text) | |
| # # return extracted_text.strip() | |
| # # except Exception as e: | |
| # # print(f"Error extracting text from PDF: {e}") | |
| # # return "" | |
| # # # # Function to extract text from PDF | |
| # # # def extract_text_from_pdf(file_path): | |
| # # # gr.Info("Extracting text from PDF file...") | |
| # # # text_content = "" | |
| # # # with open(file_path, 'rb') as pdf_file: | |
| # # # pdf_reader = PyPDF2.PdfReader(pdf_file) | |
| # # # for page in pdf_reader.pages: | |
| # # # text_content += page.extract_text() or "" | |
| # # # gr.Info("Text extraction from PDF completed.") | |
| # # # return text_content.strip() | |
| # # # Function to define instructions for quiz generation | |
| # # def system_instructions(question_difficulty, topic, documents_str): | |
| # # gr.Info("Preparing instructions for Qwen API...") | |
| # # 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}. | |
| # # 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]""" | |
| # # # Function to convert JSON to Excel | |
| # # def json_to_excel(output_json): | |
| # # gr.Info("Converting JSON response to Excel format...") | |
| # # data = [] | |
| # # for i in range(1, 11): | |
| # # question_key = f"Q{i}" | |
| # # answer_key = f"A{i}" | |
| # # question = output_json.get(question_key, '') | |
| # # correct_answer_key = output_json.get(answer_key, '') | |
| # # correct_answer = correct_answer_key.split(':')[-1].replace('C', '').strip() if correct_answer_key else '' | |
| # # option_keys = [f"{question_key}:C{i}" for i in range(1, 6)] | |
| # # options = [output_json.get(key, '') for key in option_keys] | |
| # # data.append([ | |
| # # question, "Multiple Choice", | |
| # # options[0], options[1], options[2] if len(options) > 2 else '', | |
| # # options[3] if len(options) > 3 else '', options[4] if len(options) > 4 else '', | |
| # # correct_answer, 30, '' | |
| # # ]) | |
| # # df = pd.DataFrame(data, columns=[ | |
| # # "Question Text", "Question Type", "Option 1", "Option 2", | |
| # # "Option 3", "Option 4", "Option 5", "Correct Answer", | |
| # # "Time in seconds", "Image Link" | |
| # # ]) | |
| # # temp_file = NamedTemporaryFile(delete=False, suffix=".xlsx") | |
| # # df.to_excel(temp_file.name, index=False) | |
| # # gr.Info("Excel file generated successfully.") | |
| # # return temp_file.name | |
| # # # Define theme | |
| # # colorful_theme = gr.themes.Default(primary_hue="cyan", secondary_hue="yellow", neutral_hue="purple") | |
| # # # Define the Gradio interface | |
| # # with gr.Blocks(title="Quiz Maker", theme=colorful_theme) as QUIZBOT: | |
| # # with gr.Row(): | |
| # # with gr.Column(scale=2): | |
| # # gr.Image(value='logo.png', height=200, width=200) | |
| # # with gr.Column(scale=6): | |
| # # gr.HTML(""" | |
| # # <center> | |
| # # <h1><span style="color: purple;">ADWITIYA</span> NACIN PPT Quizbot</h1> | |
| # # <h2>Generative AI-powered Capacity building for Training Officers</h2> | |
| # # <i>⚠️ NACIN Faculties create quiz dynamically for classroom evaluation! ⚠️</i> | |
| # # </center> | |
| # # """) | |
| # # topic = gr.Textbox(label="(Optional)Enter the Topic for Quiz", placeholder="Any specific area in ppt") | |
| # # file_upload = gr.File(label="Upload PPT/PPTX or PDF File", type="filepath") | |
| # # with gr.Row(): | |
| # # difficulty_radio = gr.Radio(["easy", "average", "hard"],value='easy', label="How difficult should the quiz be?")#,visible=False) | |
| # # model_radio = gr.Radio(choices=['(ACCURATE) BGE reranker', '(HIGH ACCURATE) ColBERT'], | |
| # # value='(ACCURATE) BGE reranker', label="Embeddings",visible=False) | |
| # # generate_quiz_btn = gr.Button("Generate Quiz!🚀") | |
| # # quiz_msg = gr.Textbox() | |
| # # question_radios = [gr.Radio(visible=False) for _ in range(10)] | |
| # # @generate_quiz_btn.click(inputs=[difficulty_radio, topic, model_radio, file_upload], outputs=[quiz_msg] + question_radios + [gr.File(label="Download Excel")]) | |
| # # def generate_quiz(question_difficulty, topic, cross_encoder, file_upload): | |
| # # if not file_upload: | |
| # # return ["Error: No file uploaded. Please upload a valid PPT, PPTX, or PDF file."] | |
| # # # Detect file type and extract text accordingly | |
| # # gr.Info("Detecting file type and extracting text...") | |
| # # if file_upload.lower().endswith('.pptx') or file_upload.lower().endswith('.ppt'): | |
| # # text_from_file = extract_text_from_ppt(file_upload) | |
| # # elif file_upload.lower().endswith('.pdf'): | |
| # # text_from_file = extract_text_from_pdf(file_upload) | |
| # # else: | |
| # # return ["Error: Unsupported file type. Please upload a PPT, PPTX, or PDF file."] | |
| # # gr.Info("Preparing documents for quiz generation...") | |
| # # documents = [text_from_file] | |
| # # formatted_prompt = system_instructions(question_difficulty, topic, '\n'.join(documents)) | |
| # # try: | |
| # # gr.Info("Sending request to Qwen API for quiz generation...") | |
| # # response = client.predict(query=formatted_prompt, history=[], system="You are a helpful assistant.", api_name="/model_chat") | |
| # # response1 = response[1][0][1] | |
| # # gr.Info("Processing response from Qwen API...") | |
| # # start_index = response1.find('{') | |
| # # end_index = response1.rfind('}') | |
| # # cleaned_response = response1[start_index:end_index + 1] if start_index != -1 and end_index != -1 else '' | |
| # # output_json = json.loads(cleaned_response) | |
| # # gr.Info("JSON response successfully processed.") | |
| # # excel_file = json_to_excel(output_json) | |
| # # question_radio_list = [] | |
| # # for question_num in range(1, 11): | |
| # # question_key = f"Q{question_num}" | |
| # # question = output_json.get(question_key) | |
| # # choice_keys = [f"{question_key}:C{i}" for i in range(1, 5)] | |
| # # choice_list = [output_json.get(choice_key, "Choice not found") for choice_key in choice_keys] | |
| # # radio = gr.Radio(choices=choice_list, label=question, visible=True, interactive=True) | |
| # # question_radio_list.append(radio) | |
| # # gr.Info("Quiz generation completed successfully.") | |
| # # return ['Quiz Generated!'] + question_radio_list + [excel_file] | |
| # # except json.JSONDecodeError as e: | |
| # # gr.Info("Error in processing JSON response.") | |
| # # return [f"Error: Failed to decode JSON response. {e}"] | |
| # # check_button = gr.Button("Check Score") | |
| # # score_textbox = gr.Markdown() | |
| # # @check_button.click(inputs=question_radios, outputs=score_textbox) | |
| # # def compare_answers(*user_answers): | |
| # # user_answer_list = list(user_answers) | |
| # # answers_list = [] | |
| # # gr.Info("Comparing user answers with correct answers...") | |
| # # for question_num in range(1, 11): | |
| # # answer_key = f"A{question_num}" | |
| # # answer = quiz_data.get(quiz_data.get(answer_key)) | |
| # # if not answer: | |
| # # break | |
| # # answers_list.append(answer) | |
| # # score = sum(1 for item in user_answer_list if item in answers_list) | |
| # # if score > 7: | |
| # # message = f"### Excellent! You got {score} out of 10!" | |
| # # elif score > 5: | |
| # # message = f"### Good! You got {score} out of 10!" | |
| # # else: | |
| # # message = f"### You got {score} out of 10! Don't worry. You can prepare well and try better next time!" | |
| # # gr.Info("Score calculation completed.") | |
| # # return message | |
| # # QUIZBOT.queue() | |
| # # QUIZBOT.launch(debug=True) | |