48 lines
1.2 KiB
Python
48 lines
1.2 KiB
Python
from fastapi import FastAPI, HTTPException
|
|
from pydantic import BaseModel
|
|
from typing import List, Optional
|
|
from rapidfuzz import fuzz
|
|
|
|
app = FastAPI()
|
|
|
|
|
|
# Request body schema
|
|
class MatchRequest(BaseModel):
|
|
title: str
|
|
options: List[str]
|
|
threshold: Optional[int] = 85 # default match threshold
|
|
|
|
|
|
# Response schema
|
|
class MatchResponse(BaseModel):
|
|
match_found: bool
|
|
best_match: Optional[str] = None
|
|
similarity: Optional[float] = None
|
|
|
|
|
|
@app.post("/match-title", response_model=MatchResponse)
|
|
def match_title(request: MatchRequest):
|
|
title = request.title
|
|
options = request.options
|
|
threshold = request.threshold
|
|
|
|
print(title)
|
|
print(options)
|
|
|
|
if not title or not options:
|
|
raise HTTPException(status_code=400, detail="Title and options are required.")
|
|
|
|
best_match = None
|
|
best_score = 0
|
|
|
|
for option in options:
|
|
score = fuzz.ratio(title, option)
|
|
if score > best_score:
|
|
best_score = score
|
|
best_match = option
|
|
|
|
if best_score >= threshold:
|
|
return MatchResponse(match_found=True, best_match=best_match, similarity=best_score)
|
|
else:
|
|
return MatchResponse(match_found=False)
|