File size: 8,355 Bytes
9e68d94
 
 
 
ac5bc5b
9e68d94
 
 
 
 
 
cc603f5
 
9e68d94
cc603f5
 
 
ac5bc5b
 
cc603f5
ac5bc5b
 
9e68d94
ac5bc5b
 
9e68d94
ac5bc5b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e68d94
ac5bc5b
 
 
 
 
 
 
9e68d94
ac5bc5b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cf3ea01
ac5bc5b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e68d94
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac5bc5b
9e68d94
6158df3
9e68d94
6158df3
9e68d94
6158df3
 
9e68d94
 
 
6158df3
ac5bc5b
9e68d94
ac5bc5b
 
 
 
9e68d94
 
ac5bc5b
9e68d94
 
 
 
ac5bc5b
cf3ea01
ac5bc5b
 
 
 
 
 
 
 
 
9e68d94
ac5bc5b
9e68d94
cf3ea01
9e68d94
 
 
 
e9ebae6
 
 
ac5bc5b
 
e9ebae6
ac5bc5b
9e68d94
6158df3
e9ebae6
6158df3
9e68d94
 
ac5bc5b
 
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
import gradio as gr
from transformers import (
    AutoTokenizer, AutoModelForTokenClassification,
    AutoModelForSequenceClassification,
    pipeline
)
import torch

device = "cuda" if torch.cuda.is_available() else "cpu"

# === Tokenizery i modele ABSA ===
aspect_tokenizer = AutoTokenizer.from_pretrained("EfektMotyla/bert-aspect-ner")
aspect_model = AutoModelForTokenClassification.from_pretrained("EfektMotyla/bert-aspect-ner").to(device)

sentiment_tokenizer = AutoTokenizer.from_pretrained("EfektMotyla/absa-roberta")
sentiment_model = AutoModelForSequenceClassification.from_pretrained("EfektMotyla/absa-roberta").to(device)

pl_to_en_translator = pipeline("translation", model="Helsinki-NLP/opus-mt-pl-en", device=0 if torch.cuda.is_available() else -1)
en_to_pl_translator = pipeline("translation", model="gsarti/opus-mt-tc-en-pl", device=0 if torch.cuda.is_available() else -1)

def translate_pl_to_en(texts):
    return [res["translation_text"] for res in pl_to_en_translator(texts)]

def translate_en_to_pl(texts):
    return [res["translation_text"] for res in en_to_pl_translator(texts)]

# === Słownik znanych aspektów (EN → PL) ===
aspect_aliases = {
    # JEDZENIE / SMAK
    "food": "jedzenie",
    "meal": "jedzenie",
    "taste": "smak",
    "flavor": "smak",
    "dish": "danie",
    "portion": "porcja",
    "serving": "porcja",
    "ingredients": "składniki",
    "spices": "przyprawy",
    "salt": "sól",
    "fat": "tłuszcz",
    "grease": "tłuszcz",

    # OBSŁUGA
    "service": "obsługa",
    "staff": "obsługa",
    "waiter": "obsługa",
    "waitress": "obsługa",
    "manager": "obsługa",
    "attitude": "obsługa",

    # CENY / WARTOŚĆ
    "price": "cena",
    "value": "cena",
    "cost": "cena",

    # ATMOSFERA / WYSTRÓJ
    "decor": "wystrój",
    "interior": "wystrój",
    "design": "wystrój",
    "counter": "wystrój",
    "fridge": "wystrój",
    "music": "muzyka",
    "ambience": "klimat",
    "atmosphere": "klimat",
    "vibe": "klimat",
    "climate": "klimat",

    # MIEJSCE
    "location": "lokalizacja",
    "place": "lokalizacja",
    "entrance": "lokalizacja",
    "parking": "parking",
    "toilet": "toaleta",

    # CZAS / SZYBKOŚĆ
    "waiting time": "czas oczekiwania",
    "time": "czas oczekiwania",
    "delay": "opóźnienie",
    "speed": "czas oczekiwania",
    "service time": "czas oczekiwania",
    "slow": "czas oczekiwania",
    "fast": "czas oczekiwania",
    "immediate": "czas oczekiwania",
    "late": "opóźnienie",


    # ZAPACH / CZYSTOŚĆ
    "smell": "zapach",
    "odor": "zapach",
    "cleanliness": "czystość",
    "hygiene": "czystość",

    # OGÓLNE
    "experience": "doświadczenie",
    "visit": "wizyta",
    "menu": "menu",
    "variety": "menu",

    # MIEJSCE / LOKALIZACJA / OTOCZENIE
    "location": "lokalizacja",
    "place": "lokalizacja",
    "entrance": "lokalizacja",
    "parking": "parking",
    "view": "lokalizacja",
    "lake": "lokalizacja",
    "window": "lokalizacja",
    "terrace": "lokalizacja",
    "balcony": "lokalizacja",
    "outside": "lokalizacja",
    "area": "lokalizacja",
    "surroundings": "lokalizacja",
    "neighborhood": "lokalizacja",
    "river": "lokalizacja",
    "garden": "lokalizacja",

    # NAPOJE
    "drink": "napoje",
    "drinks": "napoje",
    "beverage": "napoje",
    "coffee": "napoje",
    "tea": "napoje",
    "water": "napoje",
    "juice": "napoje",
    "alcohol": "napoje",
    "cocktail": "napoje",
    "wine": "napoje",

    #HIGIENA
    "dirt": "czystość",
    "dirty": "czystość",
    "mess": "czystość",
    "messy": "czystość",
    "clean": "czystość",
    "filth": "czystość",

    #KUCHNIA /JAKOŚĆ 
    "chef": "kuchnia",
    "kitchen": "kuchnia",
    "preparation": "kuchnia",
    "presentation": "prezentacja",
    "quality": "jakość",
    "freshness": "jakość",
    "raw": "jakość",
    "undercooked": "jakość",
    "burnt": "jakość",
    "microwaved": "jakość",
    # Wyposażenie 
    "seat": "komfort",
    "seating": "komfort",
    "chair": "komfort",
    "table": "komfort",
    "furniture": "komfort",
    "light": "komfort",
    "noise": "komfort",
    "temperature": "komfort",
    "air conditioning": "komfort",

    # OGÓLNE WRAŻENIE / WARTOŚĆ
    "recommendation": "ogólna ocena",
    "return": "ogólna ocena",
    "again": "ogólna ocena",
    "worth": "cena",
    "overpriced": "cena",
    "cheap": "cena",
    "affordable": "cena",

    # DZIECI / RODZINA
    "child": "dzieci",
    "children": "dzieci",
    "kid": "dzieci",
    "kids": "dzieci",
    "child-friendly": "dzieci",
    "kids menu": "dzieci",
    "high chair": "dzieci",
    "stroller": "dzieci",
    "family": "rodzina",
    "families": "rodzina",
    "parent": "rodzina",
    "parents": "rodzina",
    "group": "rodzina",
    "big group": "rodzina",
    "baby": "dzieci",

    # ZWIERZĘTA
    "dog": "zwierzęta",
    "dogs": "zwierzęta",
    "pet": "zwierzęta",
    "pets": "zwierzęta",
    "pet-friendly": "zwierzęta",
    "dog-friendly": "zwierzęta",
    "animal": "zwierzęta",
}

def extract_aspects(text):
    inputs = aspect_tokenizer(text, return_tensors="pt", truncation=True, padding=True).to(device)
    with torch.no_grad():
        outputs = aspect_model(**inputs)
    preds = torch.argmax(outputs.logits, dim=2)[0].cpu().numpy()
    tokens = aspect_tokenizer.convert_ids_to_tokens(inputs["input_ids"][0])
    labels = [aspect_model.config.id2label[p] for p in preds]

    aspects = []
    current_tokens = []
    for token, label in zip(tokens, labels):
        if label == "B-ASP":
            if current_tokens:
                aspects.append(aspect_tokenizer.convert_tokens_to_string(current_tokens).strip())
                current_tokens = []
            current_tokens = [token]
        elif label == "I-ASP" and current_tokens:
            current_tokens.append(token)
        else:
            if current_tokens:
                aspects.append(aspect_tokenizer.convert_tokens_to_string(current_tokens).strip())
                current_tokens = []
    if current_tokens:
        aspects.append(aspect_tokenizer.convert_tokens_to_string(current_tokens).strip())
    return list(set(aspects))  # usuń duplikaty

def analyze(text_pl, progress=gr.Progress()):
    try:
        progress(0, desc="Tłumaczenie na angielski...")
        text_en = translate_pl_to_en([text_pl])[0]

        progress(0.3, desc="Wykrywanie aspektów...")
        aspects_en = extract_aspects(text_en)
        if not aspects_en:
            return "Nie wykryto żadnych aspektów."

        unique_aspects = sorted(set([asp.lower() for asp in aspects_en]))
        results = []
        seen_pl_aspects = set()

        for i, asp in enumerate(unique_aspects):
            progress(0.4 + i/len(unique_aspects)*0.6, desc=f"Analiza aspektu: {asp}")
            input_text = f"{text_en} [SEP] {asp}"
            inputs = sentiment_tokenizer(input_text, return_tensors="pt", truncation=True, padding=True).to(device)

            with torch.no_grad():
                logits = sentiment_model(**inputs).logits
                predicted_class_id = int(logits.argmax().cpu())
                sentiment_label = {0: "negatywny", 1: "neutralny", 2: "pozytywny", 3: "konfliktowy"}[predicted_class_id]

            # Tłumaczenie aspektu przez słownik lub model
            if asp in aspect_aliases:
                asp_pl = aspect_aliases[asp]
            else:
                asp_pl = translate_en_to_pl([asp])[0].lower()

            if asp_pl not in seen_pl_aspects:
                seen_pl_aspects.add(asp_pl)
                results.append(f"{asp_pl.capitalize()} → **{sentiment_label}**")

        return "\n".join(results)

    except Exception as e:
        return f"Błąd podczas analizy: {e}"

# === Gradio UI ===
demo = gr.Interface(
    fn=analyze,
    inputs=gr.Textbox(
        label="Komentarz po polsku",
        placeholder="Np. Pizza była pyszna, ale kelner był nieuprzejmy.",
        lines=4,
        max_lines=6
    ),
    outputs=gr.Markdown(label="Wyniki analizy"),
    title="ABSA – Analiza komentarzy restauracyjnych",
    description="Wykrywa aspekty i przypisuje im sentymenty (pozytywny / negatywny / neutralny / konfliktowy).",
    theme="default",
    allow_flagging="never"
)

if __name__ == "__main__":
    demo.launch()