parser-flair / app.py
WhotookNima's picture
Update app.py
8c040d4 verified
raw
history blame
2.61 kB
from fastapi import FastAPI
import json
import difflib
from flair.models import SequenceTagger
from flair.data import Sentence
app = FastAPI()
# Ladda Flair flerspråkig NER-modell
try:
tagger = SequenceTagger.load("flair/ner-multi")
except Exception as e:
print(f"Error loading model: {str(e)}")
raise e
# Ladda entiteter från entities.json
with open("entities.json") as f:
entities = json.load(f)
ITEMS = set(entities["items"])
COLORS = set(entities["colors"])
PRICES = set(entities["prices"])
def correct_spelling(word, valid_words, threshold=0.7):
"""Korrigera stavfel."""
normalized = word.rstrip("etn")
matches = difflib.get_close_matches(normalized, valid_words, n=1, cutoff=threshold)
return matches[0] if matches else word
@app.post("/parse")
async def parse_user_request(request: str):
if not request or len(request) > 200:
return {"error": "Ogiltig eller för lång begäran"}
try:
# Skapa Flair Sentence
sentence = Sentence(request)
# Prediktera NER-taggar
tagger.predict(sentence)
# Extrahera entiteter
result_entities = {}
# Kolla färger och priser i hela meningen
words = request.lower().split()
for word in words:
if word in COLORS:
result_entities["FÄRG"] = word
elif word in PRICES:
result_entities["PRIS"] = word
# Extrahera varor från NER
for entity in sentence.get_spans("ner"):
if entity.tag in ["MISC", "ORG", "LOC"]: # Diverse, organisationer, platser som potentiella objekt
corrected = correct_spelling(entity.text.lower(), ITEMS)
if corrected in ITEMS:
result_entities["VARA"] = corrected
elif not result_entities.get("VARA"):
result_entities["VARA"] = entity.text.lower()
# Om ingen vara hittades
if "VARA" not in result_entities:
return {"result": "error:ingen vara"}
# Skapa strukturerad sträng
result_parts = [f"vara:{result_entities['VARA']}"]
if "FÄRG" in result_entities:
result_parts.append(f"färg:{result_entities['FÄRG']}")
if "PRIS" in result_entities:
result_parts.append(f"pris:{result_entities['PRIS']}")
return {"result": ",".join(result_parts)}
except Exception as e:
return {"error": f"Fel vid parsning: {str(e)}"}
@app.get("/")
async def root():
return {"message": "Request Parser API is running!"}