import streamlit as st import requests import base64 import sounddevice as sd import soundfile as sf import tempfile # ✅ 替換成你的 ngrok 或 render 後端 API_BASE = "https://f876-125-228-143-171.ngrok-free.app " st.set_page_config(page_title="📇 名片辨識與語音輸入", layout="centered") st.title("📷 拍照 + 🎙 語音辨識系統") st.header("📸 名片拍照辨識") img_file = st.camera_input("請拍攝名片") if img_file: st.image(img_file, caption="名片預覽", use_column_width=True) img_bytes = img_file.getvalue() base64_img = base64.b64encode(img_bytes).decode("utf-8") payload = {"image": f"data:image/jpeg;base64,{base64_img}"} with st.spinner("🧠 OCR 處理中..."): try: res = requests.post(f"{API_BASE}/ocr", json=payload) text = res.json().get("text", "") st.text_area("📄 辨識結果", value=text, height=200) except Exception as e: st.error(f"❌ 錯誤:{e}") st.header("🎤 語音辨識(Whisper)") duration = st.slider("⏱ 錄音秒數", 2, 10, 4) if st.button("🎙 開始錄音"): with st.spinner("🎧 錄音中..."): fs = 16000 audio = sd.rec(int(duration * fs), samplerate=fs, channels=1) sd.wait() with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as tmp: sf.write(tmp.name, audio, fs) tmp.seek(0) audio_bytes = tmp.read() st.audio(audio_bytes, format="audio/wav") with st.spinner("🧠 Whisper 處理中..."): try: res = requests.post( f"{API_BASE}/whisper", files={"file": ("audio.wav", audio_bytes, "audio/wav")} ) result = res.json().get("text", "") st.text_area("📝 語音辨識結果", value=result, height=200) except Exception as e: st.error(f"❌ Whisper API 錯誤:{e}")