PYTHON #4
Browse files1234MODEL_NAME=adibrino/LAPOR-AIALLOWED_ORIGINS=https://lalim.vercel.app,http://localhost:8000,http://127.0.0.1:8000SERVICE_CODES_MAP="{'DPRKPCK': 'Perumahan Rakyat, Kawasan Permukiman dan Cipta Karya', 'DPUBM': 'Pekerjaan Umum Bina Marga', 'DPUSDA': 'Pekerjaan Umum Sumber Daya Air', 'DLH': 'Lingkungan Hidup', 'DINSOS': 'Sosial', 'BPBD': 'Penanggulangan Bencana Daerah', 'DISHUB': 'Perhubungan', 'DINKES': 'Kesehatan', 'SATPOLPP': 'Satuan Polisi Pamong Praja', 'DISKOMINFO': 'Komunikasi dan Informatika', 'DISNAKERTRANS': 'Tenaga Kerja dan Transmigrasi', 'DIPERTAKP': 'Pertanian dan Ketahanan Pangan', 'DISNAK': 'Peternakan', 'DKP': 'Kelautan dan Perikanan', 'DINDIK': 'Pendidikan', 'DISBUDPAR': 'Kebudayaan dan Pariwisata', 'DISPERINDAG': 'Perindustrian dan Perdagangan', 'DPMPTSP': 'Penanaman Modal dan Pelayanan Terpadu Satu Pintu', 'DISKOPUKM': 'Koperasi, Usaha Kecil dan Menengah', 'DISPORA': 'Kepemudaan dan Olahraga', 'DISPERPUSIP': 'Perpustakaan dan Kearsipan', 'BAPPEDA': 'Perencanaan Pembangunan Daerah', 'BAPENDA': 'Pajak dan Pendapatan Daerah', 'DP3AK': 'Pemberdayaan Perempuan, Perlindungan Anak dan Kependudukan'}"IS_PRODUCTION=false1234MODEL_NAME=adibrino/LAPOR-AIALLOWED_ORIGINS=https://lalim.vercel.app,http://localhost:8000,http://127.0.0.1:8000SERVICE_CODES_MAP={"DPRKPCK": "Perumahan Rakyat, Kawasan Permukiman dan Cipta Karya", "DPUBM": "Pekerjaan Umum Bina Marga", "DPUSDA": "Pekerjaan Umum Sumber Daya Air", "DLH": "Lingkungan Hidup", "DINSOS": "Sosial", "BPBD": "Penanggulangan Bencana Daerah", "DISHUB": "Perhubungan", "DINKES": "Kesehatan", "SATPOLPP": "Satuan Polisi Pamong Praja", "DISKOMINFO": "Komunikasi dan Informatika", "DISNAKERTRANS": "Tenaga Kerja dan Transmigrasi", "DIPERTAKP": "Pertanian dan Ketahanan Pangan", "DISNAK": "Peternakan", "DKP": "Kelautan dan Perikanan", "DINDIK": "Pendidikan", "DISBUDPAR": "Kebudayaan dan Pariwisata", "DISPERINDAG": "Perindustrian dan Perdagangan", "DPMPTSP": "Penanaman Modal dan Pelayanan Terpadu Satu Pintu", "DISKOPUKM": "Koperasi, Usaha Kecil dan Menengah", "DISPORA": "Kepemudaan dan Olahraga", "DISPERPUSIP": "Perpustakaan dan Kearsipan", "BAPPEDA": "Perencanaan Pembangunan Daerah", "BAPENDA": "Pajak dan Pendapatan Daerah", "DP3AK": "Pemberdayaan Perempuan, Perlindungan Anak dan Kependudukan"}IS_PRODUCTION=false
8 unmodified lines91011121314151617181920213 unmodified lines25262728293031323334353637383945 unmodified lines858687888990912 unmodified lines9495969798991001011021031041 unmodified line1061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092108 unmodified linesfrom typing import List, Any, Dict, Unionfrom fastapi import FastAPI, UploadFile, File, Formfrom fastapi.responses import JSONResponsefrom fastapi.middleware.cors import CORSMiddlewareimport uvicornfrom PIL import Imagefrom dotenv import load_dotenvimport ollamaimport spacesimport gradio as grload_dotenv()3 unmodified linesIS_PRODUCTION: str = os.getenv("IS_PRODUCTION", "false")SERVICE_MAP_STR = os.getenv("SERVICE_CODES_MAP", "{}")try:SERVICE_MAP = json.loads(SERVICE_MAP_STR)except json.JSONDecodeError:SERVICE_MAP = {}if ALLOWED_ORIGINS_RAW == "*":ALLOWED_ORIGINS = ["*"]else:ALLOWED_ORIGINS = [origin.strip() for origin in ALLOWED_ORIGINS_RAW.split(",")]print(f"ALLOWED_ORIGINS: {ALLOWED_ORIGINS}")print(f"MODEL_NAME: {MODEL_NAME}")45 unmodified linesreturn None@spaces.GPU(duration=60)def run_inference(text_laporan: str, base64_images: List[str]) -> Dict[str, Any]:print("Starting GPU Inference...")try:2 unmodified linesprint("Model not found in GPU context, pulling again...")subprocess.run(["ollama", "pull", MODEL_NAME], check=True)response: Any = ollama.chat(model=MODEL_NAME,messages=[{'role': 'user','content': text_laporan,'images': base64_images if base64_images else None # type: ignore}],format='json',1 unmodified line)if isinstance(response, dict):return responsereturn dict(response)@app.get("/")def health_check():return {"status": "Python Backend with ZeroGPU is running."}@app.post("/api/analyze")async def analyze(laporan: str = Form(...),images: List[UploadFile] = File(...)):if not laporan or len(laporan) < 10:return JSONResponse(status_code=400,content={"status": "error", "message": "Deskripsi laporan wajib diisi minimal 10 karakter."})if not images:return JSONResponse(status_code=400,content={"status": "error", "message": "Wajib melampirkan minimal 1 foto bukti."})base64_images: List[str] = []for img_file in images:content = await img_file.read()if len(content) > 0:b64 = process_image_to_base64(content)if b64:base64_images.append(b64)if not base64_images:return JSONResponse(status_code=400,content={"status": "error", "message": "File gambar tidak valid/corrupt."})max_retries = 3last_exception = Nonefor attempt in range(max_retries):try:print(f"Attempting AI Analysis... ({attempt + 1}/{max_retries})")response_raw = run_inference(laporan, base64_images)if 'message' not in response_raw or 'content' not in response_raw['message']:raise ValueError("Empty response structure from AI")content_str = response_raw['message']['content']ai_content = json.loads(content_str)required_keys = ["title", "category", "priority", "service_code"]missing_keys = [key for key in required_keys if key not in ai_content]if missing_keys:raise ValueError(f"Missing keys in JSON: {missing_keys}")service_code = ai_content["service_code"]if service_code not in SERVICE_MAP:print(f"Warning: Service code {service_code} unknown.")priority = str(ai_content["priority"]).lower()if priority not in ['high', 'medium', 'low']:priority = 'medium'ai_content["priority"] = prioritydata = {"status": "success","data": ai_content,"meta": {"model": MODEL_NAME,'processing_time_sec': (response_raw.get("total_duration", 0)) / 1e9,"images_analyzed": len(base64_images),"attempts": attempt + 1}}print("AI Success")return dataexcept Exception as e:print(f"Attempt {attempt + 1} failed: {str(e)}")last_exception = etime.sleep(1)continuereturn JSONResponse(status_code=500,content={"status": "error", "message": f"AI Failed: {str(last_exception)}"})if __name__ == "__main__":with gr.Blocks() as demo:gr.Markdown("# LAPOR AI API Backend")gr.Markdown("This space hosts the API at `/api/analyze`.")gr.Markdown(f"**Model:** {MODEL_NAME}")app = gr.mount_gradio_app(app, demo, path="/")uvicorn.run(app, host="0.0.0.0", port=7860)8 unmodified lines91011121314151617181920213 unmodified lines25262728293031323345 unmodified lines798081828384852 unmodified lines88899091929394959697981 unmodified line1001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092108 unmodified linesfrom typing import List, Any, Dict, Unionfrom fastapi import FastAPI, UploadFile, File, Formfrom fastapi.responses import JSONResponse, Responsefrom fastapi.middleware.cors import CORSMiddlewareimport uvicornfrom PIL import Imagefrom dotenv import load_dotenvimport ollamaimport spaces # type: ignoreimport gradio as grload_dotenv()3 unmodified linesIS_PRODUCTION: str = os.getenv("IS_PRODUCTION", "false")SERVICE_MAP_STR = os.getenv("SERVICE_CODES_MAP", "{}")SERVICE_MAP = json.loads(SERVICE_MAP_STR)ALLOWED_ORIGINS = ["*"] if ALLOWED_ORIGINS_RAW == "*" else [origin.strip() for origin in ALLOWED_ORIGINS_RAW.split(",")]print(f"ALLOWED_ORIGINS: {ALLOWED_ORIGINS}")print(f"MODEL_NAME: {MODEL_NAME}")45 unmodified linesreturn None@spaces.GPU(duration=60)def run_inference(report_text: str, base64_images: List[str]) -> Dict[str, Any]:print("Starting GPU Inference...")try:2 unmodified linesprint("Model not found in GPU context, pulling again...")subprocess.run(["ollama", "pull", MODEL_NAME], check=True)response: Any = ollama.chat( # type: ignoremodel=MODEL_NAME,messages=[{'role': 'user','content': report_text,'images': base64_images if base64_images else None # type: ignore}],format='json',1 unmodified line)if isinstance(response, dict):return response # type: ignorereturn dict(response)@app.get("/")def health_check():return Response("Python Backend is running.")@app.post("/api/analyze")async def analyze( # type: ignorereport: str = Form(...),images: List[UploadFile] = File(...)):try:if not report or len(report) < 10:return JSONResponse(status_code=400,content={"status": "error", "message": "Deskripsi laporan wajib diisi minimal 10 karakter."})if not images:return JSONResponse(status_code=400,content={"status": "error", "message": "Wajib melampirkan minimal 1 foto bukti."})base64_images: List[str] = []for img_file in images:content = await img_file.read()if len(content) > 0:b64 = process_image_to_base64(content)if b64:base64_images.append(b64)if not base64_images:return JSONResponse(status_code=400,content={"status": "error", "message": "File gambar tidak valid/corrupt."})max_retries = 3last_exception = Noneprint("Report Text:", report)for attempt in range(max_retries):try:print(f"Attempting AI Analysis... ({attempt + 1}/{max_retries})")response_raw = run_inference(report, base64_images)if 'message' not in response_raw or 'content' not in response_raw['message']:raise ValueError("Empty response structure from AI")content_str = response_raw['message']['content']ai_content = json.loads(content_str)required_keys = ["title", "category", "priority", "service_code"]missing_keys = [key for key in required_keys if key not in ai_content]if missing_keys:raise ValueError(f"Missing keys in JSON: {missing_keys}")service_code = ai_content["service_code"]if service_code not in SERVICE_MAP:print(f"Warning: Service code {service_code} unknown.")priority = str(ai_content["priority"]).lower()if priority not in ['high', 'medium', 'low']:priority = 'medium'ai_content["priority"] = prioritydata = { # type: ignore"status": "success","data": ai_content,"meta": {"model": MODEL_NAME,'processing_time_sec': (response_raw.get("total_duration", 0)) / 1e9,"images_analyzed": len(base64_images),"attempts": attempt + 1}}print("AI Success")print(json.dumps(data, indent=2, ensure_ascii=True))return data # type: ignoreexcept Exception as e:print(f"Attempt {attempt + 1} failed: {str(e)}")last_exception = etime.sleep(1)continuereturn JSONResponse(status_code=500,content={"status": "error", "message": f"AI Failed: {str(last_exception)}"})except Exception as e:raise eif __name__ == "__main__":with gr.Blocks() as demo:gr.Markdown("# LAPOR AI API Backend")gr.Markdown("This space hosts the API at `/api/analyze`.")gr.Markdown(f"**Model:** {MODEL_NAME}")app = gr.mount_gradio_app(app, demo, path="/") # type: ignoreuvicorn.run(app, host="0.0.0.0", port=7860)
.env+1-1
app.py+95-95