WhotookNima commited on
Commit
d5e9814
·
verified ·
1 Parent(s): b28b3cc

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +72 -0
app.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI
2
+ import json
3
+ import difflib
4
+ from flair.models import SequenceTagger
5
+ from flair.data import Sentence
6
+
7
+ app = FastAPI()
8
+
9
+ # Ladda Flair NER-modell för svenska
10
+ tagger = SequenceTagger.load("flair/ner-swedish")
11
+
12
+ # Ladda entiteter från entities.json
13
+ with open("entities.json") as f:
14
+ entities = json.load(f)
15
+ ITEMS = set(entities["items"])
16
+ COLORS = set(entities["colors"])
17
+ PRICES = set(entities["prices"])
18
+
19
+ def correct_spelling(word, valid_words, threshold=0.7):
20
+ """Korrigera stavfel."""
21
+ normalized = word.rstrip("etn")
22
+ matches = difflib.get_close_matches(normalized, valid_words, n=1, cutoff=threshold)
23
+ return matches[0] if matches else word
24
+
25
+ @app.post("/parse")
26
+ async def parse_user_request(request: str):
27
+ if not request or len(request) > 200:
28
+ return {"error": "Ogiltig eller för lång begäran"}
29
+ try:
30
+ # Skapa Flair Sentence
31
+ sentence = Sentence(request)
32
+
33
+ # Prediktera NER-taggar
34
+ tagger.predict(sentence)
35
+
36
+ # Extrahera entiteter
37
+ result_entities = {}
38
+ # Först, kolla färger och priser i hela meningen
39
+ words = request.lower().split()
40
+ for word in words:
41
+ if word in COLORS:
42
+ result_entities["FÄRG"] = word
43
+ elif word in PRICES:
44
+ result_entities["PRIS"] = word
45
+
46
+ # Extrahera varor från NER
47
+ for entity in sentence.get_spans("ner"):
48
+ if entity.tag in ["OBJ", "MISC", "PER"]: # Objekt, diverse, eller potentiella produkter
49
+ corrected = correct_spelling(entity.text.lower(), ITEMS)
50
+ if corrected in ITEMS:
51
+ result_entities["VARA"] = corrected
52
+ elif not result_entities.get("VARA"): # Fallback om ingen match i ITEMS
53
+ result_entities["VARA"] = entity.text.lower()
54
+
55
+ # Om ingen vara hittades
56
+ if "VARA" not in result_entities:
57
+ return {"result": "error:ingen vara"}
58
+
59
+ # Skapa strukturerad sträng
60
+ result_parts = [f"vara:{result_entities['VARA']}"]
61
+ if "FÄRG" in result_entities:
62
+ result_parts.append(f"färg:{result_entities['FÄRG']}")
63
+ if "PRIS" in result_entities:
64
+ result_parts.append(f"pris:{result_entities['PRIS']}")
65
+
66
+ return {"result": ",".join(result_parts)}
67
+ except Exception as e:
68
+ return {"error": f"Fel vid parsning: {str(e)}"}
69
+
70
+ @app.get("/")
71
+ async def root():
72
+ return {"message": "Request Parser API is running!"}