ruslanmv commited on
Commit
55d73fa
·
verified ·
1 Parent(s): 7bd29a3

Update tool2.py

Browse files
Files changed (1) hide show
  1. tool2.py +90 -66
tool2.py CHANGED
@@ -1,79 +1,103 @@
1
  # tool.py
2
- from gradio_client import Client
3
- import os
4
  import json
5
- import time
 
6
  import httpx
 
7
 
8
- # Function to load question sets from a directory
9
- def load_question_sets_vce(directory='questions'):
10
- question_sets = []
11
- for root, dirs, files in os.walk(directory):
12
- for file in files:
13
- if file.endswith(".json"):
14
- question_sets.append(os.path.join( file)[:-5]) # remove the .json extension
 
 
 
 
 
 
15
  return question_sets
16
 
17
- exams = load_question_sets_vce('questions/')
18
- print("question_sets:", exams)
 
19
 
20
- def select_exam_vce(exam_name):
21
- file_path = os.path.join(os.getcwd(), 'questions', f'{exam_name}.json')
 
 
 
 
 
 
 
22
  try:
23
- with open(file_path, 'r') as f:
24
- questions = json.load(f)
25
- print(f"Loaded {len(questions)} questions")
26
- return questions # Ensure the questions are returned here
27
- except FileNotFoundError:
28
- print(f"File {file_path} not found.")
29
- return [] # Return an empty list to indicate no questions were found
 
 
 
 
 
 
 
 
 
 
 
 
 
30
 
31
 
32
- # Text-to-speech function with rate limiting, retry mechanism, and client rotation
33
- # Text-to-speech clients
34
- client_1 = Client("ruslanmv/text-to-speech-fast")
35
- # Increase timeout for client_2 initialization
36
- client_2 = Client("ruslanmv/Text-To-Speech", client_kwargs={'timeout': httpx.Timeout(30.0)}) # Increased timeout to 30 seconds
37
- client_3 = Client("ruslanmv/Text-to-Voice-Transformers")
38
- clients = [client_1, client_2, client_3]
39
- # Text-to-speech function with rate limiting, retry mechanism, and client rotation
40
- def text_to_speech(text, retries=3, delay=5):
41
- client_index = 0 # Start with the first client
42
- for attempt in range(retries):
 
 
 
 
 
43
  try:
44
- client = clients[client_index]
45
- print(f"Attempt {attempt + 1} with client index {client_index}")
46
- if client_index == 0:
47
- result = client.predict(
48
- language="English",
49
- repo_id="csukuangfj/vits-piper-en_US-hfc_female-medium|1 speaker",
50
- text=text,
51
- sid="0",
52
- speed=0.8,
53
- api_name="/process"
54
- )
55
- else:
56
- result = client.predict(
57
- text=text,
58
- api_name="/predict"
59
- )
60
- return result
61
- except httpx.HTTPStatusError as e:
62
- if e.response.status_code == 429:
63
- print(f"Rate limit exceeded. Retrying in {delay} seconds...")
64
- client_index = (client_index + 1) % len(clients) # Rotate to the next client
65
- time.sleep(delay)
66
- else:
67
- raise e
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
- print("Max retries exceeded. Could not process the request.")
79
- return None
 
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)