Sahana31 commited on
Commit
8c4fcb0
·
1 Parent(s): 4a45785

added security feature

Browse files
Files changed (1) hide show
  1. app.py +112 -56
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(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
 
 
 
 
 
 
 
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
- # Find the corresponding use case by ID
18
- usecase = next((uc for uc in usecases["usecases"] if uc["id"] == usecase_id), None)
19
- if not usecase:
20
- return f"Error: Use case with ID {usecase_id} not found."
21
 
22
- voice_description = usecase["voice_description"]
23
- logger.info(f"Voice Description: {voice_description}")
24
- logger.info(f"Input Text: {input_text}")
 
 
 
 
 
25
 
26
- # Define the API endpoint and headers
27
- url = "https://slabstech-dhwani-internal-api-server.hf.space/v1/audio/speech"
28
  headers = {
29
- "X-API-Key": "your-new-secret-api-key",
30
- "Content-Type": "application/json"
31
  }
32
 
33
- # Define the request payload
34
- payload = {
35
  "input": input_text,
36
- "voice": voice_description,
37
  "model": "ai4bharat/indic-parler-tts",
38
  "response_format": "mp3",
39
- "speed": 1.0
40
  }
41
 
42
- # Send the POST request
43
- response = requests.post(url, json=payload, headers=headers, stream=True)
44
 
45
- # Check if the request was successful
46
- if response.status_code == 200:
47
- logger.info(f"API request successful. Status code: {response.status_code}")
48
-
49
- # Save the audio file
50
- audio_file_path = usecase["output_filename"]
 
 
 
 
 
 
 
 
 
51
  with open(audio_file_path, "wb") as audio_file:
52
- for chunk in response.iter_content(chunk_size=1024):
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
- else:
61
- logger.error(f"API request failed. Status code: {response.status_code}, {response.text}")
62
- return f"Error: {response.status_code}, {response.text}"
63
- except requests.exceptions.RequestException as e:
64
- logger.error(f"Request exception: {e}")
65
- return f"Request error: {e}"
66
  except Exception as e:
67
- logger.error(f"General exception: {e}")
68
- return f"Error: {e}"
69
 
70
- # Define Gradio interface inputs and outputs
71
- demo = gr.Interface(
72
- fn=get_audio,
73
- inputs=[
74
- gr.Textbox(label="Enter Text", placeholder="Type your text here..."),
75
- gr.Dropdown(
76
- label="Select Use Case",
77
- choices=[f"{uc['id']}: {uc['voice_description']}" for uc in usecases["usecases"]],
78
- type="index"
79
- )
80
- ],
81
- outputs=gr.Audio(label="Generated Audio"),
82
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83
 
84
- # Launch the Gradio demo
85
- try:
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)