File size: 2,136 Bytes
308056c
8e675fe
 
c48963c
308056c
 
 
8e675fe
 
 
c48963c
8e675fe
 
 
 
 
 
c48963c
 
 
 
308056c
 
d239f50
 
 
308056c
8e675fe
 
449b6a7
c48963c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8e675fe
 
449b6a7
8e675fe
 
 
 
 
 
449b6a7
8e675fe
308056c
 
 
 
 
8e675fe
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
from fastapi import FastAPI
import spacy
import json
import difflib

app = FastAPI()

# Ladda svensk spaCy-modell
nlp = spacy.load("sv_core_news_sm")

# 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.8):
    """Korrigera stavfel genom att hitta närmaste match i valid_words."""
    matches = difflib.get_close_matches(word, 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:
        # Analysera text med spaCy
        doc = nlp(request)
        
        # Extrahera entiteter
        entities = {}
        for token in doc:
            text = token.text.lower()
            # Prioritera definierade varor med stavfelskorrigering
            corrected_text = correct_spelling(text, ITEMS)
            if corrected_text in ITEMS:
                entities["VARA"] = corrected_text
            elif token.pos_ == "NOUN" and not entities.get("VARA"):
                entities["VARA"] = corrected_text
            # Identifiera färger och priser
            elif text in COLORS:
                entities["FÄRG"] = text
            elif text in PRICES:
                entities["PRIS"] = text
        
        # Om ingen vara hittades
        if "VARA" not in entities:
            return {"result": "error:ingen vara"}
        
        # Skapa strukturerad sträng
        result_parts = [f"vara:{entities['VARA']}"]
        if "FÄRG" in entities:
            result_parts.append(f"färg:{entities['FÄRG']}")
        if "PRIS" in entities:
            result_parts.append(f"pris:{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!"}