Update app.py
Browse files8 unmodified lines910111213141516171819202122232425262728292 unmodified lines323334353637383940414243444535 unmodified lines818283848586872 unmodified lines9091929394959697989910010125 unmodified lines1271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262278 unmodified linesimport loggingimport timefrom datetime import datetimefrom concurrent.futures import ThreadPoolExecutorfrom html.parser import HTMLParserfrom fastapi import FastAPI, Requestfrom fastapi.responses import JSONResponseimport uvicorn# Setup logginglogging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s')logger = logging.getLogger(__name__)# Initialize modelslogger.info("Loading Whisper-tiny...")whisper_model = WhisperModel("tiny", device="cpu", compute_type="int8")logger.info("Loading SmolLM2-360M-Instruct...")model_name = "HuggingFaceTB/SmolLM2-360M-Instruct"tokenizer = AutoTokenizer.from_pretrained(model_name)model = AutoModelForCausalLM.from_pretrained(2 unmodified linesdevice_map="cpu",low_cpu_mem_usage=True)logger.info("All models loaded!")TAVILY_API_KEY = os.getenv('TAVILY_API_KEY', '')BRAVE_API_KEY = os.getenv('BRAVE_API_KEY', '')def search_parallel(query):"""Simplified search - just DuckDuckGo for speed"""logger.info("[SEARCH] Starting...")try:response = requests.get(35 unmodified linesreturn "No search results", "None"def generate_answer(text_input):"""Main answer generation"""logger.info(f"[AI] Question: {text_input[:60]}...")try:2 unmodified linescurrent_date = datetime.now().strftime("%B %d, %Y")# Searchsearch_start = time.time()search_results, search_engine = search_parallel(text_input)logger.info(f"[AI] Search: {time.time()-search_start:.2f}s")# Generatemessages = [{"role": "system", "content": f"Today is {current_date}. Answer briefly using search results (60-80 words)."},{"role": "user", "content": f"Search:\n{search_results}\n\nQ: {text_input}\nA:"}25 unmodified lineslogger.error(f"[AI] Error: {str(e)}")return f"Error: {str(e)}"def transcribe_audio_base64(audio_base64):"""Transcribe audio"""logger.info("[STT] Start")try:audio_bytes = base64.b64decode(audio_base64)with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as temp_audio:temp_audio.write(audio_bytes)temp_path = temp_audio.namesegments, _ = whisper_model.transcribe(temp_path, language="en", beam_size=1)transcription = " ".join([seg.text for seg in segments])os.unlink(temp_path)logger.info("[STT] ✓")return transcription.strip()except Exception as e:logger.error(f"[STT] Error: {str(e)}")return ""# Create FastAPI app for Pluely endpointsapp = FastAPI()@app.post("/api/stt")async def api_stt(request: Request):"""Direct STT endpoint for Pluely"""try:body = await request.json()logger.info(f"[API STT] Received: {body}")audio_base64 = body.get("audio", "")if not audio_base64:return JSONResponse({"error": "No audio data"}, status_code=400)text = transcribe_audio_base64(audio_base64)return JSONResponse({"text": text})except Exception as e:logger.error(f"[API STT] Error: {str(e)}")return JSONResponse({"error": str(e)}, status_code=500)@app.post("/api/ai")async def api_ai(request: Request):"""Direct AI endpoint for Pluely"""try:body = await request.json()logger.info(f"[API AI] Received: {body}")question = body.get("text", "")if not question:return JSONResponse({"error": "No text provided"}, status_code=400)answer = generate_answer(question)return JSONResponse({"answer": answer})except Exception as e:logger.error(f"[API AI] Error: {str(e)}")return JSONResponse({"error": str(e)}, status_code=500)@app.get("/health")async def health():"""Health check"""return {"status": "ok", "model": "SmolLM2-360M"}# Gradio UI (optional, for testing)with gr.Blocks(title="Fast Q&A", theme=gr.themes.Soft()) as demo:gr.Markdown("""# ⚡ Ultra-Fast Q&A System**SmolLM2-360M** + **Direct REST API** for Pluely## Pluely Configuration:### STT Endpoint:```curl -X POST https://archcoder-basic-app.hf.space/api/stt -H "Content-Type: application/json" -d '{"audio": "{{AUDIO_BASE64}}"}'```**Response Path:** `text`### AI Endpoint:```curl -X POST https://archcoder-basic-app.hf.space/api/ai -H "Content-Type: application/json" -d '{"text": "{{TEXT}}"}'```**Response Path:** `answer`""")with gr.Tab("Test"):with gr.Row():test_input = gr.Textbox(label="Question", placeholder="Ask anything...")test_btn = gr.Button("🚀 Test")test_output = gr.Textbox(label="Answer", lines=8)test_btn.click(fn=generate_answer, inputs=[test_input], outputs=[test_output])# Mount Gradio to FastAPIapp = gr.mount_gradio_app(app, demo, path="/")if __name__ == "__main__":8 unmodified lines9101112131415161718192021222324252 unmodified lines2829303132333435363735 unmodified lines737475767778792 unmodified lines8283848586878889909125 unmodified lines1171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012028 unmodified linesimport loggingimport timefrom datetime import datetimefrom html.parser import HTMLParserfrom fastapi import FastAPI, Request, Queryfrom fastapi.responses import JSONResponseimport uvicornlogging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s')logger = logging.getLogger(__name__)# Modelslogger.info("Loading models...")whisper_model = WhisperModel("tiny", device="cpu", compute_type="int8")model_name = "HuggingFaceTB/SmolLM2-360M-Instruct"tokenizer = AutoTokenizer.from_pretrained(model_name)model = AutoModelForCausalLM.from_pretrained(2 unmodified linesdevice_map="cpu",low_cpu_mem_usage=True)logger.info("Models loaded!")def search_parallel(query):"""DuckDuckGo search"""logger.info("[SEARCH] Starting...")try:response = requests.get(35 unmodified linesreturn "No search results", "None"def generate_answer(text_input):"""Generate answer"""logger.info(f"[AI] Question: {text_input[:60]}...")try:2 unmodified linescurrent_date = datetime.now().strftime("%B %d, %Y")search_start = time.time()search_results, search_engine = search_parallel(text_input)logger.info(f"[AI] Search: {time.time()-search_start:.2f}s")messages = [{"role": "system", "content": f"Today is {current_date}. Answer briefly using search results (60-80 words)."},{"role": "user", "content": f"Search:\n{search_results}\n\nQ: {text_input}\nA:"}25 unmodified lineslogger.error(f"[AI] Error: {str(e)}")return f"Error: {str(e)}"# FastAPI appapp = FastAPI()@app.post("/api/ai")async def api_ai_post(request: Request):"""AI endpoint - POST with JSON body"""try:body = await request.body()logger.info(f"[API AI POST] Raw body: {body}")if not body:return JSONResponse({"error": "Empty request body"}, status_code=400)try:data = await request.json()except Exception as e:logger.error(f"[API AI POST] JSON parse error: {str(e)}")return JSONResponse({"error": f"Invalid JSON: {str(e)}"}, status_code=400)logger.info(f"[API AI POST] Parsed data: {data}")question = data.get("text", "")if not question:return JSONResponse({"error": "No 'text' field in JSON"}, status_code=400)answer = generate_answer(question)return JSONResponse({"answer": answer})except Exception as e:logger.error(f"[API AI POST] Error: {str(e)}")return JSONResponse({"error": str(e)}, status_code=500)@app.get("/api/ai")async def api_ai_get(text: str = Query(..., description="Question text")):"""AI endpoint - GET with query param (Pluely fallback)"""try:logger.info(f"[API AI GET] Question: {text}")if not text:return JSONResponse({"error": "No text parameter"}, status_code=400)answer = generate_answer(text)return JSONResponse({"answer": answer})except Exception as e:logger.error(f"[API AI GET] Error: {str(e)}")return JSONResponse({"error": str(e)}, status_code=500)@app.get("/health")async def health():return {"status": "ok", "model": "SmolLM2-360M"}# Gradio UIwith gr.Blocks(title="Fast Q&A") as demo:gr.Markdown("""# ⚡ Ultra-Fast Q&A - SmolLM2-360M## 🎯 Pluely Configuration### Option 1: GET with Query Param (EASIEST - Windows Compatible)```curl https://archcoder-basic-app.hf.space/api/ai?text={{TEXT}}```**Response Path:** `answer`### Option 2: POST with JSON (If Option 1 doesn't work)```curl -X POST https://archcoder-basic-app.hf.space/api/ai -H "Content-Type: application/json" --data-binary @- << EOF{"text":"{{TEXT}}"}EOF```**Response Path:** `answer`""")with gr.Tab("Test"):test_input = gr.Textbox(label="Question")test_btn = gr.Button("🚀 Test")test_output = gr.Textbox(label="Answer", lines=8)test_btn.click(fn=generate_answer, inputs=[test_input], outputs=[test_output])app = gr.mount_gradio_app(app, demo, path="/")if __name__ == "__main__":
app.py+49-74