Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI, Request
|
| 2 |
+
from pydantic import BaseModel
|
| 3 |
+
from typing import List
|
| 4 |
+
from transformers import (
|
| 5 |
+
AutoTokenizer, AutoModelForTokenClassification,
|
| 6 |
+
AutoModelForSequenceClassification, pipeline
|
| 7 |
+
)
|
| 8 |
+
import torch
|
| 9 |
+
|
| 10 |
+
app = FastAPI()
|
| 11 |
+
|
| 12 |
+
# === 艁adowanie modeli ===
|
| 13 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 14 |
+
|
| 15 |
+
aspect_tokenizer = AutoTokenizer.from_pretrained("EfektMotyla/bert-aspect-ner")
|
| 16 |
+
aspect_model = AutoModelForTokenClassification.from_pretrained("EfektMotyla/bert-aspect-ner").to(device)
|
| 17 |
+
|
| 18 |
+
sentiment_tokenizer = AutoTokenizer.from_pretrained("EfektMotyla/absa-roberta")
|
| 19 |
+
sentiment_model = AutoModelForSequenceClassification.from_pretrained("EfektMotyla/absa-roberta").to(device)
|
| 20 |
+
|
| 21 |
+
pl_to_en = pipeline("translation", model="Helsinki-NLP/opus-mt-pl-en", device=0 if device == "cuda" else -1)
|
| 22 |
+
en_to_pl = pipeline("translation", model="gsarti/opus-mt-tc-en-pl", device=0 if device == "cuda" else -1)
|
| 23 |
+
|
| 24 |
+
# === Dane wej艣ciowe i wyj艣ciowe ===
|
| 25 |
+
class Comment(BaseModel):
|
| 26 |
+
text: str
|
| 27 |
+
|
| 28 |
+
class AspectSentiment(BaseModel):
|
| 29 |
+
aspect: str
|
| 30 |
+
sentiment: str
|
| 31 |
+
|
| 32 |
+
class AnalysisResult(BaseModel):
|
| 33 |
+
results: List[AspectSentiment]
|
| 34 |
+
|
| 35 |
+
# === S艂ownik alias贸w aspekt贸w EN鈫扨L (taki sam jak wcze艣niej) ===
|
| 36 |
+
aspect_aliases = {
|
| 37 |
+
"food": "jedzenie", "service": "obs艂uga", "price": "cena",
|
| 38 |
+
"taste": "smak", "waiter": "obs艂uga", "dish": "danie",
|
| 39 |
+
"portion": "porcja", "staff": "obs艂uga", "decor": "wystr贸j",
|
| 40 |
+
"menu": "menu", "drink": "napoje", "location": "lokalizacja",
|
| 41 |
+
"time": "czas oczekiwania", "cleanliness": "czysto艣膰", "smell": "zapach",
|
| 42 |
+
"value": "cena", "experience": "do艣wiadczenie", "recommendation": "og贸lna ocena",
|
| 43 |
+
"children": "dzieci", "family": "rodzina", "pet": "zwierz臋ta"
|
| 44 |
+
# dodaj wi臋cej jak chcesz
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
# === Funkcje pomocnicze ===
|
| 48 |
+
def translate_pl_to_en(texts):
|
| 49 |
+
return [res["translation_text"] for res in pl_to_en(texts)]
|
| 50 |
+
|
| 51 |
+
def translate_en_to_pl(texts):
|
| 52 |
+
return [res["translation_text"] for res in en_to_pl(texts)]
|
| 53 |
+
|
| 54 |
+
def extract_aspects(text_en):
|
| 55 |
+
inputs = aspect_tokenizer(text_en, return_tensors="pt", truncation=True, padding=True).to(device)
|
| 56 |
+
with torch.no_grad():
|
| 57 |
+
outputs = aspect_model(**inputs)
|
| 58 |
+
preds = torch.argmax(outputs.logits, dim=2)[0].cpu().numpy()
|
| 59 |
+
tokens = aspect_tokenizer.convert_ids_to_tokens(inputs["input_ids"][0])
|
| 60 |
+
labels = [aspect_model.config.id2label[p] for p in preds]
|
| 61 |
+
|
| 62 |
+
aspects = []
|
| 63 |
+
current_tokens = []
|
| 64 |
+
for token, label in zip(tokens, labels):
|
| 65 |
+
if label == "B-ASP":
|
| 66 |
+
if current_tokens:
|
| 67 |
+
aspects.append(aspect_tokenizer.convert_tokens_to_string(current_tokens).strip())
|
| 68 |
+
current_tokens = [token]
|
| 69 |
+
elif label == "I-ASP" and current_tokens:
|
| 70 |
+
current_tokens.append(token)
|
| 71 |
+
else:
|
| 72 |
+
if current_tokens:
|
| 73 |
+
aspects.append(aspect_tokenizer.convert_tokens_to_string(current_tokens).strip())
|
| 74 |
+
current_tokens = []
|
| 75 |
+
if current_tokens:
|
| 76 |
+
aspects.append(aspect_tokenizer.convert_tokens_to_string(current_tokens).strip())
|
| 77 |
+
|
| 78 |
+
return list(set([a.lower() for a in aspects]))
|
| 79 |
+
|
| 80 |
+
# === G艂贸wna funkcja API ===
|
| 81 |
+
@app.post("/analyze", response_model=AnalysisResult)
|
| 82 |
+
def analyze_comment(comment: Comment):
|
| 83 |
+
text_pl = comment.text
|
| 84 |
+
text_en = translate_pl_to_en([text_pl])[0]
|
| 85 |
+
aspects = extract_aspects(text_en)
|
| 86 |
+
|
| 87 |
+
result = []
|
| 88 |
+
for asp in aspects:
|
| 89 |
+
input_text = f"{text_en} [SEP] {asp}"
|
| 90 |
+
inputs = sentiment_tokenizer(input_text, return_tensors="pt", truncation=True, padding=True).to(device)
|
| 91 |
+
with torch.no_grad():
|
| 92 |
+
logits = sentiment_model(**inputs).logits
|
| 93 |
+
predicted_class_id = int(logits.argmax().cpu())
|
| 94 |
+
sentiment_label = {0: "negatywny", 1: "neutralny", 2: "pozytywny", 3: "konfliktowy"}[predicted_class_id]
|
| 95 |
+
|
| 96 |
+
asp_pl = aspect_aliases.get(asp, translate_en_to_pl([asp])[0].lower())
|
| 97 |
+
result.append(AspectSentiment(aspect=asp_pl, sentiment=sentiment_label))
|
| 98 |
+
|
| 99 |
+
return {"results": result}
|