ruslanmv commited on
Commit
57931a2
·
verified ·
1 Parent(s): 42397ec

Update tool2.py

Browse files
Files changed (1) hide show
  1. tool2.py +58 -93
tool2.py CHANGED
@@ -1,103 +1,68 @@
1
- # tool2.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='questions'):
10
- question_sets = {}
11
- # Check if the directory exists before trying to list files
12
- if not os.path.exists(directory):
13
- print(f"Error: Directory '{directory}' not found.")
14
- return {} # Return empty dictionary if directory is missing
15
 
16
- for filename in os.listdir(directory):
17
- if filename.endswith('.json'):
18
- exam_name = filename[:-5] # Remove '.json' extension
19
- filepath = os.path.join(directory, filename)
20
- with open(filepath, 'r') as f:
21
- try:
22
- question_sets[exam_name] = json.load(f)
23
- except json.JSONDecodeError as e:
24
- print(f"Error decoding JSON in {filename}: {e}")
25
- continue # Skip to the next file if there's a JSON decode error
26
  return question_sets
27
 
28
- question_sets_data = load_question_sets()
29
- exams = list(question_sets_data.keys())
30
- print(f"question_sets: {exams}")
31
-
32
- # Initialize Gradio clients for text-to-speech
33
- client_fast = Client("https://ruslanmv-text-to-speech-fast.hf.space/")
34
- client_2 = None # Initialize to None, will be created with retry
35
 
36
- # Retry logic for client_2 initialization
37
- max_retries = 3
38
- retry_delay = 5 # seconds
39
-
40
- for attempt in range(max_retries):
41
  try:
42
- client_2 = Client("ruslanmv/Text-To-Speech")
43
- print("Loaded as API: https://ruslanmv-text-to-speech.hf.space ✔")
44
- break # If successful, break out of the retry loop
45
- except httpx.ReadTimeout as e:
46
- print(f"Attempt {attempt + 1} failed with ReadTimeout: {e}")
47
- if attempt < max_retries - 1:
48
- print(f"Retrying in {retry_delay} seconds...")
49
- time.sleep(retry_delay)
50
- else:
51
- print("Max retries reached. Text-to-speech (client_2) may not be available.")
52
- client_2 = None # Ensure client_2 is None if all retries fail
53
- except Exception as e: # Catch other potential exceptions during client initialization
54
- print(f"An unexpected error occurred during client_2 initialization: {e}")
55
- client_2 = None # Ensure client_2 is None if initialization fails
56
- break # No point retrying if it's not a timeout issue, break out of the loop
57
-
58
- if client_2 is None:
59
- print("Text-to-speech (client_2) NOT loaded due to errors.")
60
- else:
61
- print("Loaded as API: https://ruslanmv-text-to-speech-fast.hf.space ✔")
62
 
63
 
64
- def select_exam_vce(exam_choice):
65
- """Selects and returns the question set for the chosen exam."""
66
- return question_sets_data.get(exam_choice, [])
67
-
68
- def text_to_speech(text):
69
- """Converts text to speech using Gradio client, with fallback to client_fast if client_2 is not available."""
70
- global client_2, client_fast
71
- if client_2:
72
- try:
73
- output = client_2.predict(text, api_name="/text_to_speech")
74
- return output
75
- except Exception as e:
76
- print(f"Error using client_2, falling back to client_fast: {e}")
77
- client_2 = None # Invalidate client_2 for future attempts if it consistently fails
78
- # Fallback to client_fast will happen in the next block
79
- if client_fast: # Fallback to client_fast if client_2 is None or failed
80
  try:
81
- output = client_fast.predict(text, api_name="/text_to_speech")
82
- return output
83
- except Exception as e:
84
- print(f"Error using client_fast: {e}")
85
- return None # Both clients failed
86
- return None # No clients available
87
-
88
-
89
- def display_question(index, audio_enabled, selected_questions): # Added selected_questions as argument
90
- """Displays a question with options and generates audio (if enabled)."""
91
- if index < 0 or index >= len(selected_questions):
92
- return "No more questions.", [], None
93
- question_text_ = selected_questions[index].get('question', 'No question text available.')
94
- question_text = f"**Question {index + 1}:** {question_text_}" # Question number starts from 1
95
- choices_options = selected_questions[index].get('options', [])
96
- audio_path = text_to_speech(question_text_ + " " + " ".join(choices_options)) if audio_enabled else None
97
- return question_text, choices_options, audio_path
 
 
 
 
 
 
 
98
 
99
- def get_explanation_and_answer(index, selected_questions): # Added selected_questions as argument
100
- """Retrieves explanation and correct answer for a question."""
101
- explanation = selected_questions[index].get('explanation', 'No explanation available for this question.')
102
- correct_answer = selected_questions[index].get('correct', 'No correct answer provided.')
103
- return explanation, correct_answer
 
 
 
 
1
  from gradio_client import Client
2
+ import os
3
+ import json
 
 
 
 
 
 
 
 
4
 
5
+ # Function to load question sets from a directory
6
+ def load_question_sets_vce(directory='questions'):
7
+ question_sets = []
8
+ for root, dirs, files in os.walk(directory):
9
+ for file in files:
10
+ if file.endswith(".json"):
11
+ question_sets.append(os.path.join( file)[:-5]) # remove the .json extension
 
 
 
12
  return question_sets
13
 
14
+ exams = load_question_sets_vce('questions/')
15
+ print("question_sets:", exams)
 
 
 
 
 
16
 
17
+ def select_exam_vce(exam_name):
18
+ file_path = os.path.join(os.getcwd(), 'questions', f'{exam_name}.json')
 
 
 
19
  try:
20
+ with open(file_path, 'r') as f:
21
+ questions = json.load(f)
22
+ print(f"Loaded {len(questions)} questions")
23
+ return questions # Ensure the questions are returned here
24
+ except FileNotFoundError:
25
+ print(f"File {file_path} not found.")
26
+ return [] # Return an empty list to indicate no questions were found
 
 
 
 
 
 
 
 
 
 
 
 
 
27
 
28
 
29
+ # Text-to-speech function with rate limiting, retry mechanism, and client rotation
30
+ import time
31
+ import httpx
32
+ # Text-to-speech clients
33
+ client_1 = Client("ruslanmv/text-to-speech-fast")
34
+ client_2 = Client("ruslanmv/Text-To-Speech")
35
+ client_3 = Client("ruslanmv/Text-to-Voice-Transformers")
36
+ clients = [client_1, client_2, client_3]
37
+ # Text-to-speech function with rate limiting, retry mechanism, and client rotation
38
+ def text_to_speech(text, retries=3, delay=5):
39
+ client_index = 0 # Start with the first client
40
+ for attempt in range(retries):
 
 
 
 
41
  try:
42
+ client = clients[client_index]
43
+ print(f"Attempt {attempt + 1}")
44
+ if client_index == 0:
45
+ result = client.predict(
46
+ language="English",
47
+ repo_id="csukuangfj/vits-piper-en_US-hfc_female-medium|1 speaker",
48
+ text=text,
49
+ sid="0",
50
+ speed=0.8,
51
+ api_name="/process"
52
+ )
53
+ else:
54
+ result = client.predict(
55
+ text=text,
56
+ api_name="/predict"
57
+ )
58
+ return result
59
+ except httpx.HTTPStatusError as e:
60
+ if e.response.status_code == 429:
61
+ print(f"Rate limit exceeded. Retrying in {delay} seconds...")
62
+ client_index = (client_index + 1) % len(clients) # Rotate to the next client
63
+ time.sleep(delay)
64
+ else:
65
+ raise e
66
 
67
+ print("Max retries exceeded. Could not process the request.")
68
+ return None