Spaces:
Sleeping
Sleeping
Download app/main.py from jonathanjordan21/Test-ticketing: direct link, hf CLI and curl.
- Browser
- Download file 5.37 kB
-
https://huggingface.co/spaces/jonathanjordan21/Test-ticketing/resolve/main/app/main.py
- Command line
-
hf download hf://spaces/jonathanjordan21/Test-ticketing/app/main.py
-
curl -L -o main.py https://huggingface.co/spaces/jonathanjordan21/Test-ticketing/resolve/main/app/main.py
5.37 kB
| import os | |
| import time | |
| import numpy as np | |
| from contextlib import asynccontextmanager | |
| from fastapi import FastAPI, HTTPException, Header | |
| from fastapi.concurrency import run_in_threadpool | |
| from app.models import models | |
| from app.schemas import ( | |
| AnalysisRequest, | |
| EmbeddingRequest, | |
| SarcasmRequest, | |
| AbsaRequest | |
| ) | |
| API_KEY = os.getenv("API_KEY", "") | |
| def verify_api_key(key: str | None): | |
| if API_KEY and key != API_KEY: | |
| raise HTTPException( | |
| status_code=401, | |
| detail="Invalid API key" | |
| ) | |
| def classify(pipe, text): | |
| result = pipe(text)[0] | |
| return { | |
| "label": result["label"], | |
| "confidence": round(float(result["score"]), 6) | |
| } | |
| def detect_absa(request: AbsaRequest): | |
| absa_model = models.absa() | |
| start = time.perf_counter() | |
| # Format input untuk ABSA: [sentence] [SEP] [aspect] | |
| text_input = f"{request.text} [SEP] {request.aspect}" | |
| # Prediksi sentimen | |
| pred = absa_model(text_input) | |
| return { | |
| "absa":pred, | |
| "metadata": { | |
| "pipeline": ["absa"], | |
| "inference_time_ms": round( | |
| (time.perf_counter() - start) * 1000, | |
| 2 | |
| ) | |
| }, | |
| } | |
| def detect_sarcasm_text(request: SarcasmRequest): | |
| # # PHASE 3: Sarcasm Detection | |
| sarcasm_model = models.sarcasm() | |
| text = request.text | |
| start = time.perf_counter() | |
| sarcasm = classify( | |
| sarcasm_model, | |
| text | |
| ) | |
| return { | |
| # "entities": entities, | |
| # "sentiment": sentiment, | |
| "sarcasm": { | |
| **sarcasm, | |
| # "is_sarcastic": ( | |
| # "sarcas" in sarcasm["label"].lower() | |
| # or sarcasm["label"] == "LABEL_1" or sarcasm["label"] == "1" | |
| # ) | |
| }, | |
| "metadata": { | |
| "pipeline": [ | |
| # "dynamic_ner", | |
| # "sentiment", | |
| "sarcasm" | |
| ], | |
| "inference_time_ms": round( | |
| (time.perf_counter() - start) * 1000, | |
| 2 | |
| ) | |
| } | |
| } | |
| def analyze_text(request: AnalysisRequest): | |
| text = request.text | |
| start = time.perf_counter() | |
| # PHASE 1: Dynamic NER | |
| ner_model = models.ner() | |
| entities = ner_model.predict_entities( | |
| text, | |
| request.entity_labels, | |
| threshold=request.entity_threshold | |
| ) | |
| # PHASE 2: Sentiment Analysis | |
| sentiment_model = models.sentiment() | |
| sentiment = classify( | |
| sentiment_model, | |
| text | |
| ) | |
| # # PHASE 3: Sarcasm Detection | |
| # sarcasm_model = models.sarcasm() | |
| # sarcasm = classify( | |
| # sarcasm_model, | |
| # text | |
| # ) | |
| return { | |
| "entities": entities, | |
| "sentiment": sentiment, | |
| # "sarcasm": { | |
| # **sarcasm, | |
| # "is_sarcastic": ( | |
| # "sarcas" in sarcasm["label"].lower() | |
| # or sarcasm["label"] == "LABEL_1" | |
| # ) | |
| # }, | |
| "metadata": { | |
| "pipeline": [ | |
| "dynamic_ner", | |
| "sentiment", | |
| # "sarcasm" | |
| ], | |
| "inference_time_ms": round( | |
| (time.perf_counter() - start) * 1000, | |
| 2 | |
| ) | |
| } | |
| } | |
| async def lifespan(app: FastAPI): | |
| yield | |
| app = FastAPI( | |
| title="NLP Inference Service", | |
| version="1.0.0", | |
| lifespan=lifespan | |
| ) | |
| async def health(): | |
| return { | |
| "status": "healthy", | |
| "loaded_models": list(models._models.keys()) | |
| } | |
| async def analyze( | |
| request: AnalysisRequest, | |
| x_api_key: str | None = Header(default=None) | |
| ): | |
| verify_api_key(x_api_key) | |
| try: | |
| return await run_in_threadpool( | |
| analyze_text, | |
| request | |
| ) | |
| except HTTPException: | |
| raise | |
| except Exception as exc: | |
| raise HTTPException( | |
| status_code=500, | |
| detail=str(exc) | |
| ) | |
| async def detect_sarcasm( | |
| request: SarcasmRequest, | |
| x_api_key: str | None = Header(default=None) | |
| ): | |
| verify_api_key(x_api_key) | |
| try: | |
| return await run_in_threadpool( | |
| detect_sarcasm_text, | |
| request | |
| ) | |
| except HTTPException: | |
| raise | |
| except Exception as exc: | |
| raise HTTPException( | |
| status_code=500, | |
| detail=str(exc) | |
| ) | |
| async def absa( | |
| request: AbsaRequest, | |
| x_api_key: str | None = Header(default=None) | |
| ): | |
| verify_api_key(x_api_key) | |
| try: | |
| return await run_in_threadpool( | |
| detect_absa, | |
| request | |
| ) | |
| except HTTPException: | |
| raise | |
| except Exception as exc: | |
| raise HTTPException( | |
| status_code=500, | |
| detail=str(exc) | |
| ) | |
| from app.embedding import generate_embeddings | |
| async def embeddings( | |
| request: EmbeddingRequest, | |
| x_api_key: str | None = Header(default=None) | |
| ): | |
| verify_api_key(x_api_key) | |
| try: | |
| return await run_in_threadpool( | |
| generate_embeddings, | |
| request | |
| ) | |
| except HTTPException: | |
| raise | |
| except Exception as exc: | |
| raise HTTPException( | |
| status_code=500, | |
| detail=str(exc) | |
| ) | |