Spaces:
Sleeping
Sleeping
Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293import spacesimport gradio as grimport edge_ttsimport asyncioimport tempfileimport osimport re# Get all available voicesasync def get_voices():voices = await edge_tts.list_voices()return {f"{v['ShortName']} - {v['Locale']} ({v['Gender']})": v['ShortName'] for v in voices}# Split text into words for precise clickingdef split_text_into_words(text):if not text.strip():return []words = re.findall(r'\S+', text)return words# Create interactive HTML with clickable wordsdef create_interactive_text(text):if not text.strip():return "<p style='color: #666; font-style: italic;'>Enter text and generate audio to see interactive text here...</p>"words = split_text_into_words(text)html = f"""<div id="interactive-text-container" style="line-height: 1.8; font-size: 16px; padding: 20px; border: 2px solid #2196f3; border-radius: 12px; background: linear-gradient(135deg, #f8fdff 0%, #e3f2fd 100%); margin: 10px 0;"><div style="margin-bottom: 15px; padding: 10px; background: rgba(33, 150, 243, 0.1); border-radius: 8px; text-align: center;"><p style="margin: 0; font-weight: bold; color: #1976d2; font-size: 14px;">🎯 Click on any word below to start reading from that position</p></div><div id="clickable-text" style="line-height: 1.6;">"""# Reconstruct text with clickable wordstext_with_indices = ""word_index = 0current_pos = 0for match in re.finditer(r'(\S+)(\s*)', text):word = match.group(1)space = match.group(2)text_with_indices += f'''<span class="clickable-word"data-index="{word_index}"data-position="{current_pos}"style="cursor: pointer; padding: 1px 2px; border-radius: 3px; transition: all 0.2s; display: inline-block; margin: 1px;"onmouseover="this.style.backgroundColor='#bbdefb'; this.style.transform='scale(1.05)';"onmouseout="this.style.backgroundColor='transparent'; this.style.transform='scale(1)';"onclick="handleWordClick({current_pos}, {word_index})">{word}</span>{space}'''word_index += 1current_pos = match.end()html += text_with_indiceshtml += """</div></div><script>const originalText = `""" + text.replace('`', '\\`').replace('\\', '\\\\') + """`;function handleWordClick(position, wordIndex) {console.log('Word clicked at position:', position, 'word index:', wordIndex);// Get text from clicked positionconst textFromPosition = originalText.substring(position);console.log('Text from position:', textFromPosition.substring(0, 50) + '...');// Visual feedback - highlight from clicked word onwardsconst allWords = document.querySelectorAll('.clickable-word');// Reset all highlightsallWords.forEach((word, index) => {if (index >= wordIndex) {word.style.backgroundColor = '#c8e6c9';word.style.fontWeight = 'bold';} else {word.style.backgroundColor = 'transparent';word.style.fontWeight = 'normal';}});// Trigger Gradio event by updating the textbox valueconst event = new CustomEvent('wordClicked', {detail: {text: textFromPosition,position: position,wordIndex: wordIndex}});// Store in window for access by Gradiowindow.clickedText = textFromPosition;window.clickedPosition = position;// Dispatch custom eventdocument.dispatchEvent(event);// Also try to find and update hidden textbox directlysetTimeout(() => {const hiddenTextarea = document.querySelector('textarea[data-testid="textbox"]:not([style*="display: block"])');if (hiddenTextarea) {hiddenTextarea.value = textFromPosition;hiddenTextarea.dispatchEvent(new Event('input', { bubbles: true }));}}, 100);}// Function to get clicked text (called by Gradio)function getClickedText() {return window.clickedText || '';}</script>"""return html# Text-to-speech functionasync def text_to_speech(text, voice, rate, pitch):if not text.strip():return None, "Please enter text to convert."if not voice:return None, "Please select a voice."try:voice_short_name = voice.split(" - ")[0] if " - " in voice else voicerate_str = f"{rate:+d}%"pitch_str = f"{pitch:+d}Hz"communicate = edge_tts.Communicate(text, voice_short_name, rate=rate_str, pitch=pitch_str)with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as tmp_file:tmp_path = tmp_file.nameawait communicate.save(tmp_path)return tmp_path, "✅ Audio generated! Click any word in the text below to start from that position."except Exception as e:return None, f"❌ Error: {str(e)}"# Generate full audio@spaces.GPUdef generate_full_audio(text, voice, rate, pitch):if not text.strip():return None, "", "Please enter some text first."if not voice:return None, "", "Please select a voice."audio_path, message = asyncio.run(text_to_speech(text, voice, rate, pitch))interactive_html = create_interactive_text(text)return audio_path, interactive_html, message# Generate partial audio - this will be called when text is clicked@spaces.GPUdef generate_partial_audio(clicked_text, voice, rate, pitch):if not clicked_text or not clicked_text.strip():return None, "No text was clicked."print(f"Generating partial audio for: {clicked_text[:50]}...") # Debugaudio_path, message = asyncio.run(text_to_speech(clicked_text, voice, rate, pitch))if audio_path:return audio_path, f"🎵 Playing from clicked position: '{clicked_text[:30]}...'"else:return None, f"❌ Failed to generate audio: {message}"# Function to handle click events (bridge between JS and Python)def handle_text_click(full_text, voice, rate, pitch):# This function will be called by JavaScript# JavaScript will pass the clicked text through a hidden componentreturn "Click detected - processing..."# Create the Gradio applicationasync def create_demo():voices = await get_voices()voice_choices = list(voices.keys())with gr.Blocks(title="Interactive Text-to-Speech",theme=gr.themes.Soft()) as demo:gr.Markdown("""# 🎤 Interactive Text-to-Speech## Click anywhere in your text to start reading from that position!""")with gr.Row():with gr.Column(scale=1):gr.Markdown("### 📝 Input")text_input = gr.Textbox(label="Your Text",lines=6,value="Hello and welcome to the interactive text-to-speech system. This incredible technology allows you to click on any word in this sentence and the system will start reading from exactly that position. Try it out by first generating the audio, then clicking anywhere in this text to hear it read from that point!")voice_dropdown = gr.Dropdown(choices=voice_choices,label="Voice",value=voice_choices[0] if voice_choices else None)with gr.Row():rate_slider = gr.Slider(-50, 50, 0, step=5, label="Speed (%)")pitch_slider = gr.Slider(-20, 20, 0, step=2, label="Pitch (Hz)")generate_btn = gr.Button("🎵 Generate Interactive Audio", variant="primary", size="lg")with gr.Column(scale=1):gr.Markdown("### 🔊 Audio Output")full_audio = gr.Audio(label="Full Audio")partial_audio = gr.Audio(label="Audio from Clicked Position")status_box = gr.Textbox(label="Status", interactive=False, lines=2)gr.Markdown("### 🎯 Interactive Text (Click any word)")interactive_display = gr.HTML(value="<div style='text-align: center; padding: 40px; color: #666;'>📝 Generate audio first to see clickable text</div>")# Hidden textbox to capture clicked textclicked_text_box = gr.Textbox(visible=False, interactive=True)# Create a polling mechanism to check for clicksdef check_for_clicks(current_clicked_text, voice, rate, pitch):if current_clicked_text and current_clicked_text.strip():# Generate audio for the clicked textreturn generate_partial_audio(current_clicked_text, voice, rate, pitch)return None, "Waiting for text click..."# Event handlersgenerate_btn.click(fn=generate_full_audio,inputs=[text_input, voice_dropdown, rate_slider, pitch_slider],outputs=[full_audio, interactive_display, status_box])# Monitor the hidden textbox for changes (when JavaScript updates it)clicked_text_box.change(fn=check_for_clicks,inputs=[clicked_text_box, voice_dropdown, rate_slider, pitch_slider],outputs=[partial_audio, status_box])# Add JavaScript to bridge the gapdemo.load(js="""function setupClickHandler() {console.log('Setting up click handler...');// Function to update the hidden textbox when text is clickeddocument.addEventListener('wordClicked', function(e) {console.log('Word clicked event received:', e.detail);// Find the hidden textbox and update its valuesetTimeout(() => {const textareas = document.querySelectorAll('textarea');const hiddenTextarea = Array.from(textareas).find(ta =>ta.style.display === 'none' ||ta.parentElement.style.display === 'none' ||ta.closest('[style*="display: none"]'));if (hiddenTextarea) {console.log('Found hidden textarea, updating with:', e.detail.text.substring(0, 50));hiddenTextarea.value = e.detail.text;// Trigger the change eventconst event = new Event('input', { bubbles: true });hiddenTextarea.dispatchEvent(event);// Also try blur eventsetTimeout(() => {hiddenTextarea.dispatchEvent(new Event('blur', { bubbles: true }));}, 100);} else {console.log('Hidden textarea not found');}}, 200);});}setupClickHandler();""")return demo# Run the applicationif __name__ == "__main__":demo = asyncio.run(create_demo())demo.launch(share=True, debug=True)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159import gradio as grimport edge_ttsimport asynciofrom typing import Optionalimport os# Global variables to manage playbackcurrent_playback_task = Nonecurrent_position = 0stop_playback_flag = Falseasync def text_to_speech(text: str, play_from: int = 0, voice: str = "en-US-GuyNeural") -> tuple[str, str]:global current_playback_task, current_position, stop_playback_flag# Stop any ongoing playbackstop_playback()# Get only the text from the specified positiontext_to_read = text[play_from:]current_position = play_from# Create a new playback taskcurrent_playback_task = asyncio.create_task(play_audio(text_to_read, voice))return text, f"Playing from position {play_from}..."async def play_audio(text: str, voice: str):try:communicate = edge_tts.Communicate(text, voice)async for chunk in communicate.stream():if stop_playback_flag:breakexcept Exception as e:print(f"Playback error: {e}")def stop_playback():global current_playback_task, stop_playback_flagif current_playback_task:stop_playback_flag = Truecurrent_playback_task.cancel()stop_playback_flag = Falsedef handle_word_click(word_index: int, text: str, voice: str) -> tuple[str, str]:global current_position# Convert word index to character positionwords = text.split()if word_index < len(words):# Find the character position of the clicked wordchar_pos = 0for i, word in enumerate(words):if i == word_index:breakchar_pos += len(word) + 1 # +1 for the space# Start playback from this positionreturn asyncio.run(text_to_speech(text, char_pos, voice))return text, "Invalid word selection"async def get_voices():voices = await edge_tts.list_voices()return [v["ShortName"] for v in voices if v["Locale"].startswith("en-")]# JavaScript for interactive textjs = """function splitText(text) {if (!text) return '';const words = text.split(' ');return words.map((word, index) => {return `<span class="word" data-index="${index}"style="cursor:pointer; margin-right:5px;"onmouseover="this.style.backgroundColor='#f0f0f0'"onmouseout="this.style.backgroundColor='transparent'"onclick="handleWordClick(this)">${word}</span>`;}).join(' ');}function handleWordClick(element) {const index = element.getAttribute('data-index');document.getElementById('word-index').value = index;document.getElementById('word-index').dispatchEvent(new Event('input'));}function updateTextDisplay(text) {const container = document.getElementById('text-display');container.innerHTML = splitText(text);}document.addEventListener('DOMContentLoaded', function() {// Update display when text changesconst textInput = document.querySelector('#text-input textarea');if (textInput) {textInput.addEventListener('input', function() {updateTextDisplay(this.value);});}});"""css = """.word:hover { background-color: #f0f0f0; }#text-display {padding: 10px;border: 1px solid #ccc;border-radius: 5px;min-height: 100px;white-space: pre-wrap;}"""with gr.Blocks(js=js, css=css) as demo:gr.Markdown("# Interactive TTS Service (edge-tts)")gr.Markdown("Enter text below and click 'Speak' to hear it. Click on any word to start playback from that point.")with gr.Row():text_input = gr.Textbox(label="Input Text", lines=5, elem_id="text-input")word_index = gr.Number(visible=False, elem_id="word-index")with gr.Row():text_display = gr.HTML(elem_id="text-display")with gr.Row():voice_dropdown = gr.Dropdown(label="Voice", choices=asyncio.run(get_voices()), value="en-US-GuyNeural")rate_slider = gr.Slider(50, 200, value=100, label="Speed (%)")with gr.Row():speak_btn = gr.Button("Speak", variant="primary")stop_btn = gr.Button("Stop")status = gr.Textbox(label="Status", interactive=False)# Event handlerstext_input.change(fn=lambda x: x,inputs=text_input,outputs=text_display,_js="(x) => { updateTextDisplay(x); return x; }")word_index.change(fn=handle_word_click,inputs=[word_index, text_input, voice_dropdown],outputs=[text_input, status])speak_btn.click(fn=lambda text, voice: asyncio.run(text_to_speech(text, 0, voice)),inputs=[text_input, voice_dropdown],outputs=[text_input, status])stop_btn.click(fn=stop_playback,outputs=status,_js="() => { return 'Playback stopped'; }")if __name__ == "__main__":demo.launch()
app.py+136-270