AWS-Exam-Simulator / tool2.py
ruslanmv's picture
Update tool2.py
55d73fa verified
raw
history blame
4.75 kB
# tool.py
import json
import os
from gradio_client import Client
import httpx
import time # Import the time module
# Load question sets from JSON files
def load_question_sets(directory='question_sets'):
question_sets = {}
for filename in os.listdir(directory):
if filename.endswith('.json'):
exam_name = filename[:-5] # Remove '.json' extension
filepath = os.path.join(directory, filename)
with open(filepath, 'r') as f:
try:
question_sets[exam_name] = json.load(f)
except json.JSONDecodeError as e:
print(f"Error decoding JSON in {filename}: {e}")
continue # Skip to the next file if there's a JSON decode error
return question_sets
question_sets_data = load_question_sets()
exams = list(question_sets_data.keys())
print(f"question_sets: {exams}")
# Initialize Gradio clients for text-to-speech
client_fast = Client("https://ruslanmv-text-to-speech-fast.hf.space/")
client_2 = None # Initialize to None, will be created with retry
# Retry logic for client_2 initialization
max_retries = 3
retry_delay = 5 # seconds
for attempt in range(max_retries):
try:
client_2 = Client("ruslanmv/Text-To-Speech")
print("Loaded as API: https://ruslanmv-text-to-speech.hf.space βœ”")
break # If successful, break out of the retry loop
except httpx.ReadTimeout as e:
print(f"Attempt {attempt + 1} failed with ReadTimeout: {e}")
if attempt < max_retries - 1:
print(f"Retrying in {retry_delay} seconds...")
time.sleep(retry_delay)
else:
print("Max retries reached. Text-to-speech (client_2) may not be available.")
client_2 = None # Ensure client_2 is None if all retries fail
except Exception as e: # Catch other potential exceptions during client initialization
print(f"An unexpected error occurred during client_2 initialization: {e}")
client_2 = None # Ensure client_2 is None if initialization fails
break # No point retrying if it's not a timeout issue, break out of the loop
if client_2 is None:
print("Text-to-speech (client_2) NOT loaded due to errors.")
else:
print("Loaded as API: https://ruslanmv-text-to-speech-fast.hf.space βœ”")
def select_exam_vce(exam_choice):
"""Selects and returns the question set for the chosen exam."""
return question_sets_data.get(exam_choice, [])
def text_to_speech(text):
"""Converts text to speech using Gradio client, with fallback to client_fast if client_2 is not available."""
global client_2, client_fast
if client_2:
try:
output = client_2.predict(text, api_name="/text_to_speech")
return output
except Exception as e:
print(f"Error using client_2, falling back to client_fast: {e}")
client_2 = None # Invalidate client_2 for future attempts if it consistently fails
# Fallback to client_fast will happen in the next block
if client_fast: # Fallback to client_fast if client_2 is None or failed
try:
output = client_fast.predict(text, api_name="/text_to_speech")
return output
except Exception as e:
print(f"Error using client_fast: {e}")
return None # Both clients failed
return None # No clients available
def display_question(index, audio_enabled, selected_questions): # Added selected_questions as argument
"""Displays a question with options and generates audio (if enabled)."""
if index < 0 or index >= len(selected_questions):
return "No more questions.", [], None
question_text_ = selected_questions[index].get('question', 'No question text available.')
question_text = f"**Question {index + 1}:** {question_text_}" # Question number starts from 1
choices_options = selected_questions[index].get('options', [])
audio_path = text_to_speech(question_text_ + " " + " ".join(choices_options)) if audio_enabled else None
return question_text, choices_options, audio_path
def get_explanation_and_answer(index, selected_questions): # Added selected_questions as argument
"""Retrieves explanation and correct answer for a question."""
explanation = selected_questions[index].get('explanation', 'No explanation available for this question.')
correct_answer = selected_questions[index].get('correct', 'No correct answer provided.')
return explanation, correct_answer
# backend1.py - No changes needed as per problem description, but ensure it's in the same directory and defines 'exams'
exams = list(question_sets_data.keys()) # backend1.py (simplified and corrected to use loaded exams)