File size: 4,746 Bytes
46432cf
 
55d73fa
 
46432cf
55d73fa
46432cf
55d73fa
 
 
 
 
 
 
 
 
 
 
 
 
46432cf
 
55d73fa
 
 
46432cf
55d73fa
 
 
 
 
 
 
 
 
46432cf
55d73fa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46432cf
 
55d73fa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46432cf
55d73fa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46432cf
 
55d73fa
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
# 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)