ruslanmv commited on
Commit
6e912a0
·
1 Parent(s): e0bd0f2

Create backend1.py

Browse files
Files changed (1) hide show
  1. backend1.py +130 -0
backend1.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from gradio_client import Client
3
+ import os
4
+ import json
5
+
6
+ # Function to load question sets from a directory
7
+ def load_question_sets_vce(directory='questions'):
8
+ question_sets = []
9
+ for root, dirs, files in os.walk(directory):
10
+ for file in files:
11
+ if file.endswith(".json"):
12
+ question_sets.append(os.path.join( file)[:-5]) # remove the .json extension
13
+ return question_sets
14
+
15
+ exams = load_question_sets_vce('questions/')
16
+ print("question_sets:", exams)
17
+
18
+ def select_exam_vce(exam_name):
19
+ file_path = os.path.join(os.getcwd(), 'questions', f'{exam_name}.json')
20
+ try:
21
+ with open(file_path, 'r') as f:
22
+ questions = json.load(f)
23
+ print(f"Loaded {len(questions)} questions")
24
+ return questions # Ensure the questions are returned here
25
+ except FileNotFoundError:
26
+ print(f"File {file_path} not found.")
27
+ return [] # Return an empty list to indicate no questions were found
28
+
29
+
30
+ # Text-to-speech function with rate limiting, retry mechanism, and client rotation
31
+ import time
32
+ import httpx
33
+ # Text-to-speech clients
34
+ client_1 = Client("ruslanmv/text-to-speech-fast")
35
+ client_2 = Client("ruslanmv/Text-To-Speech")
36
+ client_3 = Client("ruslanmv/Text-to-Voice-Transformers")
37
+ clients = [client_1, client_2, client_3]
38
+ # Text-to-speech function with rate limiting, retry mechanism, and client rotation
39
+ def text_to_speech(text, retries=3, delay=5):
40
+ client_index = 0 # Start with the first client
41
+ for attempt in range(retries):
42
+ try:
43
+ client = clients[client_index]
44
+ print(f"Attempt {attempt + 1}")
45
+ if client_index == 0:
46
+ result = client.predict(
47
+ language="English",
48
+ repo_id="csukuangfj/vits-piper-en_US-hfc_female-medium|1 speaker",
49
+ text=text,
50
+ sid="0",
51
+ speed=0.8,
52
+ api_name="/process"
53
+ )
54
+ else:
55
+ result = client.predict(
56
+ text=text,
57
+ api_name="/predict"
58
+ )
59
+ return result
60
+ except httpx.HTTPStatusError as e:
61
+ if e.response.status_code == 429:
62
+ print(f"Rate limit exceeded. Retrying in {delay} seconds...")
63
+ client_index = (client_index + 1) % len(clients) # Rotate to the next client
64
+ time.sleep(delay)
65
+ else:
66
+ raise e
67
+
68
+ print("Max retries exceeded. Could not process the request.")
69
+ return None
70
+ # Function to start exam
71
+ def start_exam(exam_choice, audio_enabled):
72
+ global selected_questions
73
+ selected_questions = select_exam_vce(exam_choice)
74
+ question, options, audio_path = display_question(0, audio_enabled)
75
+ return (
76
+ gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False),
77
+ gr.update(visible=False), # Hide the audio_checkbox
78
+ gr.update(visible=True), question, gr.update(choices=options, visible=True), gr.update(visible=True),
79
+ gr.update(visible=True), gr.update(visible=True), gr.update(visible=True), 0, "", audio_path
80
+ )
81
+
82
+ # Function to display a question
83
+ def display_question(index, audio_enabled):
84
+ if index < 0 or index >= len(selected_questions):
85
+ return "No more questions.", [], None
86
+ question_text_ = selected_questions[index]['question']
87
+ question_text = f"**Question {index + 1}:** {question_text_}" # Numbering added
88
+ choices_options = selected_questions[index]['options']
89
+ audio_path = text_to_speech(question_text_ + " " + " ".join(choices_options)) if audio_enabled else None
90
+ return question_text, choices_options, audio_path
91
+
92
+ # Function to check the answer
93
+ def check_answer(index, answer):
94
+ correct_answer = selected_questions[index]['correct']
95
+ if answer == correct_answer:
96
+ return f"Correct! The answer is: {correct_answer}"
97
+ else:
98
+ return f"Incorrect. The correct answer is: {correct_answer}"
99
+
100
+ # Function to update the question
101
+ def update_question(index, audio_enabled):
102
+ question, options, audio_path = display_question(index, audio_enabled)
103
+ return question, gr.update(choices=options), index, audio_path
104
+
105
+ # Function to handle the answer submission
106
+ def handle_answer(index, answer, audio_enabled):
107
+ result = check_answer(index, answer)
108
+ audio_path = text_to_speech(result) if audio_enabled else None
109
+ return result, audio_path
110
+
111
+ # Function to handle the next question
112
+ def handle_next(index, audio_enabled):
113
+ new_index = min(index + 1, len(selected_questions) - 1)
114
+ question, options, new_index, audio_path = update_question(new_index, audio_enabled)
115
+ return question, options, new_index, "", audio_path
116
+
117
+ # Function to handle the previous question
118
+ def handle_previous(index, audio_enabled):
119
+ new_index = max(index - 1, 0)
120
+ question, options, new_index, audio_path = update_question(new_index, audio_enabled)
121
+ return question, options, new_index, "", audio_path
122
+
123
+ # Function to return to the home page
124
+ def return_home():
125
+ return (
126
+ gr.update(visible=True), gr.update(visible=True), gr.update(visible=True), gr.update(visible=True),
127
+ gr.update(visible=True), # Show the audio_checkbox
128
+ gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False),
129
+ gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), "", ""
130
+ )