Spaces:
Runtime error
Runtime error
Update tool2.py
Browse files
tool2.py
CHANGED
@@ -1,79 +1,103 @@
|
|
1 |
# tool.py
|
2 |
-
from gradio_client import Client
|
3 |
-
import os
|
4 |
import json
|
5 |
-
import
|
|
|
6 |
import httpx
|
|
|
7 |
|
8 |
-
#
|
9 |
-
def
|
10 |
-
question_sets =
|
11 |
-
for
|
12 |
-
|
13 |
-
|
14 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
15 |
return question_sets
|
16 |
|
17 |
-
|
18 |
-
|
|
|
19 |
|
20 |
-
|
21 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
22 |
try:
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
30 |
|
31 |
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
|
|
|
|
|
|
|
|
|
|
43 |
try:
|
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 |
-
except httpx.ReadTimeout: # Catch specific ReadTimeout during prediction as well
|
69 |
-
print(f"ReadTimeout during prediction with client {client_index}. Rotating client and retrying.")
|
70 |
-
client_index = (client_index + 1) % len(clients)
|
71 |
-
time.sleep(delay) # Add a delay before retrying with next client to give server some breathing room
|
72 |
-
except Exception as e: # Catch other potential exceptions during prediction
|
73 |
-
print(f"Exception during prediction: {e}. Rotating client and retrying.")
|
74 |
-
client_index = (client_index + 1) % len(clients)
|
75 |
-
time.sleep(delay)
|
76 |
|
77 |
|
78 |
-
|
79 |
-
|
|
|
1 |
# tool.py
|
|
|
|
|
2 |
import json
|
3 |
+
import os
|
4 |
+
from gradio_client import Client
|
5 |
import httpx
|
6 |
+
import time # Import the time module
|
7 |
|
8 |
+
# Load question sets from JSON files
|
9 |
+
def load_question_sets(directory='question_sets'):
|
10 |
+
question_sets = {}
|
11 |
+
for filename in os.listdir(directory):
|
12 |
+
if filename.endswith('.json'):
|
13 |
+
exam_name = filename[:-5] # Remove '.json' extension
|
14 |
+
filepath = os.path.join(directory, filename)
|
15 |
+
with open(filepath, 'r') as f:
|
16 |
+
try:
|
17 |
+
question_sets[exam_name] = json.load(f)
|
18 |
+
except json.JSONDecodeError as e:
|
19 |
+
print(f"Error decoding JSON in {filename}: {e}")
|
20 |
+
continue # Skip to the next file if there's a JSON decode error
|
21 |
return question_sets
|
22 |
|
23 |
+
question_sets_data = load_question_sets()
|
24 |
+
exams = list(question_sets_data.keys())
|
25 |
+
print(f"question_sets: {exams}")
|
26 |
|
27 |
+
# Initialize Gradio clients for text-to-speech
|
28 |
+
client_fast = Client("https://ruslanmv-text-to-speech-fast.hf.space/")
|
29 |
+
client_2 = None # Initialize to None, will be created with retry
|
30 |
+
|
31 |
+
# Retry logic for client_2 initialization
|
32 |
+
max_retries = 3
|
33 |
+
retry_delay = 5 # seconds
|
34 |
+
|
35 |
+
for attempt in range(max_retries):
|
36 |
try:
|
37 |
+
client_2 = Client("ruslanmv/Text-To-Speech")
|
38 |
+
print("Loaded as API: https://ruslanmv-text-to-speech.hf.space ✔")
|
39 |
+
break # If successful, break out of the retry loop
|
40 |
+
except httpx.ReadTimeout as e:
|
41 |
+
print(f"Attempt {attempt + 1} failed with ReadTimeout: {e}")
|
42 |
+
if attempt < max_retries - 1:
|
43 |
+
print(f"Retrying in {retry_delay} seconds...")
|
44 |
+
time.sleep(retry_delay)
|
45 |
+
else:
|
46 |
+
print("Max retries reached. Text-to-speech (client_2) may not be available.")
|
47 |
+
client_2 = None # Ensure client_2 is None if all retries fail
|
48 |
+
except Exception as e: # Catch other potential exceptions during client initialization
|
49 |
+
print(f"An unexpected error occurred during client_2 initialization: {e}")
|
50 |
+
client_2 = None # Ensure client_2 is None if initialization fails
|
51 |
+
break # No point retrying if it's not a timeout issue, break out of the loop
|
52 |
+
|
53 |
+
if client_2 is None:
|
54 |
+
print("Text-to-speech (client_2) NOT loaded due to errors.")
|
55 |
+
else:
|
56 |
+
print("Loaded as API: https://ruslanmv-text-to-speech-fast.hf.space ✔")
|
57 |
|
58 |
|
59 |
+
def select_exam_vce(exam_choice):
|
60 |
+
"""Selects and returns the question set for the chosen exam."""
|
61 |
+
return question_sets_data.get(exam_choice, [])
|
62 |
+
|
63 |
+
def text_to_speech(text):
|
64 |
+
"""Converts text to speech using Gradio client, with fallback to client_fast if client_2 is not available."""
|
65 |
+
global client_2, client_fast
|
66 |
+
if client_2:
|
67 |
+
try:
|
68 |
+
output = client_2.predict(text, api_name="/text_to_speech")
|
69 |
+
return output
|
70 |
+
except Exception as e:
|
71 |
+
print(f"Error using client_2, falling back to client_fast: {e}")
|
72 |
+
client_2 = None # Invalidate client_2 for future attempts if it consistently fails
|
73 |
+
# Fallback to client_fast will happen in the next block
|
74 |
+
if client_fast: # Fallback to client_fast if client_2 is None or failed
|
75 |
try:
|
76 |
+
output = client_fast.predict(text, api_name="/text_to_speech")
|
77 |
+
return output
|
78 |
+
except Exception as e:
|
79 |
+
print(f"Error using client_fast: {e}")
|
80 |
+
return None # Both clients failed
|
81 |
+
return None # No clients available
|
82 |
+
|
83 |
+
|
84 |
+
def display_question(index, audio_enabled, selected_questions): # Added selected_questions as argument
|
85 |
+
"""Displays a question with options and generates audio (if enabled)."""
|
86 |
+
if index < 0 or index >= len(selected_questions):
|
87 |
+
return "No more questions.", [], None
|
88 |
+
question_text_ = selected_questions[index].get('question', 'No question text available.')
|
89 |
+
question_text = f"**Question {index + 1}:** {question_text_}" # Question number starts from 1
|
90 |
+
choices_options = selected_questions[index].get('options', [])
|
91 |
+
audio_path = text_to_speech(question_text_ + " " + " ".join(choices_options)) if audio_enabled else None
|
92 |
+
return question_text, choices_options, audio_path
|
93 |
+
|
94 |
+
def get_explanation_and_answer(index, selected_questions): # Added selected_questions as argument
|
95 |
+
"""Retrieves explanation and correct answer for a question."""
|
96 |
+
explanation = selected_questions[index].get('explanation', 'No explanation available for this question.')
|
97 |
+
correct_answer = selected_questions[index].get('correct', 'No correct answer provided.')
|
98 |
+
return explanation, correct_answer
|
99 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
100 |
|
101 |
|
102 |
+
# backend1.py - No changes needed as per problem description, but ensure it's in the same directory and defines 'exams'
|
103 |
+
exams = list(question_sets_data.keys()) # backend1.py (simplified and corrected to use loaded exams)
|