vineet124jig commited on
Commit
e129c85
Β·
verified Β·
1 Parent(s): d75c38c

Upload 3 files

Browse files
Files changed (3) hide show
  1. README.md +4 -3
  2. app.py +199 -0
  3. requirements.txt +4 -0
README.md CHANGED
@@ -1,13 +1,14 @@
1
  ---
2
- title: Text To Speech Transcription
3
  emoji: πŸš€
4
- colorFrom: yellow
5
- colorTo: gray
6
  sdk: gradio
7
  sdk_version: 5.34.2
8
  app_file: app.py
9
  pinned: false
10
  license: mit
 
11
  ---
12
 
13
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
  ---
2
+ title: Convert Text to Speech with Ease
3
  emoji: πŸš€
4
+ colorFrom: purple
5
+ colorTo: purple
6
  sdk: gradio
7
  sdk_version: 5.34.2
8
  app_file: app.py
9
  pinned: false
10
  license: mit
11
+ short_description: 'Convert text to speech easily with jigsawstack '
12
  ---
13
 
14
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import requests
3
+ import json
4
+ import os
5
+ import time
6
+ from collections import defaultdict
7
+
8
+ BASE_URL = "https://api.jigsawstack.com/v1"
9
+ headers = {
10
+ "x-api-key": os.getenv("JIGSAWSTACK_API_KEY")
11
+ }
12
+
13
+
14
+ # Rate limiting configuration
15
+ request_times = defaultdict(list)
16
+ MAX_REQUESTS = 1 # Maximum requests per time window
17
+ TIME_WINDOW = 3600 # Time window in seconds (1 hour)
18
+
19
+ def get_real_ip(request: gr.Request):
20
+ """Extract real IP address using x-forwarded-for header or fallback"""
21
+ if not request:
22
+ return "unknown"
23
+
24
+ forwarded = request.headers.get("x-forwarded-for")
25
+ if forwarded:
26
+ ip = forwarded.split(",")[0].strip() # First IP in the list is the client's
27
+ else:
28
+ ip = request.client.host # fallback
29
+ return ip
30
+
31
+ def check_rate_limit(request: gr.Request):
32
+ """Check if the current request exceeds rate limits"""
33
+ if not request:
34
+ return True, "Rate limit check failed - no request info"
35
+
36
+ ip = get_real_ip(request)
37
+ now = time.time()
38
+
39
+ # Clean up old timestamps outside the time window
40
+ request_times[ip] = [t for t in request_times[ip] if now - t < TIME_WINDOW]
41
+
42
+
43
+ # Check if rate limit exceeded
44
+ if len(request_times[ip]) >= MAX_REQUESTS:
45
+ time_remaining = int(TIME_WINDOW - (now - request_times[ip][0]))
46
+ time_remaining_minutes = round(time_remaining / 60, 1)
47
+ time_window_minutes = round(TIME_WINDOW / 60, 1)
48
+
49
+ return False, f"Rate limit exceeded. You can make {MAX_REQUESTS} requests per {time_window_minutes} minutes. Try again in {time_remaining_minutes} minutes."
50
+
51
+ # Add current request timestamp
52
+ request_times[ip].append(now)
53
+ return True, ""
54
+
55
+
56
+ def text_to_speech(text, accent, voice_clone_id, request: gr.Request):
57
+ rate_limit_ok, rate_limit_msg = check_rate_limit(request)
58
+ if not rate_limit_ok:
59
+ return None, rate_limit_msg
60
+
61
+ if not text or not text.strip():
62
+ return None, "Error: Text input is required."
63
+
64
+ payload = {"text": text.strip()}
65
+
66
+ if accent and accent.strip():
67
+ payload["accent"] = accent.strip()
68
+
69
+ if voice_clone_id and voice_clone_id.strip():
70
+ payload["voice_clone_id"] = voice_clone_id.strip()
71
+
72
+ # Validate text length
73
+ max_len = 500 if "voice_clone_id" in payload else 1500
74
+ if len(payload["text"]) > max_len:
75
+ mode = "Voice Cloning" if "voice_clone_id" in payload else "Standard"
76
+ return None, f"Error: Text for {mode} is limited to {max_len} characters."
77
+
78
+ try:
79
+ response = requests.post(f"{BASE_URL}/ai/tts", headers=headers, json=payload)
80
+ response.raise_for_status()
81
+
82
+ if response.headers.get("content-type", "").startswith("audio/"):
83
+ import tempfile
84
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as tmp_file:
85
+ tmp_file.write(response.content)
86
+ return tmp_file.name, "βœ… Speech generated successfully!"
87
+ else:
88
+ try:
89
+ error_data = response.json()
90
+ return None, f"Error: API returned an error - {error_data.get('message', 'Unknown error')}"
91
+ except:
92
+ return None, "Error: Received an unexpected response from the API."
93
+
94
+ except requests.exceptions.RequestException as e:
95
+ return None, f"Request failed: {str(e)}"
96
+ except Exception as e:
97
+ return None, f"An unexpected error occurred: {str(e)}"
98
+
99
+
100
+ # ----------------- Gradio UI ------------------
101
+
102
+ with gr.Blocks() as demo:
103
+ gr.Markdown("""
104
+ <div style='text-align: center; margin-bottom: 24px;'>
105
+ <h1 style='font-size:2.2em; margin-bottom: 0.2em;'>🧩 Text to Speech</h1>
106
+ <p style='font-size:1.2em; margin-top: 0;'>Transform text into natural-sounding human-like AI voices with low latency and exceptional quality.</p>
107
+ <p style='font-size:1em; margin-top: 0.5em;'>For more details and API usage, see the <a href='https://jigsawstack.com/docs/api-reference/audio/tts/text-to-speech' target='_blank'>documentation</a>.</p>
108
+ </div>
109
+ """)
110
+
111
+ with gr.Row():
112
+ with gr.Column():
113
+ gr.Markdown("#### Input")
114
+ tts_text = gr.Textbox(
115
+ label="Text to Convert",
116
+ lines=5,
117
+ placeholder="Enter the text you want to convert to speech here."
118
+ )
119
+
120
+ gr.Markdown("#### Quick Examples")
121
+ gr.Markdown("Click any example below to auto-fill the text:")
122
+
123
+ with gr.Row():
124
+ tts_example_btn1 = gr.Button("πŸ‘‹ Greeting", size="sm")
125
+ tts_example_btn2 = gr.Button("πŸ“’ Announcement", size="sm")
126
+ tts_example_btn3 = gr.Button("πŸ“š Story", size="sm")
127
+
128
+ with gr.Row():
129
+ tts_example_btn4 = gr.Button("🎡 Song Lyrics", size="sm")
130
+ tts_example_btn5 = gr.Button("πŸ“– Poem", size="sm")
131
+ tts_example_btn6 = gr.Button("πŸ’Ό Business", size="sm")
132
+
133
+ with gr.Row():
134
+ tts_example_btn7 = gr.Button("🎭 Drama", size="sm")
135
+ tts_example_btn8 = gr.Button("πŸ”” Notification", size="sm")
136
+
137
+ accent = gr.Textbox(
138
+ label="Voice Accent (Optional)",
139
+ placeholder="e.g., en-US-female-27, en-GB-male-2",
140
+ info="Default voice is used if left blank. Ignored if Voice Clone ID is provided."
141
+ )
142
+
143
+ voice_clone_id = gr.Textbox(
144
+ label="Voice Clone ID (Optional)",
145
+ placeholder="Enter a voice clone ID to use a custom voice.",
146
+ info="Overrides the accent if provided."
147
+ )
148
+
149
+ with gr.Column():
150
+ gr.Markdown("#### Generated Audio")
151
+ audio_output = gr.Audio(label="Speech Output")
152
+ tts_status = gr.Textbox(label="Status", interactive=False, placeholder="Ready to generate speech...")
153
+
154
+ tts_btn = gr.Button("Generate Speech", variant="primary")
155
+
156
+ # Example functions to auto-fill text field
157
+ def fill_tts_example_1():
158
+ return "Hello! Welcome to our AI-powered text-to-speech system. This technology can convert any written text into natural-sounding speech."
159
+
160
+ def fill_tts_example_2():
161
+ return "Attention all passengers. Flight 1234 to New York is now boarding at gate 15. Please have your boarding pass ready."
162
+
163
+ def fill_tts_example_3():
164
+ return "Once upon a time, in a magical forest, there lived a wise old owl who loved to share stories with all the woodland creatures."
165
+
166
+ def fill_tts_example_4():
167
+ return "Twinkle twinkle little star, how I wonder what you are. Up above the world so high, like a diamond in the sky."
168
+
169
+ def fill_tts_example_5():
170
+ return "The road not taken by Robert Frost. Two roads diverged in a yellow wood, and sorry I could not travel both."
171
+
172
+ def fill_tts_example_6():
173
+ return "Thank you for your business. Your order has been confirmed and will be shipped within 2-3 business days."
174
+
175
+ def fill_tts_example_7():
176
+ return "To be or not to be, that is the question. Whether tis nobler in the mind to suffer the slings and arrows of outrageous fortune."
177
+
178
+ def fill_tts_example_8():
179
+ return "You have a new message. Please check your inbox for important updates regarding your account."
180
+
181
+ # Connect example buttons to auto-fill functions
182
+ tts_example_btn1.click(fill_tts_example_1, outputs=[tts_text])
183
+ tts_example_btn2.click(fill_tts_example_2, outputs=[tts_text])
184
+ tts_example_btn3.click(fill_tts_example_3, outputs=[tts_text])
185
+ tts_example_btn4.click(fill_tts_example_4, outputs=[tts_text])
186
+ tts_example_btn5.click(fill_tts_example_5, outputs=[tts_text])
187
+ tts_example_btn6.click(fill_tts_example_6, outputs=[tts_text])
188
+ tts_example_btn7.click(fill_tts_example_7, outputs=[tts_text])
189
+ tts_example_btn8.click(fill_tts_example_8, outputs=[tts_text])
190
+
191
+ tts_btn.click(
192
+ text_to_speech,
193
+ inputs=[tts_text, accent, voice_clone_id],
194
+ outputs=[audio_output, tts_status]
195
+ )
196
+
197
+
198
+
199
+ demo.launch()
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ gradio
2
+ requests
3
+ Pillow
4
+ python-dotenv