Update app.py
Browse files50 unmodified lines515253545455575657585962606162666364658 unmodified lines747576817778847980816 unmodified lines88899097989192937 unmodified lines1011021031121041051061161071081092 unmodified lines11211311412512612712812913013113213313413513613713813914014114211511611711814511912012112210 unmodified lines13313413516213613713813914016714114214314414514617314714814915015115215315415515615715815916016116217 unmodified lines18018118219918320120218418518618718812 unmodified lines20120220322120422320520620720819 unmodified lines2282292302492312322331 unmodified line23523623725725825923823924024126424224324426826924524627127224724824925027627725125225328025425525625728428525825926028728828926126226326426526626726829629726927027129930027227327427527627727827930730828028128250 unmodified linesdef transcribe_audio_base64(audio_base64): """Transcribe audio from base64 string (for Pluely STT endpoint)""" try: # Decode base64 audio audio_bytes = base64.b64decode(audio_base64) # Save to temporary file with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as temp_audio: temp_audio.write(audio_bytes) temp_path = temp_audio.name # Transcribe segments, _ = whisper_model.transcribe(temp_path, language="en", beam_size=1) transcription = " ".join([seg.text for seg in segments]) # Cleanup os.unlink(temp_path) return {"text": transcription.strip()}8 unmodified lines yield "No input provided" return # Web search (non-streaming part) search_results = search_web(text_input, max_results=2) # Prepare messages messages = [ {"role": "system", "content": "You are a helpful assistant. Answer briefly using provided context. Keep responses under 40 words."}, {"role": "user", "content": f"Context:\n{search_results}\n\nQuestion: {text_input}\n\nAnswer:"}6 unmodified lines ) inputs = tokenizer([text], return_tensors="pt").to("cpu") # Setup streaming streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True) generation_kwargs = dict(7 unmodified lines streamer=streamer ) # Start generation in separate thread thread = Thread(target=model.generate, kwargs=generation_kwargs) thread.start() # Stream tokens as they're generated generated_text = "" for new_text in streamer: generated_text += new_text2 unmodified lines except Exception as e: yield f"Error: {str(e)}"
def generate_answer(text_input): """Generate complete answer (non-streaming)""" try: if not text_input or text_input.strip() == "": return "No input provided" # Get the last chunk from streaming final_answer = "" for chunk in generate_answer_stream(text_input): final_answer = chunk return final_answer except Exception as e: return f"Error: {str(e)}"
def process_audio_stream(audio_path, question_text=None): """Streaming pipeline for Gradio UI - Returns tuple generator"""def process_audio_stream(audio_path, question_text): """Streaming pipeline that yields tuples""" start_time = time.time() # Step 1: Transcribe audio if provided # Transcribe if audio provided if audio_path: try: segments, _ = whisper_model.transcribe(audio_path, language="en", beam_size=1)10 unmodified lines transcription_time = time.time() - start_time # Step 2: Web search # Web search search_start = time.time() search_results = search_web(question, max_results=2) search_time = time.time() - search_start # Step 3: Stream answer generation # Stream answer llm_start = time.time() for partial_answer in generate_answer_stream(question): current_time = time.time() - start_time time_emoji = "🟢" if current_time < 3.0 else "🟡" if current_time < 3.5 else "🔴" timing_info = f"\n\n{time_emoji} **Timing:** Trans={transcription_time:.2f}s | Search={search_time:.2f}s | LLM={(time.time()-llm_start):.2f}s | **Total={current_time:.2f}s**" # IMPORTANT: Must yield tuple (text, number) to match output components yield partial_answer + timing_info, current_time
# Wrapper functions for proper API handlingdef audio_handler(audio_path): """Wrapper for audio input""" for result in process_audio_stream(audio_path, None): yield result
def text_handler(text_input): """Wrapper for text input""" for result in process_audio_stream(None, text_input): yield result
# Create Gradio interfacewith gr.Blocks(title="Fast Q&A - Streaming Enabled", theme=gr.themes.Soft()) as demo: gr.Markdown("""17 unmodified lines audio_output = gr.Textbox(label="Answer (Streaming)", lines=8, show_copy_button=True) audio_time = gr.Number(label="Response Time (seconds)", precision=2) # Fixed: Lambda wrapper ensures proper tuple unpacking audio_submit.click( fn=process_audio_stream, inputs=[audio_input, gr.Textbox(value=None, visible=False)], fn=audio_handler, inputs=[audio_input], outputs=[audio_output, audio_time], api_name="audio_query_stream" )12 unmodified lines text_output = gr.Textbox(label="Answer (Streaming)", lines=8, show_copy_button=True) text_time = gr.Number(label="Response Time (seconds)", precision=2) # Fixed: Proper function call with audio=None text_submit.click( fn=lambda text: process_audio_stream(None, text), fn=text_handler, inputs=[text_input], outputs=[text_output, text_time], api_name="text_query_stream"19 unmodified lines -H "Content-Type: application/json" \\ -d '{"data": ["BASE64_AUDIO_DATA"]}' ``` **Response Format:** `{"data": [{"text": "transcribed text"}]}` ### 2. AI Endpoint - Streaming ```1 unmodified line -H "Content-Type: application/json" \\ -d '{"data": ["Your question here"]}' ``` **Response Format:** Streaming text chunks --- ## Pluely Configuration ### Custom STT Provider: **Curl Command:** ``` curl https://archcoder-basic-app.hf.space/call/transcribe_stt -H "Content-Type: application/json" -d '{"data": ["{{AUDIO_BASE64}}"]}' ``` **Response Content Path:** `data[0].text` **Streaming:** OFF **Response Path:** `data[0].text` | **Streaming:** OFF ### Custom AI Provider (Streaming): **Curl Command:** ### Custom AI Provider: ``` curl https://archcoder-basic-app.hf.space/call/answer_ai_stream -H "Content-Type: application/json" -d '{"data": ["{{TEXT}}"]}' ``` **Response Content Path:** `data` **Streaming:** ON ✅ **Response Path:** `data` | **Streaming:** ON ✅ """) # Hidden interface components that create API endpoints # Hidden components for API endpoints with gr.Row(visible=False): stt_input = gr.Textbox() stt_output = gr.JSON() ai_stream_input = gr.Textbox() ai_stream_output = gr.Textbox() ai_input = gr.Textbox() ai_output = gr.Textbox() # These create the /call/transcribe_stt and /call/answer_ai_stream endpoints stt_button = gr.Button("STT", visible=False) stt_button.click( stt_btn = gr.Button("STT", visible=False) stt_btn.click( fn=transcribe_audio_base64, inputs=[stt_input], outputs=[stt_output], api_name="transcribe_stt" ) ai_stream_button = gr.Button("AI Stream", visible=False) ai_stream_button.click( ai_btn = gr.Button("AI", visible=False) ai_btn.click( fn=generate_answer_stream, inputs=[ai_stream_input], outputs=[ai_stream_output], inputs=[ai_input], outputs=[ai_output], api_name="answer_ai_stream" ) gr.Markdown(""" --- 🟢 = Under 3s | 🟡 = 3-3.5s | 🔴 = Over 3.5s **Streaming Mode:** Words appear as they're generated - much faster perceived response! """)
if __name__ == "__main__":app.py+31-60