Update app.py
Browse files7 unmodified lines89101112131415161714 unmodified lines3233343536373827 unmodified lines6667686970717273747576777879803 unmodified lines8485868788899091929315 unmodified lines1091101111121131141154 unmodified lines1201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581592 unmodified lines1621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002017 unmodified linesimport osimport 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')14 unmodified linesdef search_parallel(query):"""DuckDuckGo search"""logger.info("[SEARCH] Starting...")try:response = requests.get('https://html.duckduckgo.com/html/',27 unmodified linesparser = DDGParser()parser.feed(response.text)result = "\n".join([f"• {r}" for r in parser.results[:2]]) if parser.results else "No results"logger.info("[SEARCH] ✓")return result, "DuckDuckGo"except:passreturn "No search results", "None"def generate_answer(text_input):"""Generate answer"""logger.info(f"[AI] Question: {text_input[:60]}...")try:if not text_input or not text_input.strip():3 unmodified linessearch_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:"}]15 unmodified lines)answer = tokenizer.decode(outputs[0][inputs['input_ids'].shape[1]:], skip_special_tokens=True).strip()logger.info(f"[AI] Gen: {time.time()-gen_start:.2f}s | ✓")return f"{answer}\n\n**Source:** {search_engine}"4 unmodified lines# 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)2 unmodified linesreturn 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="/")7 unmodified lines891011121314151617181914 unmodified lines3435363738394027 unmodified lines6869707172737475767778798081823 unmodified lines868788899091929394959615 unmodified lines1121131141151161171181191204 unmodified lines1251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921932 unmodified lines1961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782797 unmodified linesimport osimport loggingimport timeimport jsonfrom datetime import datetimefrom html.parser import HTMLParserfrom fastapi import FastAPI, Request, Queryfrom fastapi.responses import JSONResponsefrom fastapi.middleware.cors import CORSMiddlewareimport uvicornlogging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s')14 unmodified linesdef search_parallel(query):"""DuckDuckGo search"""logger.info(f"[SEARCH] Query: {query}")try:response = requests.get('https://html.duckduckgo.com/html/',27 unmodified linesparser = DDGParser()parser.feed(response.text)result = "\n".join([f"• {r}" for r in parser.results[:2]]) if parser.results else "No results"logger.info(f"[SEARCH] ✓ Found {len(parser.results)} results")return result, "DuckDuckGo"except Exception as e:logger.error(f"[SEARCH] Error: {str(e)}")return "No search results", "None"def generate_answer(text_input):"""Generate answer"""logger.info(f"[AI] Question: {text_input}")try:if not text_input or not text_input.strip():3 unmodified linessearch_start = time.time()search_results, search_engine = search_parallel(text_input)search_time = time.time() - search_startlogger.info(f"[AI] Search: {search_time:.2f}s")messages = [{"role": "system", "content": f"Today is {current_date}. Answer briefly (60-80 words)."},{"role": "user", "content": f"Search:\n{search_results}\n\nQ: {text_input}\nA:"}]15 unmodified lines)answer = tokenizer.decode(outputs[0][inputs['input_ids'].shape[1]:], skip_special_tokens=True).strip()gen_time = time.time() - gen_startlogger.info(f"[AI] Gen: {gen_time:.2f}s")logger.info(f"[AI] Answer: {answer[:100]}...")return f"{answer}\n\n**Source:** {search_engine}"4 unmodified lines# FastAPI appapp = FastAPI()# Add CORSapp.add_middleware(CORSMiddleware,allow_origins=["*"],allow_credentials=True,allow_methods=["*"],allow_headers=["*"],)@app.middleware("http")async def log_requests(request: Request, call_next):"""Log all requests"""logger.info("="*80)logger.info(f"[REQUEST] Method: {request.method}")logger.info(f"[REQUEST] URL: {request.url}")logger.info(f"[REQUEST] Headers: {dict(request.headers)}")logger.info(f"[REQUEST] Query params: {dict(request.query_params)}")# Read body if POSTif request.method == "POST":body = await request.body()logger.info(f"[REQUEST] Raw body ({len(body)} bytes): {body}")try:body_str = body.decode('utf-8')logger.info(f"[REQUEST] Body as string: {body_str}")body_json = json.loads(body_str)logger.info(f"[REQUEST] Body as JSON: {body_json}")except Exception as e:logger.error(f"[REQUEST] Body parse error: {str(e)}")response = await call_next(request)logger.info(f"[RESPONSE] Status: {response.status_code}")logger.info("="*80)return response@app.post("/api/ai")async def api_ai_post(request: Request):"""AI endpoint - POST"""try:body = await request.body()if not body:return JSONResponse({"error": "Empty body"}, status_code=400)data = json.loads(body.decode('utf-8'))logger.info(f"[API POST] Parsed: {data}")question = data.get("text", "")if not question:return JSONResponse({"error": "No 'text' field"}, status_code=400)answer = generate_answer(question)return JSONResponse({"answer": answer})except Exception as e:logger.error(f"[API POST] Error: {str(e)}")return JSONResponse({"error": str(e)}, status_code=500)@app.get("/api/ai")async def api_ai_get(text: str = Query(default="", description="Question")):"""AI endpoint - GET"""try:logger.info(f"[API GET] text param: '{text}'")if not text:return JSONResponse({"error": "No text parameter"}, status_code=400)2 unmodified linesreturn JSONResponse({"answer": answer})except Exception as e:logger.error(f"[API GET] Error: {str(e)}")return JSONResponse({"error": str(e)}, status_code=500)@app.get("/health")async def health():return {"status": "ok", "model": "SmolLM2-360M", "endpoints": ["/api/ai (GET/POST)"]}# Gradio UIwith gr.Blocks(title="Fast Q&A") as demo:gr.Markdown("""# ⚡ Fast Q&A - SmolLM2-360M## 🎯 Pluely Configuration### Method 1: GET Request (RECOMMENDED - Works with Pluely)**Curl Command for Pluely:**```curl https://archcoder-basic-app.hf.space/api/ai?text={{TEXT}}```**Response Path:** `answer`**Streaming:** OFF---### Method 2: POST Request (Alternative)**Curl Command for Pluely:**```curl -X POST https://archcoder-basic-app.hf.space/api/ai -H "Content-Type: application/json" -d {\"text\":\"{{TEXT}}\"}```**Response Path:** `answer`**Streaming:** OFF---## 🧪 Test Manually**Windows CMD:**```curl "https://archcoder-basic-app.hf.space/api/ai?text=Who+is+the+president"```**PowerShell:**```Invoke-RestMethod -Uri "https://archcoder-basic-app.hf.space/api/ai?text=Who is the president"```**Browser:**```https://archcoder-basic-app.hf.space/api/ai?text=Who is the president```""")with gr.Tab("Test"):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])with gr.Tab("Logs"):gr.Markdown("""## How to Check Logs1. Go to your Hugging Face Space2. Click on **"Logs"** tab at the top3. You'll see all requests with:- Request method and URL- Headers- Body content- ResponseThis helps debug what Pluely is actually sending!""")app = gr.mount_gradio_app(app, demo, path="/")
app.py+110-32