|
|
from fastapi import FastAPI |
|
|
from pydantic import BaseModel |
|
|
import uvicorn |
|
|
from translator import translate |
|
|
|
|
|
app = FastAPI( |
|
|
title="Chatbot & Translator API", |
|
|
description="API untuk chatbot dan translator Indonesia-English", |
|
|
version="1.0.0" |
|
|
) |
|
|
|
|
|
|
|
|
class ChatRequest(BaseModel): |
|
|
message: str |
|
|
history: list[dict] = [] |
|
|
system_message: str = "You are a friendly chatbot." |
|
|
max_tokens: int = 512 |
|
|
temperature: float = 0.7 |
|
|
top_p: float = 0.95 |
|
|
|
|
|
class ChatResponse(BaseModel): |
|
|
response: str |
|
|
status: str = "success" |
|
|
|
|
|
class TranslateRequest(BaseModel): |
|
|
text: str |
|
|
direction: str |
|
|
|
|
|
class TranslateResponse(BaseModel): |
|
|
translation: str |
|
|
original_text: str |
|
|
direction: str |
|
|
status: str = "success" |
|
|
|
|
|
|
|
|
@app.get("/") |
|
|
def root(): |
|
|
return { |
|
|
"message": "Chatbot & Translator API", |
|
|
"endpoints": ["/chat", "/translate"], |
|
|
"docs": "/docs" |
|
|
} |
|
|
|
|
|
|
|
|
@app.post("/chat", response_model=ChatResponse) |
|
|
def chat_endpoint(req: ChatRequest): |
|
|
try: |
|
|
|
|
|
|
|
|
response_text = f"Simulasi jawaban untuk: {req.message}" |
|
|
|
|
|
return ChatResponse( |
|
|
response=response_text, |
|
|
status="success" |
|
|
) |
|
|
except Exception as e: |
|
|
return ChatResponse( |
|
|
response=f"Error: {str(e)}", |
|
|
status="error" |
|
|
) |
|
|
|
|
|
|
|
|
@app.post("/translate", response_model=TranslateResponse) |
|
|
def translate_endpoint(req: TranslateRequest): |
|
|
try: |
|
|
result = translate(req.text, req.direction) |
|
|
|
|
|
return TranslateResponse( |
|
|
translation=result, |
|
|
original_text=req.text, |
|
|
direction=req.direction, |
|
|
status="success" |
|
|
) |
|
|
except Exception as e: |
|
|
return TranslateResponse( |
|
|
translation="Translation failed", |
|
|
original_text=req.text, |
|
|
direction=req.direction, |
|
|
status="error" |
|
|
) |
|
|
|
|
|
|
|
|
@app.get("/health") |
|
|
def health_check(): |
|
|
return {"status": "healthy", "message": "API is running"} |
|
|
|
|
|
|
|
|
if __name__ == "__main__": |
|
|
uvicorn.run(app, host="0.0.0.0", port=7860) |