Spaces:
Running
Running
updated code with environment variables
Browse files
app.py
CHANGED
@@ -2,143 +2,95 @@ import gradio as gr
|
|
2 |
import requests
|
3 |
import logging
|
4 |
import json
|
5 |
-
import
|
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 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
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 |
-
|
48 |
-
def get_audio(input_text, usecase_id, token):
|
49 |
try:
|
50 |
-
|
51 |
-
|
|
|
52 |
|
53 |
-
#
|
54 |
-
|
55 |
-
usecase = next((uc for uc in usecases["usecases"] if str(uc["id"]) == str(usecase_id)), None)
|
56 |
if not usecase:
|
57 |
-
|
58 |
-
return f"Error: Invalid use case ID {usecase_id}"
|
59 |
-
|
60 |
-
logger.debug(f"Found use case: {usecase['voice_description']}")
|
61 |
|
62 |
-
|
63 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
64 |
headers = {
|
65 |
-
"
|
66 |
-
"
|
67 |
}
|
68 |
|
69 |
-
|
70 |
-
query_params = {
|
71 |
"input": input_text,
|
72 |
-
"voice":
|
73 |
"model": "ai4bharat/indic-parler-tts",
|
74 |
"response_format": "mp3",
|
75 |
-
"speed": 1
|
76 |
}
|
77 |
|
78 |
-
|
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 |
-
|
|
|
|
|
95 |
with open(audio_file_path, "wb") as audio_file:
|
96 |
-
|
97 |
-
|
98 |
-
audio_file.write(chunk)
|
99 |
-
logger.info(f"Successfully saved audio file: {audio_file_path}")
|
100 |
return audio_file_path
|
101 |
-
|
102 |
-
logger.error(f"
|
103 |
-
return
|
104 |
-
|
105 |
except Exception as e:
|
106 |
-
logger.error(f"
|
107 |
-
return
|
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 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
142 |
|
143 |
if __name__ == "__main__":
|
144 |
-
|
|
|
|
|
|
|
|
2 |
import requests
|
3 |
import logging
|
4 |
import json
|
5 |
+
import os
|
6 |
|
7 |
# Configure logging
|
8 |
+
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
9 |
logger = logging.getLogger(__name__)
|
10 |
|
11 |
# Load the JSON file containing use cases
|
12 |
with open("voice_description_indian.json", "r") as file:
|
13 |
usecases = json.load(file)
|
|
|
14 |
|
15 |
+
def get_api_token():
|
16 |
+
username = os.getenv('USERNAME')
|
17 |
+
password = os.getenv('PASSWORD')
|
18 |
+
if not username or not password:
|
19 |
+
raise ValueError("Environment variables USERNAME and PASSWORD must be set.")
|
20 |
+
url = 'https://slabstech-dhwani-server.hf.space/v1/token'
|
21 |
+
headers = {'accept': 'application/json', 'Content-Type': 'application/json'}
|
22 |
+
payload = {"username": username, "password": password}
|
23 |
+
response = requests.post(url, json=payload, headers=headers)
|
24 |
+
if response.status_code == 200:
|
25 |
+
return response.json().get('access_token')
|
26 |
+
else:
|
27 |
+
logger.error(f"Failed to get API token: {response.text}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
28 |
return None
|
29 |
|
30 |
+
def get_audio(input_text, usecase_id):
|
|
|
31 |
try:
|
32 |
+
api_token = get_api_token()
|
33 |
+
if not api_token:
|
34 |
+
return "Error: Failed to obtain API token."
|
35 |
|
36 |
+
# Retrieve the selected use case
|
37 |
+
usecase = next((uc for uc in usecases["usecases"] if uc["id"] == usecase_id), None)
|
|
|
38 |
if not usecase:
|
39 |
+
return f"Error: Use case with ID {usecase_id} not found."
|
|
|
|
|
|
|
40 |
|
41 |
+
voice_description = usecase.get("voice_description")
|
42 |
+
|
43 |
+
if not voice_description:
|
44 |
+
return "Error: Missing voice description in the use case JSON."
|
45 |
+
|
46 |
+
logger.info(f"Voice Description: {voice_description}")
|
47 |
+
logger.info(f"Input Text: {input_text}")
|
48 |
+
|
49 |
+
url = f"https://slabstech-dhwani-server.hf.space/v1/audio/speech"
|
50 |
headers = {
|
51 |
+
"Authorization": f"Bearer {api_token}",
|
52 |
+
"accept": "application/json"
|
53 |
}
|
54 |
|
55 |
+
params = {
|
|
|
56 |
"input": input_text,
|
57 |
+
"voice": voice_description,
|
58 |
"model": "ai4bharat/indic-parler-tts",
|
59 |
"response_format": "mp3",
|
60 |
+
"speed": 1.0
|
61 |
}
|
62 |
|
63 |
+
response = requests.post(url, headers=headers, params=params)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
64 |
|
65 |
+
if response.status_code == 200:
|
66 |
+
logger.info(f"API request successful. Status code: {response.status_code}")
|
67 |
+
audio_file_path = f"{usecase_id}_output.mp3"
|
68 |
with open(audio_file_path, "wb") as audio_file:
|
69 |
+
audio_file.write(response.content)
|
70 |
+
logger.info(f"Audio file saved to: {audio_file_path}")
|
|
|
|
|
71 |
return audio_file_path
|
72 |
+
else:
|
73 |
+
logger.error(f"API request failed. Status code: {response.status_code}, {response.text}")
|
74 |
+
return None
|
|
|
75 |
except Exception as e:
|
76 |
+
logger.error(f"Exception in get_audio: {e}")
|
77 |
+
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
78 |
|
79 |
+
demo = gr.Interface(
|
80 |
+
fn=get_audio,
|
81 |
+
inputs=[
|
82 |
+
gr.Textbox(label="Enter Text", placeholder="Type your text here..."),
|
83 |
+
gr.Dropdown(
|
84 |
+
label="Select Use Case",
|
85 |
+
choices=[f"{uc['id']}: {uc['voice_description']}" for uc in usecases["usecases"]],
|
86 |
+
type="index"
|
87 |
+
)
|
88 |
+
],
|
89 |
+
outputs=gr.Audio(label="Generated Audio"),
|
90 |
+
)
|
91 |
|
92 |
if __name__ == "__main__":
|
93 |
+
try:
|
94 |
+
demo.launch(show_error=True)
|
95 |
+
except Exception as e:
|
96 |
+
logger.error(f"Failed to launch Gradio demo: {e}")
|