Spaces:
Running
Running
added security feature
Browse files
app.py
CHANGED
@@ -2,87 +2,143 @@ import gradio as gr
|
|
2 |
import requests
|
3 |
import logging
|
4 |
import json
|
|
|
5 |
|
6 |
# Configure logging
|
7 |
-
logging.basicConfig(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
8 |
logger = logging.getLogger(__name__)
|
9 |
|
10 |
# Load the JSON file containing use cases
|
11 |
with open("voice_description_indian.json", "r") as file:
|
12 |
usecases = json.load(file)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
13 |
|
14 |
# Function to send text input to the API and retrieve the audio file
|
15 |
-
def get_audio(input_text, usecase_id):
|
16 |
try:
|
17 |
-
|
18 |
-
|
19 |
-
if not usecase:
|
20 |
-
return f"Error: Use case with ID {usecase_id} not found."
|
21 |
|
22 |
-
|
23 |
-
logger.
|
24 |
-
|
|
|
|
|
|
|
|
|
|
|
25 |
|
26 |
-
#
|
27 |
-
|
28 |
headers = {
|
29 |
-
"
|
30 |
-
"
|
31 |
}
|
32 |
|
33 |
-
#
|
34 |
-
|
35 |
"input": input_text,
|
36 |
-
"voice": voice_description,
|
37 |
"model": "ai4bharat/indic-parler-tts",
|
38 |
"response_format": "mp3",
|
39 |
-
"speed": 1
|
40 |
}
|
41 |
|
42 |
-
|
43 |
-
response = requests.post(url, json=payload, headers=headers, stream=True)
|
44 |
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
51 |
with open(audio_file_path, "wb") as audio_file:
|
52 |
-
for chunk in
|
53 |
if chunk:
|
54 |
audio_file.write(chunk)
|
55 |
-
|
56 |
-
logger.info(f"Audio file saved to: {audio_file_path}")
|
57 |
-
|
58 |
-
# Return the path to the saved audio file
|
59 |
return audio_file_path
|
60 |
-
|
61 |
-
logger.error(f"
|
62 |
-
return f"Error: {
|
63 |
-
|
64 |
-
logger.error(f"Request exception: {e}")
|
65 |
-
return f"Request error: {e}"
|
66 |
except Exception as e:
|
67 |
-
logger.error(f"
|
68 |
-
return f"
|
69 |
|
70 |
-
#
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
gr.Textbox(label="
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
83 |
|
84 |
-
|
85 |
-
|
86 |
-
demo.launch()
|
87 |
-
except Exception as e:
|
88 |
-
logger.error(f"Failed to launch Gradio demo: {e}")
|
|
|
2 |
import requests
|
3 |
import logging
|
4 |
import json
|
5 |
+
import traceback
|
6 |
|
7 |
# Configure logging
|
8 |
+
logging.basicConfig(
|
9 |
+
level=logging.DEBUG,
|
10 |
+
format='%(asctime)s - %(levelname)s - %(message)s',
|
11 |
+
handlers=[
|
12 |
+
logging.FileHandler("app_debug.log"),
|
13 |
+
logging.StreamHandler()
|
14 |
+
]
|
15 |
+
)
|
16 |
logger = logging.getLogger(__name__)
|
17 |
|
18 |
# Load the JSON file containing use cases
|
19 |
with open("voice_description_indian.json", "r") as file:
|
20 |
usecases = json.load(file)
|
21 |
+
logger.debug(f"Loaded {len(usecases['usecases'])} use cases from JSON file")
|
22 |
+
|
23 |
+
# Function to obtain an access token
|
24 |
+
def get_access_token(username, password):
|
25 |
+
try:
|
26 |
+
url_token = "https://slabstech-dhwani-server.hf.space/v1/token"
|
27 |
+
payload = {"username": username, "password": password}
|
28 |
+
|
29 |
+
response_token = requests.post(url_token, json=payload)
|
30 |
+
response_token.raise_for_status()
|
31 |
+
token_data = response_token.json()
|
32 |
+
if 'token' in token_data:
|
33 |
+
token = token_data['token']
|
34 |
+
elif 'access_token' in token_data:
|
35 |
+
token = token_data['access_token']
|
36 |
+
else:
|
37 |
+
logger.error("Token not found in response. Full response: %s", response_token.text)
|
38 |
+
return None
|
39 |
+
|
40 |
+
logger.debug("Successfully acquired access token")
|
41 |
+
return token
|
42 |
+
|
43 |
+
except requests.exceptions.HTTPError as e:
|
44 |
+
logger.error(f"Token request HTTP error: {e.response.status_code} - {e.response.text}")
|
45 |
+
return None
|
46 |
|
47 |
# Function to send text input to the API and retrieve the audio file
|
48 |
+
def get_audio(input_text, usecase_id, token):
|
49 |
try:
|
50 |
+
logger.info(f"Starting audio generation request")
|
51 |
+
logger.debug(f"Inputs - Text: '{input_text}', UseCase ID: {usecase_id}")
|
|
|
|
|
52 |
|
53 |
+
# Use case validation
|
54 |
+
logger.debug(f"Looking up use case ID: {usecase_id}")
|
55 |
+
usecase = next((uc for uc in usecases["usecases"] if str(uc["id"]) == str(usecase_id)), None)
|
56 |
+
if not usecase:
|
57 |
+
logger.error(f"Use case {usecase_id} not found in available options")
|
58 |
+
return f"Error: Invalid use case ID {usecase_id}"
|
59 |
+
|
60 |
+
logger.debug(f"Found use case: {usecase['voice_description']}")
|
61 |
|
62 |
+
# API request
|
63 |
+
url_audio = "https://slabstech-dhwani-server.hf.space/v1/audio/speech"
|
64 |
headers = {
|
65 |
+
"accept": "application/json",
|
66 |
+
"Authorization": f"Bearer {token}"
|
67 |
}
|
68 |
|
69 |
+
# Construct URL with query parameters
|
70 |
+
query_params = {
|
71 |
"input": input_text,
|
72 |
+
"voice": usecase["voice_description"],
|
73 |
"model": "ai4bharat/indic-parler-tts",
|
74 |
"response_format": "mp3",
|
75 |
+
"speed": 1
|
76 |
}
|
77 |
|
78 |
+
url_audio_with_params = f"{url_audio}?input={input_text}&voice={usecase['voice_description']}&model=ai4bharat%2Findic-parler-tts&response_format=mp3&speed=1"
|
|
|
79 |
|
80 |
+
logger.debug(f"Sending request to {url_audio_with_params}")
|
81 |
+
|
82 |
+
response_audio = requests.post(url_audio_with_params, headers=headers, stream=True)
|
83 |
+
|
84 |
+
try:
|
85 |
+
response_audio.raise_for_status()
|
86 |
+
except requests.exceptions.HTTPError as e:
|
87 |
+
logger.error(f"Audio API HTTP error: {e.response.status_code} - {e.response.text}")
|
88 |
+
return f"API Error: {e.response.status_code} - {e.response.text}"
|
89 |
+
|
90 |
+
# File handling
|
91 |
+
audio_file_path = f"usecase_{usecase['id']}_output.mp3" # Short and meaningful filename
|
92 |
+
logger.debug(f"Saving audio to: {audio_file_path}")
|
93 |
+
|
94 |
+
try:
|
95 |
with open(audio_file_path, "wb") as audio_file:
|
96 |
+
for chunk in response_audio.iter_content(chunk_size=1024):
|
97 |
if chunk:
|
98 |
audio_file.write(chunk)
|
99 |
+
logger.info(f"Successfully saved audio file: {audio_file_path}")
|
|
|
|
|
|
|
100 |
return audio_file_path
|
101 |
+
except IOError as e:
|
102 |
+
logger.error(f"File save error: {str(e)}")
|
103 |
+
return f"Error saving file: {str(e)}"
|
104 |
+
|
|
|
|
|
105 |
except Exception as e:
|
106 |
+
logger.error(f"Unexpected error: {str(e)}\n{traceback.format_exc()}")
|
107 |
+
return f"Critical error: {str(e)}"
|
108 |
|
109 |
+
# Gradio interface
|
110 |
+
with gr.Blocks() as demo:
|
111 |
+
with gr.Row():
|
112 |
+
username_input = gr.Textbox(label="Username")
|
113 |
+
password_input = gr.Textbox(label="Password", type="password")
|
114 |
+
|
115 |
+
input_text = gr.Textbox(label="Input Text")
|
116 |
+
usecase_dropdown = gr.Dropdown(
|
117 |
+
label="Use Case",
|
118 |
+
choices=[f"{uc['id']}: {uc['voice_description']}" for uc in usecases["usecases"]],
|
119 |
+
)
|
120 |
+
|
121 |
+
generate_button = gr.Button("Generate Audio")
|
122 |
+
audio_output = gr.Audio(label="Output")
|
123 |
+
|
124 |
+
def process_request(input_text, usecase_entry, username, password):
|
125 |
+
logger.debug(f"Processing request - User: {username}, Selection: {usecase_entry}")
|
126 |
+
|
127 |
+
# Extract use case ID from the selected entry
|
128 |
+
usecase_id = usecase_entry.split(":")[0].strip()
|
129 |
+
|
130 |
+
# Obtain access token
|
131 |
+
token = get_access_token(username, password)
|
132 |
+
if not token:
|
133 |
+
return "Error: Unable to authenticate"
|
134 |
+
|
135 |
+
return get_audio(input_text, usecase_id, token)
|
136 |
+
|
137 |
+
generate_button.click(
|
138 |
+
fn=process_request,
|
139 |
+
inputs=[input_text, usecase_dropdown, username_input, password_input],
|
140 |
+
outputs=audio_output
|
141 |
+
)
|
142 |
|
143 |
+
if __name__ == "__main__":
|
144 |
+
demo.launch(share=True)
|
|
|
|
|
|