File size: 2,018 Bytes
bea1d24
 
 
 
5b9289f
bea1d24
 
 
 
 
 
 
4a3b971
bea1d24
4a3b971
 
 
bea1d24
 
 
 
 
4a3b971
 
 
 
08cd11e
 
 
4a3b971
08cd11e
fb0b7d6
4a3b971
 
 
 
bea1d24
 
 
 
 
4a3b971
 
 
bea1d24
 
 
 
 
 
 
 
 
 
 
be272f0
4a3b971
bea1d24
4a3b971
bea1d24
 
 
4a3b971
 
 
 
 
 
 
 
 
 
 
 
 
5391c7d
4a3b971
bea1d24
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import os
from fastapi import FastAPI, Header, HTTPException, Depends
from pydantic import BaseModel
from text_humanizer import TextHumanizer, download_nltk_resources
from text_detector import AITextDetector
import spacy

API_KEY = os.environ.get("API_KEY", "dev-key")
PORT = int(os.environ.get("PORT", 7860))

app = FastAPI()
humanizer = None
detector = None

# =========================
# Request / Response Models
# =========================
class HumanizeReq(BaseModel):
    text: str
    use_passive: bool = False
    use_synonyms: bool = False

class DetectReq(BaseModel):
    text: str

class DetectResp(BaseModel):
    summary: str
    overall_ai_probability: float
    category_distribution: dict
    metrics: dict
    interpretation: str
    label: str

# =========================
# API Key verification
# =========================
def verify_key(x_api_key: str = Header(None)):
    if x_api_key != API_KEY:
        raise HTTPException(status_code=403, detail="Forbidden")
    return True

# =========================
# Routes
# =========================
@app.get("/")
def greet_json():
    return {"Hello": "World!"}

@app.on_event("startup")
def startup():
    download_nltk_resources()
    try:
        spacy.load("en_core_web_sm")
    except OSError:
        spacy.cli.download("en_core_web_sm")

    global humanizer, detector
    humanizer = TextHumanizer()
    detector = AITextDetector()   # <-- init detector here

@app.post("/humanize")
def humanize(req: HumanizeReq, _=Depends(verify_key)):
    return {
        "humanized": humanizer.humanize_text(
            req.text,
            req.use_passive,
            req.use_synonyms
        )
    }

@app.post("/detect", response_model=DetectResp)
def detect(req: DetectReq, _=Depends(verify_key)):
    """
    Detect whether the text is AI-generated or human-written.
    """
    report = detector.detect(req.text)
    return DetectResp(**report)

# if __name__ == "__main__":
#     import uvicorn
#     uvicorn.run(app, host="0.0.0.0", port=PORT)