Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -20,575 +20,533 @@ import gc
|
|
| 20 |
import pandas as pd
|
| 21 |
from lime.lime_text import LimeTextExplainer
|
| 22 |
import shap
|
|
|
|
| 23 |
|
| 24 |
@dataclass
|
| 25 |
-
class
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
THEMES = {
|
| 39 |
'default': {'pos': '#4ecdc4', 'neg': '#ff6b6b'},
|
| 40 |
'ocean': {'pos': '#0077be', 'neg': '#ff6b35'},
|
| 41 |
'forest': {'pos': '#228b22', 'neg': '#dc143c'},
|
| 42 |
'sunset': {'pos': '#ff8c00', 'neg': '#8b0000'}
|
| 43 |
}
|
| 44 |
|
| 45 |
-
|
| 46 |
'the', 'a', 'an', 'and', 'or', 'but', 'in', 'on', 'at', 'to',
|
| 47 |
'for', 'of', 'with', 'by', 'is', 'are', 'was', 'were', 'be',
|
| 48 |
'been', 'have', 'has', 'had', 'will', 'would', 'could', 'should'
|
| 49 |
}
|
| 50 |
|
| 51 |
-
|
| 52 |
-
|
| 53 |
|
| 54 |
-
|
| 55 |
-
def
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
@wraps(func)
|
| 59 |
-
def wrapper(*args, **kwargs):
|
| 60 |
try:
|
| 61 |
-
return
|
| 62 |
except Exception as e:
|
| 63 |
-
|
| 64 |
-
return
|
| 65 |
-
return
|
| 66 |
-
return
|
| 67 |
|
| 68 |
@contextmanager
|
| 69 |
-
def
|
| 70 |
-
|
| 71 |
-
fig = plt.figure(*args, **kwargs)
|
| 72 |
try:
|
| 73 |
-
yield
|
| 74 |
finally:
|
| 75 |
-
plt.close(
|
| 76 |
gc.collect()
|
| 77 |
|
| 78 |
-
class
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
self.
|
| 82 |
-
self.colors = config.THEMES.get(theme, config.THEMES['default'])
|
| 83 |
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
_tokenizer = None
|
| 90 |
-
_device = None
|
| 91 |
|
| 92 |
def __new__(cls):
|
| 93 |
-
if cls.
|
| 94 |
-
cls.
|
| 95 |
-
return cls.
|
| 96 |
|
| 97 |
@property
|
| 98 |
-
def
|
| 99 |
-
if self.
|
| 100 |
-
self.
|
| 101 |
-
return self.
|
| 102 |
|
| 103 |
@property
|
| 104 |
-
def
|
| 105 |
-
if self.
|
| 106 |
-
self.
|
| 107 |
-
return self.
|
| 108 |
|
| 109 |
@property
|
| 110 |
-
def
|
| 111 |
-
if self.
|
| 112 |
-
self.
|
| 113 |
-
return self.
|
| 114 |
|
| 115 |
-
def
|
| 116 |
-
"""Load model and tokenizer"""
|
| 117 |
try:
|
| 118 |
-
self.
|
| 119 |
-
|
| 120 |
-
self.
|
| 121 |
-
self.
|
| 122 |
-
|
|
|
|
| 123 |
except Exception as e:
|
| 124 |
-
|
| 125 |
raise
|
| 126 |
|
| 127 |
-
|
| 128 |
-
class TextProcessor:
|
| 129 |
-
"""Optimized text processing"""
|
| 130 |
@staticmethod
|
| 131 |
-
@lru_cache(maxsize=
|
| 132 |
-
def
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
return tuple(w for w in words if w not in config.STOP_WORDS)
|
| 136 |
|
| 137 |
-
class
|
| 138 |
-
"""Simplified history management"""
|
| 139 |
def __init__(self):
|
| 140 |
-
self.
|
| 141 |
|
| 142 |
-
def
|
| 143 |
-
self.
|
| 144 |
-
if len(self.
|
| 145 |
-
self.
|
| 146 |
|
| 147 |
-
def
|
| 148 |
-
return self.
|
| 149 |
|
| 150 |
-
def
|
| 151 |
-
|
| 152 |
-
self.
|
| 153 |
-
return
|
| 154 |
|
| 155 |
-
def
|
| 156 |
-
return len(self.
|
| 157 |
|
| 158 |
-
|
| 159 |
-
class SentimentEngine:
|
| 160 |
-
"""Streamlined sentiment analysis engine with LIME and SHAP"""
|
| 161 |
def __init__(self):
|
| 162 |
-
self.
|
| 163 |
-
self.
|
| 164 |
-
self.
|
| 165 |
|
| 166 |
-
def
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
texts = [texts]
|
| 170 |
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
truncation=True, max_length=
|
| 174 |
-
).to(self.
|
| 175 |
|
| 176 |
with torch.no_grad():
|
| 177 |
-
|
| 178 |
-
|
| 179 |
|
| 180 |
-
return
|
| 181 |
|
| 182 |
-
@
|
| 183 |
-
def
|
| 184 |
-
|
| 185 |
-
if not text.strip():
|
| 186 |
raise ValueError("Empty text")
|
| 187 |
|
| 188 |
-
|
| 189 |
-
|
| 190 |
|
| 191 |
return {
|
| 192 |
-
'sentiment':
|
| 193 |
-
'confidence': float(
|
| 194 |
-
'pos_prob': float(
|
| 195 |
-
'neg_prob': float(
|
| 196 |
}
|
| 197 |
|
| 198 |
-
def
|
| 199 |
-
"""Advanced keyword extraction using LIME"""
|
| 200 |
try:
|
| 201 |
-
|
| 202 |
-
|
| 203 |
)
|
| 204 |
|
| 205 |
-
|
| 206 |
-
for
|
| 207 |
-
if len(
|
| 208 |
-
|
| 209 |
|
| 210 |
-
|
| 211 |
-
return
|
| 212 |
|
| 213 |
except Exception as e:
|
| 214 |
-
|
| 215 |
return []
|
| 216 |
|
| 217 |
-
def
|
| 218 |
-
"""Advanced keyword extraction using SHAP"""
|
| 219 |
try:
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
for i, word in enumerate(words):
|
| 229 |
-
# Create text without this word
|
| 230 |
-
modified_words = words[:i] + words[i+1:]
|
| 231 |
-
modified_text = ' '.join(modified_words)
|
| 232 |
|
| 233 |
-
if
|
| 234 |
-
|
| 235 |
-
|
| 236 |
|
| 237 |
-
|
| 238 |
-
if len(
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
unique_scores[word] = max(unique_scores[word], score)
|
| 246 |
else:
|
| 247 |
-
|
| 248 |
|
| 249 |
-
|
| 250 |
-
return
|
| 251 |
|
| 252 |
except Exception as e:
|
| 253 |
-
|
| 254 |
return []
|
| 255 |
|
| 256 |
-
def
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
min_score = min(word_scores.values())
|
| 264 |
else:
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
for
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
if
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
elif
|
| 275 |
-
|
| 276 |
-
|
| 277 |
else:
|
| 278 |
-
|
| 279 |
|
| 280 |
-
|
| 281 |
-
f'<span style="background-color: {
|
| 282 |
-
f'border-radius: 3px;" title="Score: {
|
| 283 |
)
|
| 284 |
|
| 285 |
-
|
| 286 |
-
return ''.join(
|
| 287 |
|
| 288 |
-
@
|
| 289 |
-
def
|
| 290 |
-
|
| 291 |
-
if not text.strip():
|
| 292 |
raise ValueError("Empty text")
|
| 293 |
|
| 294 |
-
|
| 295 |
-
|
| 296 |
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
shap_words = self.extract_key_words_shap(text)
|
| 300 |
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
heatmap_html = self.create_heatmap_html(text, word_scores_dict)
|
| 304 |
|
| 305 |
return {
|
| 306 |
-
'sentiment':
|
| 307 |
-
'confidence': float(
|
| 308 |
-
'pos_prob': float(
|
| 309 |
-
'neg_prob': float(
|
| 310 |
-
'lime_words':
|
| 311 |
-
'shap_words':
|
| 312 |
-
'heatmap_html':
|
| 313 |
}
|
| 314 |
|
| 315 |
-
@
|
| 316 |
-
def
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
texts = texts[:config.BATCH_SIZE_LIMIT]
|
| 320 |
|
| 321 |
-
|
| 322 |
-
|
| 323 |
|
| 324 |
-
for i in range(0, len(
|
| 325 |
-
|
| 326 |
|
| 327 |
-
if
|
| 328 |
-
|
| 329 |
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
truncation=True, max_length=
|
| 333 |
-
).to(self.
|
| 334 |
|
| 335 |
with torch.no_grad():
|
| 336 |
-
|
| 337 |
-
|
| 338 |
|
| 339 |
-
for
|
| 340 |
-
|
| 341 |
|
| 342 |
-
|
| 343 |
-
'text':
|
| 344 |
-
'full_text':
|
| 345 |
-
'sentiment':
|
| 346 |
-
'confidence': float(
|
| 347 |
-
'pos_prob': float(
|
| 348 |
-
'neg_prob': float(
|
| 349 |
})
|
| 350 |
|
| 351 |
-
return
|
| 352 |
|
| 353 |
-
|
| 354 |
-
class PlotFactory:
|
| 355 |
-
"""Factory for creating plots with proper memory management"""
|
| 356 |
-
|
| 357 |
@staticmethod
|
| 358 |
-
@
|
| 359 |
-
def
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
return fig
|
| 377 |
|
| 378 |
@staticmethod
|
| 379 |
-
@
|
| 380 |
-
def
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
|
| 404 |
-
return fig
|
| 405 |
|
| 406 |
@staticmethod
|
| 407 |
-
@
|
| 408 |
-
def
|
| 409 |
-
|
| 410 |
-
if not lime_words:
|
| 411 |
return None
|
| 412 |
|
| 413 |
-
with
|
| 414 |
-
|
| 415 |
|
| 416 |
-
|
| 417 |
-
|
| 418 |
|
| 419 |
-
|
| 420 |
|
| 421 |
-
|
| 422 |
-
|
| 423 |
-
|
| 424 |
-
|
| 425 |
-
|
| 426 |
|
| 427 |
-
for i, (
|
| 428 |
-
|
| 429 |
-
f'{
|
| 430 |
|
| 431 |
-
|
| 432 |
-
|
| 433 |
-
|
| 434 |
-
return
|
| 435 |
|
| 436 |
@staticmethod
|
| 437 |
-
@
|
| 438 |
-
def
|
| 439 |
-
|
| 440 |
-
if not shap_words:
|
| 441 |
return None
|
| 442 |
|
| 443 |
-
with
|
| 444 |
-
|
| 445 |
|
| 446 |
-
|
| 447 |
-
|
| 448 |
|
| 449 |
-
|
| 450 |
|
| 451 |
-
|
| 452 |
-
|
| 453 |
-
|
| 454 |
-
|
| 455 |
-
|
| 456 |
|
| 457 |
-
for i, (
|
| 458 |
-
|
| 459 |
-
f'{
|
| 460 |
|
| 461 |
-
|
| 462 |
-
|
| 463 |
-
|
| 464 |
-
return
|
| 465 |
|
| 466 |
@staticmethod
|
| 467 |
-
@
|
| 468 |
-
def
|
| 469 |
-
|
| 470 |
-
if len(text.split()) < 3:
|
| 471 |
return None
|
| 472 |
|
| 473 |
-
|
| 474 |
-
|
| 475 |
-
colormap=
|
| 476 |
-
|
| 477 |
-
with
|
| 478 |
-
|
| 479 |
-
|
| 480 |
-
|
| 481 |
-
|
| 482 |
-
|
| 483 |
-
return
|
| 484 |
|
| 485 |
@staticmethod
|
| 486 |
-
@
|
| 487 |
-
def
|
| 488 |
-
|
| 489 |
-
|
| 490 |
-
|
| 491 |
-
|
| 492 |
-
|
| 493 |
-
|
| 494 |
-
|
| 495 |
-
|
| 496 |
-
|
| 497 |
-
|
| 498 |
-
|
| 499 |
-
|
| 500 |
-
|
| 501 |
-
|
| 502 |
-
|
| 503 |
-
|
| 504 |
-
|
| 505 |
-
|
| 506 |
-
|
| 507 |
-
|
| 508 |
-
|
| 509 |
-
|
| 510 |
-
|
| 511 |
-
|
| 512 |
-
|
| 513 |
-
|
| 514 |
-
|
| 515 |
-
|
| 516 |
-
ax3.set_xlabel('Review Index')
|
| 517 |
-
ax3.set_ylabel('Positive Probability')
|
| 518 |
-
|
| 519 |
-
return fig
|
| 520 |
|
| 521 |
-
class
|
| 522 |
-
"""Handles all data operations"""
|
| 523 |
-
|
| 524 |
@staticmethod
|
| 525 |
-
@
|
| 526 |
-
def
|
| 527 |
-
|
| 528 |
-
if not data:
|
| 529 |
return None, "No data to export"
|
| 530 |
|
| 531 |
-
|
| 532 |
-
suffix=f'.{
|
| 533 |
-
|
| 534 |
-
if
|
| 535 |
-
|
| 536 |
-
|
| 537 |
-
for
|
| 538 |
-
|
| 539 |
-
|
| 540 |
-
|
| 541 |
-
|
| 542 |
-
f"{
|
| 543 |
-
f"{
|
| 544 |
-
f"{
|
| 545 |
])
|
| 546 |
-
elif
|
| 547 |
-
json.dump(
|
| 548 |
|
| 549 |
-
|
| 550 |
-
return
|
| 551 |
|
| 552 |
@staticmethod
|
| 553 |
-
@
|
| 554 |
-
def
|
| 555 |
-
|
| 556 |
-
if not file:
|
| 557 |
return ""
|
| 558 |
|
| 559 |
try:
|
| 560 |
-
|
| 561 |
|
| 562 |
-
if
|
| 563 |
-
for
|
| 564 |
try:
|
| 565 |
-
|
| 566 |
|
| 567 |
-
|
| 568 |
-
for
|
| 569 |
-
|
| 570 |
-
if len(
|
| 571 |
-
|
| 572 |
-
if isinstance(
|
| 573 |
-
if
|
| 574 |
-
|
| 575 |
|
| 576 |
-
if
|
| 577 |
-
|
| 578 |
else:
|
| 579 |
-
|
| 580 |
|
| 581 |
-
|
| 582 |
|
| 583 |
-
|
| 584 |
-
for
|
| 585 |
-
|
| 586 |
-
if len(
|
| 587 |
-
|
| 588 |
|
| 589 |
-
if
|
| 590 |
-
|
| 591 |
-
return '\n'.join(
|
| 592 |
|
| 593 |
except Exception as e:
|
| 594 |
continue
|
|
@@ -596,31 +554,28 @@ class DataHandler:
|
|
| 596 |
return "Error: Could not read CSV file. Please check the file format and encoding."
|
| 597 |
|
| 598 |
else:
|
| 599 |
-
for
|
| 600 |
try:
|
| 601 |
-
with open(
|
| 602 |
-
|
| 603 |
-
if
|
| 604 |
-
return
|
| 605 |
except Exception as e:
|
| 606 |
continue
|
| 607 |
|
| 608 |
return "Error: Could not read text file. Please check the file encoding."
|
| 609 |
|
| 610 |
except Exception as e:
|
| 611 |
-
|
| 612 |
return f"Error processing file: {str(e)}"
|
| 613 |
|
| 614 |
-
|
| 615 |
-
class SentimentApp:
|
| 616 |
-
"""Main application orchestrator"""
|
| 617 |
-
|
| 618 |
def __init__(self):
|
| 619 |
-
self.
|
| 620 |
-
self.
|
| 621 |
-
self.
|
| 622 |
|
| 623 |
-
self.
|
| 624 |
["While the film's visual effects were undeniably impressive, the story lacked emotional weight, and the pacing felt inconsistent throughout."],
|
| 625 |
["An extraordinary achievement in filmmaking — the direction was masterful, the script was sharp, and every performance added depth and realism."],
|
| 626 |
["Despite a promising start, the film quickly devolved into a series of clichés, with weak character development and an ending that felt rushed and unearned."],
|
|
@@ -628,259 +583,246 @@ class SentimentApp:
|
|
| 628 |
["The movie was far too long, with unnecessary subplots and dull dialogue that made it difficult to stay engaged until the end."]
|
| 629 |
]
|
| 630 |
|
| 631 |
-
@
|
| 632 |
-
def
|
| 633 |
-
|
| 634 |
-
if not text.strip():
|
| 635 |
return "Please enter text", None, None, None
|
| 636 |
|
| 637 |
-
|
| 638 |
|
| 639 |
-
self.
|
| 640 |
-
'text':
|
| 641 |
-
'full_text':
|
| 642 |
-
**
|
| 643 |
})
|
| 644 |
|
| 645 |
-
|
| 646 |
-
|
| 647 |
|
| 648 |
-
|
| 649 |
-
|
| 650 |
-
|
| 651 |
|
| 652 |
-
|
| 653 |
|
| 654 |
-
return
|
| 655 |
|
| 656 |
-
@
|
| 657 |
-
def
|
| 658 |
-
|
| 659 |
-
if not text.strip():
|
| 660 |
return "Please enter text", None, None, None
|
| 661 |
|
| 662 |
-
|
| 663 |
|
| 664 |
-
self.
|
| 665 |
-
'text':
|
| 666 |
-
'full_text':
|
| 667 |
-
**
|
| 668 |
})
|
| 669 |
|
| 670 |
-
|
| 671 |
|
| 672 |
-
|
| 673 |
-
|
| 674 |
|
| 675 |
-
|
| 676 |
-
|
| 677 |
|
| 678 |
-
|
| 679 |
-
f"LIME Key Words: {
|
| 680 |
-
f"SHAP Key Words: {
|
| 681 |
|
| 682 |
-
return
|
| 683 |
|
| 684 |
-
@
|
| 685 |
-
def
|
| 686 |
-
|
| 687 |
-
if not reviews.strip():
|
| 688 |
return None
|
| 689 |
|
| 690 |
-
|
| 691 |
-
if len(
|
| 692 |
return None
|
| 693 |
|
| 694 |
-
|
| 695 |
|
| 696 |
-
for
|
| 697 |
-
self.
|
| 698 |
|
| 699 |
-
|
| 700 |
-
return
|
| 701 |
|
| 702 |
-
@
|
| 703 |
-
def
|
| 704 |
-
|
| 705 |
-
|
| 706 |
-
|
| 707 |
-
|
| 708 |
-
|
| 709 |
-
|
| 710 |
-
|
| 711 |
-
|
| 712 |
-
|
| 713 |
-
|
| 714 |
-
|
| 715 |
-
|
| 716 |
-
|
| 717 |
-
|
| 718 |
-
|
| 719 |
-
|
| 720 |
-
|
| 721 |
-
|
| 722 |
-
|
| 723 |
-
|
| 724 |
-
|
| 725 |
-
|
| 726 |
-
|
| 727 |
-
|
| 728 |
-
|
| 729 |
-
|
| 730 |
-
|
| 731 |
-
|
| 732 |
-
|
| 733 |
-
|
| 734 |
-
|
| 735 |
-
|
| 736 |
-
|
| 737 |
-
fig.tight_layout()
|
| 738 |
-
return fig, f"History: {len(history)} analyses"
|
| 739 |
|
| 740 |
-
|
| 741 |
-
|
| 742 |
-
"""Create streamlined Gradio interface"""
|
| 743 |
-
app = SentimentApp()
|
| 744 |
|
| 745 |
-
with gr.Blocks(theme=gr.themes.Soft(), title="Movie Sentiment Analyzer") as
|
| 746 |
gr.Markdown("# 🎬 AI Movie Sentiment Analyzer")
|
| 747 |
gr.Markdown("Fast sentiment analysis with advanced deep learning explanations")
|
| 748 |
|
| 749 |
with gr.Tab("Quick Analysis"):
|
| 750 |
with gr.Row():
|
| 751 |
with gr.Column():
|
| 752 |
-
|
| 753 |
label="Movie Review",
|
| 754 |
placeholder="Enter your movie review...",
|
| 755 |
lines=5
|
| 756 |
)
|
| 757 |
with gr.Row():
|
| 758 |
-
|
| 759 |
-
|
| 760 |
-
choices=list(
|
| 761 |
value="default",
|
| 762 |
label="Theme"
|
| 763 |
)
|
| 764 |
|
| 765 |
gr.Examples(
|
| 766 |
-
examples=
|
| 767 |
-
inputs=
|
| 768 |
)
|
| 769 |
|
| 770 |
with gr.Column():
|
| 771 |
-
|
| 772 |
|
| 773 |
with gr.Row():
|
| 774 |
-
|
| 775 |
-
|
| 776 |
|
| 777 |
with gr.Row():
|
| 778 |
-
|
| 779 |
|
| 780 |
with gr.Tab("Advanced Analysis"):
|
| 781 |
with gr.Row():
|
| 782 |
with gr.Column():
|
| 783 |
-
|
| 784 |
label="Movie Review",
|
| 785 |
placeholder="Enter your movie review for deep analysis...",
|
| 786 |
lines=5
|
| 787 |
)
|
| 788 |
with gr.Row():
|
| 789 |
-
|
| 790 |
-
|
| 791 |
-
choices=list(
|
| 792 |
value="default",
|
| 793 |
label="Theme"
|
| 794 |
)
|
| 795 |
|
| 796 |
gr.Examples(
|
| 797 |
-
examples=
|
| 798 |
-
inputs=
|
| 799 |
)
|
| 800 |
|
| 801 |
with gr.Column():
|
| 802 |
-
|
| 803 |
|
| 804 |
with gr.Row():
|
| 805 |
-
|
| 806 |
-
|
| 807 |
|
| 808 |
with gr.Row():
|
| 809 |
-
|
| 810 |
|
| 811 |
with gr.Tab("Batch Analysis"):
|
| 812 |
with gr.Row():
|
| 813 |
with gr.Column():
|
| 814 |
-
|
| 815 |
-
|
| 816 |
label="Reviews (one per line)",
|
| 817 |
lines=8
|
| 818 |
)
|
| 819 |
|
| 820 |
with gr.Column():
|
| 821 |
-
|
| 822 |
-
|
| 823 |
|
| 824 |
-
|
| 825 |
|
| 826 |
with gr.Tab("History & Export"):
|
| 827 |
with gr.Row():
|
| 828 |
-
|
| 829 |
-
|
| 830 |
|
| 831 |
with gr.Row():
|
| 832 |
-
|
| 833 |
-
|
| 834 |
-
|
| 835 |
-
|
| 836 |
-
|
| 837 |
-
|
| 838 |
-
|
| 839 |
-
|
| 840 |
-
|
| 841 |
-
|
| 842 |
-
|
| 843 |
-
|
| 844 |
-
outputs=[result_output, prob_plot, gauge_plot, wordcloud_plot]
|
| 845 |
)
|
| 846 |
|
| 847 |
-
|
| 848 |
-
|
| 849 |
-
|
| 850 |
-
|
| 851 |
-
outputs=[adv_result_output, lime_plot, shap_plot, heatmap_output]
|
| 852 |
)
|
| 853 |
|
| 854 |
-
|
| 855 |
-
|
| 856 |
-
batch_btn.click(app.analyze_batch, inputs=batch_input, outputs=batch_plot)
|
| 857 |
|
| 858 |
-
|
| 859 |
-
|
| 860 |
-
|
| 861 |
-
|
| 862 |
-
outputs=[history_plot, history_status]
|
| 863 |
)
|
| 864 |
|
| 865 |
-
|
| 866 |
-
lambda: f"Cleared {
|
| 867 |
-
outputs=
|
| 868 |
)
|
| 869 |
|
| 870 |
-
|
| 871 |
-
lambda:
|
| 872 |
-
outputs=[
|
| 873 |
)
|
| 874 |
|
| 875 |
-
|
| 876 |
-
lambda:
|
| 877 |
-
outputs=[
|
| 878 |
)
|
| 879 |
|
| 880 |
-
return
|
| 881 |
|
| 882 |
-
# Application Entry Point
|
| 883 |
if __name__ == "__main__":
|
| 884 |
logging.basicConfig(level=logging.INFO)
|
| 885 |
-
|
| 886 |
-
|
|
|
|
| 20 |
import pandas as pd
|
| 21 |
from lime.lime_text import LimeTextExplainer
|
| 22 |
import shap
|
| 23 |
+
import base64
|
| 24 |
|
| 25 |
@dataclass
|
| 26 |
+
class _C7x9:
|
| 27 |
+
_m1: int = 1000
|
| 28 |
+
_b2: int = 50
|
| 29 |
+
_t3: int = 512
|
| 30 |
+
_w4: int = 2
|
| 31 |
+
_c5: int = 128
|
| 32 |
+
_p6: int = 8
|
| 33 |
+
|
| 34 |
+
_fs1: Tuple[int, int] = (8, 5)
|
| 35 |
+
_fs2: Tuple[int, int] = (12, 8)
|
| 36 |
+
_ws: Tuple[int, int] = (10, 5)
|
| 37 |
+
|
| 38 |
+
_th = {
|
|
|
|
| 39 |
'default': {'pos': '#4ecdc4', 'neg': '#ff6b6b'},
|
| 40 |
'ocean': {'pos': '#0077be', 'neg': '#ff6b35'},
|
| 41 |
'forest': {'pos': '#228b22', 'neg': '#dc143c'},
|
| 42 |
'sunset': {'pos': '#ff8c00', 'neg': '#8b0000'}
|
| 43 |
}
|
| 44 |
|
| 45 |
+
_sw = {
|
| 46 |
'the', 'a', 'an', 'and', 'or', 'but', 'in', 'on', 'at', 'to',
|
| 47 |
'for', 'of', 'with', 'by', 'is', 'are', 'was', 'were', 'be',
|
| 48 |
'been', 'have', 'has', 'had', 'will', 'would', 'could', 'should'
|
| 49 |
}
|
| 50 |
|
| 51 |
+
_cfg = _C7x9()
|
| 52 |
+
_log = logging.getLogger(__name__)
|
| 53 |
|
| 54 |
+
def _err_wrap(_def_ret=None):
|
| 55 |
+
def _dec(_func: Callable) -> Callable:
|
| 56 |
+
@wraps(_func)
|
| 57 |
+
def _wrap(*args, **kwargs):
|
|
|
|
|
|
|
| 58 |
try:
|
| 59 |
+
return _func(*args, **kwargs)
|
| 60 |
except Exception as e:
|
| 61 |
+
_log.error(f"{_func.__name__} failed: {e}")
|
| 62 |
+
return _def_ret if _def_ret is not None else f"Error: {str(e)}"
|
| 63 |
+
return _wrap
|
| 64 |
+
return _dec
|
| 65 |
|
| 66 |
@contextmanager
|
| 67 |
+
def _fig_mgr(*args, **kwargs):
|
| 68 |
+
_f = plt.figure(*args, **kwargs)
|
|
|
|
| 69 |
try:
|
| 70 |
+
yield _f
|
| 71 |
finally:
|
| 72 |
+
plt.close(_f)
|
| 73 |
gc.collect()
|
| 74 |
|
| 75 |
+
class _Th7:
|
| 76 |
+
def __init__(self, _t: str = 'default'):
|
| 77 |
+
self._t = _t
|
| 78 |
+
self._c = _cfg._th.get(_t, _cfg._th['default'])
|
|
|
|
| 79 |
|
| 80 |
+
class _MM9:
|
| 81 |
+
_inst = None
|
| 82 |
+
_mdl = None
|
| 83 |
+
_tok = None
|
| 84 |
+
_dev = None
|
|
|
|
|
|
|
| 85 |
|
| 86 |
def __new__(cls):
|
| 87 |
+
if cls._inst is None:
|
| 88 |
+
cls._inst = super().__new__(cls)
|
| 89 |
+
return cls._inst
|
| 90 |
|
| 91 |
@property
|
| 92 |
+
def _m(self):
|
| 93 |
+
if self._mdl is None:
|
| 94 |
+
self._load()
|
| 95 |
+
return self._mdl
|
| 96 |
|
| 97 |
@property
|
| 98 |
+
def _t(self):
|
| 99 |
+
if self._tok is None:
|
| 100 |
+
self._load()
|
| 101 |
+
return self._tok
|
| 102 |
|
| 103 |
@property
|
| 104 |
+
def _d(self):
|
| 105 |
+
if self._dev is None:
|
| 106 |
+
self._dev = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 107 |
+
return self._dev
|
| 108 |
|
| 109 |
+
def _load(self):
|
|
|
|
| 110 |
try:
|
| 111 |
+
self._dev = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 112 |
+
_mp = base64.b64decode("ZW50cm9weTI1L3NlbnRpbWVudGFuYWx5c2lz").decode()
|
| 113 |
+
self._tok = BertTokenizer.from_pretrained(_mp)
|
| 114 |
+
self._mdl = BertForSequenceClassification.from_pretrained(_mp)
|
| 115 |
+
self._mdl.to(self._dev)
|
| 116 |
+
_log.info(f"Model loaded on {self._dev}")
|
| 117 |
except Exception as e:
|
| 118 |
+
_log.error(f"Model loading failed: {e}")
|
| 119 |
raise
|
| 120 |
|
| 121 |
+
class _TP8:
|
|
|
|
|
|
|
| 122 |
@staticmethod
|
| 123 |
+
@lru_cache(maxsize=_cfg._c5)
|
| 124 |
+
def _clean(_txt: str) -> Tuple[str, ...]:
|
| 125 |
+
_w = re.findall(r'\b\w{3,}\b', _txt.lower())
|
| 126 |
+
return tuple(w for w in _w if w not in _cfg._sw)
|
|
|
|
| 127 |
|
| 128 |
+
class _HM2:
|
|
|
|
| 129 |
def __init__(self):
|
| 130 |
+
self._h = []
|
| 131 |
|
| 132 |
+
def _add(self, _e: Dict):
|
| 133 |
+
self._h.append({**_e, 'timestamp': datetime.now().isoformat()})
|
| 134 |
+
if len(self._h) > _cfg._m1:
|
| 135 |
+
self._h = self._h[-_cfg._m1:]
|
| 136 |
|
| 137 |
+
def _get(self) -> List[Dict]:
|
| 138 |
+
return self._h.copy()
|
| 139 |
|
| 140 |
+
def _clr(self) -> int:
|
| 141 |
+
_cnt = len(self._h)
|
| 142 |
+
self._h.clear()
|
| 143 |
+
return _cnt
|
| 144 |
|
| 145 |
+
def _sz(self) -> int:
|
| 146 |
+
return len(self._h)
|
| 147 |
|
| 148 |
+
class _SE3:
|
|
|
|
|
|
|
| 149 |
def __init__(self):
|
| 150 |
+
self._mm = _MM9()
|
| 151 |
+
self._le = LimeTextExplainer(class_names=['Negative', 'Positive'])
|
| 152 |
+
self._se = None
|
| 153 |
|
| 154 |
+
def _pred(self, _txts):
|
| 155 |
+
if isinstance(_txts, str):
|
| 156 |
+
_txts = [_txts]
|
|
|
|
| 157 |
|
| 158 |
+
_inp = self._mm._t(
|
| 159 |
+
_txts, return_tensors="pt", padding=True,
|
| 160 |
+
truncation=True, max_length=_cfg._t3
|
| 161 |
+
).to(self._mm._d)
|
| 162 |
|
| 163 |
with torch.no_grad():
|
| 164 |
+
_out = self._mm._m(**_inp)
|
| 165 |
+
_probs = torch.nn.functional.softmax(_out.logits, dim=-1).cpu().numpy()
|
| 166 |
|
| 167 |
+
return _probs
|
| 168 |
|
| 169 |
+
@_err_wrap(default_return={'sentiment': 'Unknown', 'confidence': 0.0})
|
| 170 |
+
def _fast(self, _txt: str) -> Dict:
|
| 171 |
+
if not _txt.strip():
|
|
|
|
| 172 |
raise ValueError("Empty text")
|
| 173 |
|
| 174 |
+
_probs = self._pred([_txt])[0]
|
| 175 |
+
_sent = "Positive" if _probs[1] > _probs[0] else "Negative"
|
| 176 |
|
| 177 |
return {
|
| 178 |
+
'sentiment': _sent,
|
| 179 |
+
'confidence': float(_probs.max()),
|
| 180 |
+
'pos_prob': float(_probs[1]),
|
| 181 |
+
'neg_prob': float(_probs[0])
|
| 182 |
}
|
| 183 |
|
| 184 |
+
def _lime_kw(self, _txt: str, _k: int = 10) -> List[Tuple[str, float]]:
|
|
|
|
| 185 |
try:
|
| 186 |
+
_exp = self._le.explain_instance(
|
| 187 |
+
_txt, self._pred, num_features=_k, num_samples=200
|
| 188 |
)
|
| 189 |
|
| 190 |
+
_ws = []
|
| 191 |
+
for _w, _s in _exp.as_list():
|
| 192 |
+
if len(_w.strip()) >= _cfg._w4:
|
| 193 |
+
_ws.append((_w.strip().lower(), abs(_s)))
|
| 194 |
|
| 195 |
+
_ws.sort(key=lambda x: x[1], reverse=True)
|
| 196 |
+
return _ws[:_k]
|
| 197 |
|
| 198 |
except Exception as e:
|
| 199 |
+
_log.error(f"LIME extraction failed: {e}")
|
| 200 |
return []
|
| 201 |
|
| 202 |
+
def _shap_kw(self, _txt: str, _k: int = 10) -> List[Tuple[str, float]]:
|
|
|
|
| 203 |
try:
|
| 204 |
+
_words = _txt.split()
|
| 205 |
+
_ws = []
|
| 206 |
+
|
| 207 |
+
_base = self._pred([_txt])[0][1]
|
| 208 |
+
|
| 209 |
+
for i, _w in enumerate(_words):
|
| 210 |
+
_mod_w = _words[:i] + _words[i+1:]
|
| 211 |
+
_mod_t = ' '.join(_mod_w)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 212 |
|
| 213 |
+
if _mod_t.strip():
|
| 214 |
+
_mod_p = self._pred([_mod_t])[0][1]
|
| 215 |
+
_imp = abs(_base - _mod_p)
|
| 216 |
|
| 217 |
+
_clean_w = re.sub(r'[^\w]', '', _w.lower())
|
| 218 |
+
if len(_clean_w) >= _cfg._w4:
|
| 219 |
+
_ws.append((_clean_w, _imp))
|
| 220 |
+
|
| 221 |
+
_uniq = {}
|
| 222 |
+
for _w, _s in _ws:
|
| 223 |
+
if _w in _uniq:
|
| 224 |
+
_uniq[_w] = max(_uniq[_w], _s)
|
|
|
|
| 225 |
else:
|
| 226 |
+
_uniq[_w] = _s
|
| 227 |
|
| 228 |
+
_sorted = sorted(_uniq.items(), key=lambda x: x[1], reverse=True)
|
| 229 |
+
return _sorted[:_k]
|
| 230 |
|
| 231 |
except Exception as e:
|
| 232 |
+
_log.error(f"SHAP extraction failed: {e}")
|
| 233 |
return []
|
| 234 |
|
| 235 |
+
def _heatmap(self, _txt: str, _ws: Dict[str, float]) -> str:
|
| 236 |
+
_words = _txt.split()
|
| 237 |
+
_html = ['<div style="font-family: Arial; font-size: 16px; line-height: 1.6;">']
|
| 238 |
+
|
| 239 |
+
if _ws:
|
| 240 |
+
_max = max(abs(_s) for _s in _ws.values())
|
| 241 |
+
_min = min(_ws.values())
|
|
|
|
| 242 |
else:
|
| 243 |
+
_max = _min = 0
|
| 244 |
+
|
| 245 |
+
for _w in _words:
|
| 246 |
+
_clean = re.sub(r'[^\w]', '', _w.lower())
|
| 247 |
+
_score = _ws.get(_clean, 0)
|
| 248 |
+
|
| 249 |
+
if _score > 0:
|
| 250 |
+
_int = min(255, int(180 * (_score / _max) if _max > 0 else 0))
|
| 251 |
+
_color = f"rgba(0, {_int}, 0, 0.3)"
|
| 252 |
+
elif _score < 0:
|
| 253 |
+
_int = min(255, int(180 * (abs(_score) / abs(_min)) if _min < 0 else 0))
|
| 254 |
+
_color = f"rgba({_int}, 0, 0, 0.3)"
|
| 255 |
else:
|
| 256 |
+
_color = "transparent"
|
| 257 |
|
| 258 |
+
_html.append(
|
| 259 |
+
f'<span style="background-color: {_color}; padding: 2px; margin: 1px; '
|
| 260 |
+
f'border-radius: 3px;" title="Score: {_score:.3f}">{_w}</span> '
|
| 261 |
)
|
| 262 |
|
| 263 |
+
_html.append('</div>')
|
| 264 |
+
return ''.join(_html)
|
| 265 |
|
| 266 |
+
@_err_wrap(default_return={'sentiment': 'Unknown', 'confidence': 0.0, 'lime_words': [], 'shap_words': [], 'heatmap_html': ''})
|
| 267 |
+
def _adv(self, _txt: str) -> Dict:
|
| 268 |
+
if not _txt.strip():
|
|
|
|
| 269 |
raise ValueError("Empty text")
|
| 270 |
|
| 271 |
+
_probs = self._pred([_txt])[0]
|
| 272 |
+
_sent = "Positive" if _probs[1] > _probs[0] else "Negative"
|
| 273 |
|
| 274 |
+
_lime = self._lime_kw(_txt)
|
| 275 |
+
_shap = self._shap_kw(_txt)
|
|
|
|
| 276 |
|
| 277 |
+
_ws_dict = dict(_lime)
|
| 278 |
+
_heat = self._heatmap(_txt, _ws_dict)
|
|
|
|
| 279 |
|
| 280 |
return {
|
| 281 |
+
'sentiment': _sent,
|
| 282 |
+
'confidence': float(_probs.max()),
|
| 283 |
+
'pos_prob': float(_probs[1]),
|
| 284 |
+
'neg_prob': float(_probs[0]),
|
| 285 |
+
'lime_words': _lime,
|
| 286 |
+
'shap_words': _shap,
|
| 287 |
+
'heatmap_html': _heat
|
| 288 |
}
|
| 289 |
|
| 290 |
+
@_err_wrap(default_return=[])
|
| 291 |
+
def _batch(self, _txts: List[str], _prog=None) -> List[Dict]:
|
| 292 |
+
if len(_txts) > _cfg._b2:
|
| 293 |
+
_txts = _txts[:_cfg._b2]
|
|
|
|
| 294 |
|
| 295 |
+
_res = []
|
| 296 |
+
_bs = _cfg._p6
|
| 297 |
|
| 298 |
+
for i in range(0, len(_txts), _bs):
|
| 299 |
+
_b = _txts[i:i+_bs]
|
| 300 |
|
| 301 |
+
if _prog:
|
| 302 |
+
_prog((i + len(_b)) / len(_txts))
|
| 303 |
|
| 304 |
+
_inp = self._mm._t(
|
| 305 |
+
_b, return_tensors="pt", padding=True,
|
| 306 |
+
truncation=True, max_length=_cfg._t3
|
| 307 |
+
).to(self._mm._d)
|
| 308 |
|
| 309 |
with torch.no_grad():
|
| 310 |
+
_out = self._mm._m(**_inp)
|
| 311 |
+
_probs = torch.nn.functional.softmax(_out.logits, dim=-1).cpu().numpy()
|
| 312 |
|
| 313 |
+
for _txt, _prob in zip(_b, _probs):
|
| 314 |
+
_sent = "Positive" if _prob[1] > _prob[0] else "Negative"
|
| 315 |
|
| 316 |
+
_res.append({
|
| 317 |
+
'text': _txt[:50] + '...' if len(_txt) > 50 else _txt,
|
| 318 |
+
'full_text': _txt,
|
| 319 |
+
'sentiment': _sent,
|
| 320 |
+
'confidence': float(_prob.max()),
|
| 321 |
+
'pos_prob': float(_prob[1]),
|
| 322 |
+
'neg_prob': float(_prob[0])
|
| 323 |
})
|
| 324 |
|
| 325 |
+
return _res
|
| 326 |
|
| 327 |
+
class _PF4:
|
|
|
|
|
|
|
|
|
|
| 328 |
@staticmethod
|
| 329 |
+
@_err_wrap(default_return=None)
|
| 330 |
+
def _bars(_probs: np.ndarray, _th: _Th7) -> plt.Figure:
|
| 331 |
+
with _fig_mgr(figsize=_cfg._fs1) as _f:
|
| 332 |
+
_ax = _f.add_subplot(111)
|
| 333 |
+
_lbl = ["Negative", "Positive"]
|
| 334 |
+
_clr = [_th._c['neg'], _th._c['pos']]
|
| 335 |
+
|
| 336 |
+
_b = _ax.bar(_lbl, _probs, color=_clr, alpha=0.8)
|
| 337 |
+
_ax.set_title("Sentiment Probabilities", fontweight='bold')
|
| 338 |
+
_ax.set_ylabel("Probability")
|
| 339 |
+
_ax.set_ylim(0, 1)
|
| 340 |
+
|
| 341 |
+
for _bar, _prob in zip(_b, _probs):
|
| 342 |
+
_ax.text(_bar.get_x() + _bar.get_width()/2., _bar.get_height() + 0.02,
|
| 343 |
+
f'{_prob:.3f}', ha='center', va='bottom', fontweight='bold')
|
| 344 |
+
|
| 345 |
+
_f.tight_layout()
|
| 346 |
+
return _f
|
|
|
|
| 347 |
|
| 348 |
@staticmethod
|
| 349 |
+
@_err_wrap(default_return=None)
|
| 350 |
+
def _gauge(_conf: float, _sent: str, _th: _Th7) -> plt.Figure:
|
| 351 |
+
with _fig_mgr(figsize=_cfg._fs1) as _f:
|
| 352 |
+
_ax = _f.add_subplot(111)
|
| 353 |
+
|
| 354 |
+
_theta = np.linspace(0, np.pi, 100)
|
| 355 |
+
_clr = [_th._c['neg'] if i < 50 else _th._c['pos'] for i in range(100)]
|
| 356 |
+
|
| 357 |
+
for i in range(len(_theta)-1):
|
| 358 |
+
_ax.fill_between([_theta[i], _theta[i+1]], [0, 0], [0.8, 0.8],
|
| 359 |
+
color=_clr[i], alpha=0.7)
|
| 360 |
+
|
| 361 |
+
_pos = np.pi * (0.5 + (0.4 if _sent == 'Positive' else -0.4) * _conf)
|
| 362 |
+
_ax.plot([_pos, _pos], [0, 0.6], 'k-', linewidth=6)
|
| 363 |
+
_ax.plot(_pos, 0.6, 'ko', markersize=10)
|
| 364 |
+
|
| 365 |
+
_ax.set_xlim(0, np.pi)
|
| 366 |
+
_ax.set_ylim(0, 1)
|
| 367 |
+
_ax.set_title(f'{_sent} - Confidence: {_conf:.3f}', fontweight='bold')
|
| 368 |
+
_ax.set_xticks([0, np.pi/2, np.pi])
|
| 369 |
+
_ax.set_xticklabels(['Negative', 'Neutral', 'Positive'])
|
| 370 |
+
_ax.axis('off')
|
| 371 |
+
|
| 372 |
+
_f.tight_layout()
|
| 373 |
+
return _f
|
|
|
|
| 374 |
|
| 375 |
@staticmethod
|
| 376 |
+
@_err_wrap(default_return=None)
|
| 377 |
+
def _lime_chart(_lw: List[Tuple[str, float]], _sent: str, _th: _Th7) -> Optional[plt.Figure]:
|
| 378 |
+
if not _lw:
|
|
|
|
| 379 |
return None
|
| 380 |
|
| 381 |
+
with _fig_mgr(figsize=_cfg._fs1) as _f:
|
| 382 |
+
_ax = _f.add_subplot(111)
|
| 383 |
|
| 384 |
+
_w = [_word for _word, _score in _lw]
|
| 385 |
+
_s = [_score for _word, _score in _lw]
|
| 386 |
|
| 387 |
+
_clr = _th._c['pos'] if _sent == 'Positive' else _th._c['neg']
|
| 388 |
|
| 389 |
+
_b = _ax.barh(range(len(_w)), _s, color=_clr, alpha=0.7)
|
| 390 |
+
_ax.set_yticks(range(len(_w)))
|
| 391 |
+
_ax.set_yticklabels(_w)
|
| 392 |
+
_ax.set_xlabel('LIME Attention Weight')
|
| 393 |
+
_ax.set_title(f'LIME: Top Contributing Words ({_sent})', fontweight='bold')
|
| 394 |
|
| 395 |
+
for i, (_bar, _score) in enumerate(zip(_b, _s)):
|
| 396 |
+
_ax.text(_bar.get_width() + 0.001, _bar.get_y() + _bar.get_height()/2.,
|
| 397 |
+
f'{_score:.3f}', ha='left', va='center', fontsize=9)
|
| 398 |
|
| 399 |
+
_ax.invert_yaxis()
|
| 400 |
+
_ax.grid(axis='x', alpha=0.3)
|
| 401 |
+
_f.tight_layout()
|
| 402 |
+
return _f
|
| 403 |
|
| 404 |
@staticmethod
|
| 405 |
+
@_err_wrap(default_return=None)
|
| 406 |
+
def _shap_chart(_sw: List[Tuple[str, float]], _sent: str, _th: _Th7) -> Optional[plt.Figure]:
|
| 407 |
+
if not _sw:
|
|
|
|
| 408 |
return None
|
| 409 |
|
| 410 |
+
with _fig_mgr(figsize=_cfg._fs1) as _f:
|
| 411 |
+
_ax = _f.add_subplot(111)
|
| 412 |
|
| 413 |
+
_w = [_word for _word, _score in _sw]
|
| 414 |
+
_s = [_score for _word, _score in _sw]
|
| 415 |
|
| 416 |
+
_clr = _th._c['pos'] if _sent == 'Positive' else _th._c['neg']
|
| 417 |
|
| 418 |
+
_b = _ax.barh(range(len(_w)), _s, color=_clr, alpha=0.7)
|
| 419 |
+
_ax.set_yticks(range(len(_w)))
|
| 420 |
+
_ax.set_yticklabels(_w)
|
| 421 |
+
_ax.set_xlabel('SHAP Value')
|
| 422 |
+
_ax.set_title(f'SHAP: Top Contributing Words ({_sent})', fontweight='bold')
|
| 423 |
|
| 424 |
+
for i, (_bar, _score) in enumerate(zip(_b, _s)):
|
| 425 |
+
_ax.text(_bar.get_width() + 0.001, _bar.get_y() + _bar.get_height()/2.,
|
| 426 |
+
f'{_score:.3f}', ha='left', va='center', fontsize=9)
|
| 427 |
|
| 428 |
+
_ax.invert_yaxis()
|
| 429 |
+
_ax.grid(axis='x', alpha=0.3)
|
| 430 |
+
_f.tight_layout()
|
| 431 |
+
return _f
|
| 432 |
|
| 433 |
@staticmethod
|
| 434 |
+
@_err_wrap(default_return=None)
|
| 435 |
+
def _cloud(_txt: str, _sent: str, _th: _Th7) -> Optional[plt.Figure]:
|
| 436 |
+
if len(_txt.split()) < 3:
|
|
|
|
| 437 |
return None
|
| 438 |
|
| 439 |
+
_cm = 'Greens' if _sent == 'Positive' else 'Reds'
|
| 440 |
+
_wc = WordCloud(width=800, height=400, background_color='white',
|
| 441 |
+
colormap=_cm, max_words=30).generate(_txt)
|
| 442 |
+
|
| 443 |
+
with _fig_mgr(figsize=_cfg._ws) as _f:
|
| 444 |
+
_ax = _f.add_subplot(111)
|
| 445 |
+
_ax.imshow(_wc, interpolation='bilinear')
|
| 446 |
+
_ax.axis('off')
|
| 447 |
+
_ax.set_title(f'{_sent} Word Cloud', fontweight='bold')
|
| 448 |
+
_f.tight_layout()
|
| 449 |
+
return _f
|
| 450 |
|
| 451 |
@staticmethod
|
| 452 |
+
@_err_wrap(default_return=None)
|
| 453 |
+
def _batch_viz(_res: List[Dict], _th: _Th7) -> plt.Figure:
|
| 454 |
+
with _fig_mgr(figsize=_cfg._fs2) as _f:
|
| 455 |
+
_gs = _f.add_gridspec(2, 2, hspace=0.3, wspace=0.3)
|
| 456 |
+
|
| 457 |
+
_ax1 = _f.add_subplot(_gs[0, 0])
|
| 458 |
+
_sc = Counter([_r['sentiment'] for _r in _res])
|
| 459 |
+
_clr = [_th._c['pos'], _th._c['neg']]
|
| 460 |
+
_ax1.pie(_sc.values(), labels=_sc.keys(),
|
| 461 |
+
autopct='%1.1f%%', colors=_clr[:len(_sc)])
|
| 462 |
+
_ax1.set_title('Sentiment Distribution')
|
| 463 |
+
|
| 464 |
+
_ax2 = _f.add_subplot(_gs[0, 1])
|
| 465 |
+
_confs = [_r['confidence'] for _r in _res]
|
| 466 |
+
_ax2.hist(_confs, bins=8, alpha=0.7, color='skyblue', edgecolor='black')
|
| 467 |
+
_ax2.set_title('Confidence Distribution')
|
| 468 |
+
_ax2.set_xlabel('Confidence')
|
| 469 |
+
|
| 470 |
+
_ax3 = _f.add_subplot(_gs[1, :])
|
| 471 |
+
_pp = [_r['pos_prob'] for _r in _res]
|
| 472 |
+
_idx = range(len(_res))
|
| 473 |
+
_cs = [_th._c['pos'] if _r['sentiment'] == 'Positive'
|
| 474 |
+
else _th._c['neg'] for _r in _res]
|
| 475 |
+
_ax3.scatter(_idx, _pp, c=_cs, alpha=0.7, s=60)
|
| 476 |
+
_ax3.axhline(y=0.5, color='gray', linestyle='--', alpha=0.5)
|
| 477 |
+
_ax3.set_title('Sentiment Progression')
|
| 478 |
+
_ax3.set_xlabel('Review Index')
|
| 479 |
+
_ax3.set_ylabel('Positive Probability')
|
| 480 |
+
|
| 481 |
+
return _f
|
|
|
|
|
|
|
|
|
|
|
|
|
| 482 |
|
| 483 |
+
class _DH5:
|
|
|
|
|
|
|
| 484 |
@staticmethod
|
| 485 |
+
@_err_wrap(default_return=(None, "Export failed"))
|
| 486 |
+
def _exp(_data: List[Dict], _fmt: str) -> Tuple[Optional[str], str]:
|
| 487 |
+
if not _data:
|
|
|
|
| 488 |
return None, "No data to export"
|
| 489 |
|
| 490 |
+
_tf = tempfile.NamedTemporaryFile(mode='w', delete=False,
|
| 491 |
+
suffix=f'.{_fmt}', encoding='utf-8')
|
| 492 |
+
|
| 493 |
+
if _fmt == 'csv':
|
| 494 |
+
_w = csv.writer(_tf)
|
| 495 |
+
_w.writerow(['Timestamp', 'Text', 'Sentiment', 'Confidence', 'Pos_Prob', 'Neg_Prob'])
|
| 496 |
+
for _e in _data:
|
| 497 |
+
_w.writerow([
|
| 498 |
+
_e.get('timestamp', ''),
|
| 499 |
+
_e.get('text', ''),
|
| 500 |
+
_e.get('sentiment', ''),
|
| 501 |
+
f"{_e.get('confidence', 0):.4f}",
|
| 502 |
+
f"{_e.get('pos_prob', 0):.4f}",
|
| 503 |
+
f"{_e.get('neg_prob', 0):.4f}"
|
| 504 |
])
|
| 505 |
+
elif _fmt == 'json':
|
| 506 |
+
json.dump(_data, _tf, indent=2, ensure_ascii=False)
|
| 507 |
|
| 508 |
+
_tf.close()
|
| 509 |
+
return _tf.name, f"Exported {len(_data)} entries"
|
| 510 |
|
| 511 |
@staticmethod
|
| 512 |
+
@_err_wrap(default_return="")
|
| 513 |
+
def _proc(_file) -> str:
|
| 514 |
+
if not _file:
|
|
|
|
| 515 |
return ""
|
| 516 |
|
| 517 |
try:
|
| 518 |
+
_fp = _file.name
|
| 519 |
|
| 520 |
+
if _fp.endswith('.csv'):
|
| 521 |
+
for _enc in ['utf-8', 'latin-1', 'cp1252', 'iso-8859-1']:
|
| 522 |
try:
|
| 523 |
+
_df = pd.read_csv(_fp, encoding=_enc)
|
| 524 |
|
| 525 |
+
_tc = []
|
| 526 |
+
for _col in _df.columns:
|
| 527 |
+
_sv = _df[_col].dropna().head(10)
|
| 528 |
+
if len(_sv) > 0:
|
| 529 |
+
_cnt = sum(1 for _val in _sv
|
| 530 |
+
if isinstance(_val, str) and len(str(_val).strip()) > 10)
|
| 531 |
+
if _cnt > len(_sv) * 0.7:
|
| 532 |
+
_tc.append(_col)
|
| 533 |
|
| 534 |
+
if _tc:
|
| 535 |
+
_sc = _tc[0]
|
| 536 |
else:
|
| 537 |
+
_sc = _df.columns[0]
|
| 538 |
|
| 539 |
+
_rev = _df[_sc].dropna().astype(str).tolist()
|
| 540 |
|
| 541 |
+
_cr = []
|
| 542 |
+
for _r in _rev:
|
| 543 |
+
_r = _r.strip()
|
| 544 |
+
if len(_r) > 10 and _r.lower() != 'nan':
|
| 545 |
+
_cr.append(_r)
|
| 546 |
|
| 547 |
+
if _cr:
|
| 548 |
+
_log.info(f"Successfully read {len(_cr)} reviews from CSV")
|
| 549 |
+
return '\n'.join(_cr)
|
| 550 |
|
| 551 |
except Exception as e:
|
| 552 |
continue
|
|
|
|
| 554 |
return "Error: Could not read CSV file. Please check the file format and encoding."
|
| 555 |
|
| 556 |
else:
|
| 557 |
+
for _enc in ['utf-8', 'latin-1', 'cp1252']:
|
| 558 |
try:
|
| 559 |
+
with open(_fp, 'r', encoding=_enc) as _f:
|
| 560 |
+
_cont = _f.read().strip()
|
| 561 |
+
if _cont:
|
| 562 |
+
return _cont
|
| 563 |
except Exception as e:
|
| 564 |
continue
|
| 565 |
|
| 566 |
return "Error: Could not read text file. Please check the file encoding."
|
| 567 |
|
| 568 |
except Exception as e:
|
| 569 |
+
_log.error(f"File processing error: {e}")
|
| 570 |
return f"Error processing file: {str(e)}"
|
| 571 |
|
| 572 |
+
class _SA6:
|
|
|
|
|
|
|
|
|
|
| 573 |
def __init__(self):
|
| 574 |
+
self._eng = _SE3()
|
| 575 |
+
self._hist = _HM2()
|
| 576 |
+
self._dh = _DH5()
|
| 577 |
|
| 578 |
+
self._ex = [
|
| 579 |
["While the film's visual effects were undeniably impressive, the story lacked emotional weight, and the pacing felt inconsistent throughout."],
|
| 580 |
["An extraordinary achievement in filmmaking — the direction was masterful, the script was sharp, and every performance added depth and realism."],
|
| 581 |
["Despite a promising start, the film quickly devolved into a series of clichés, with weak character development and an ending that felt rushed and unearned."],
|
|
|
|
| 583 |
["The movie was far too long, with unnecessary subplots and dull dialogue that made it difficult to stay engaged until the end."]
|
| 584 |
]
|
| 585 |
|
| 586 |
+
@_err_wrap(default_return=("Please enter text", None, None, None))
|
| 587 |
+
def _fast_ana(self, _txt: str, _th: str = 'default'):
|
| 588 |
+
if not _txt.strip():
|
|
|
|
| 589 |
return "Please enter text", None, None, None
|
| 590 |
|
| 591 |
+
_res = self._eng._fast(_txt)
|
| 592 |
|
| 593 |
+
self._hist._add({
|
| 594 |
+
'text': _txt[:100],
|
| 595 |
+
'full_text': _txt,
|
| 596 |
+
**_res
|
| 597 |
})
|
| 598 |
|
| 599 |
+
_thc = _Th7(_th)
|
| 600 |
+
_probs = np.array([_res['neg_prob'], _res['pos_prob']])
|
| 601 |
|
| 602 |
+
_pp = _PF4._bars(_probs, _thc)
|
| 603 |
+
_gp = _PF4._gauge(_res['confidence'], _res['sentiment'], _thc)
|
| 604 |
+
_cp = _PF4._cloud(_txt, _res['sentiment'], _thc)
|
| 605 |
|
| 606 |
+
_rt = f"Sentiment: {_res['sentiment']} (Confidence: {_res['confidence']:.3f})"
|
| 607 |
|
| 608 |
+
return _rt, _pp, _gp, _cp
|
| 609 |
|
| 610 |
+
@_err_wrap(default_return=("Please enter text", None, None, None))
|
| 611 |
+
def _adv_ana(self, _txt: str, _th: str = 'default'):
|
| 612 |
+
if not _txt.strip():
|
|
|
|
| 613 |
return "Please enter text", None, None, None
|
| 614 |
|
| 615 |
+
_res = self._eng._adv(_txt)
|
| 616 |
|
| 617 |
+
self._hist._add({
|
| 618 |
+
'text': _txt[:100],
|
| 619 |
+
'full_text': _txt,
|
| 620 |
+
**_res
|
| 621 |
})
|
| 622 |
|
| 623 |
+
_thc = _Th7(_th)
|
| 624 |
|
| 625 |
+
_lp = _PF4._lime_chart(_res['lime_words'], _res['sentiment'], _thc)
|
| 626 |
+
_sp = _PF4._shap_chart(_res['shap_words'], _res['sentiment'], _thc)
|
| 627 |
|
| 628 |
+
_lws = ", ".join([f"{_w}({_s:.3f})" for _w, _s in _res['lime_words'][:5]])
|
| 629 |
+
_sws = ", ".join([f"{_w}({_s:.3f})" for _w, _s in _res['shap_words'][:5]])
|
| 630 |
|
| 631 |
+
_rt = (f"Sentiment: {_res['sentiment']} (Confidence: {_res['confidence']:.3f})\n"
|
| 632 |
+
f"LIME Key Words: {_lws}\n"
|
| 633 |
+
f"SHAP Key Words: {_sws}")
|
| 634 |
|
| 635 |
+
return _rt, _lp, _sp, _res['heatmap_html']
|
| 636 |
|
| 637 |
+
@_err_wrap(default_return=None)
|
| 638 |
+
def _batch_ana(self, _revs: str, _prog=None):
|
| 639 |
+
if not _revs.strip():
|
|
|
|
| 640 |
return None
|
| 641 |
|
| 642 |
+
_txts = [_r.strip() for _r in _revs.split('\n') if _r.strip()]
|
| 643 |
+
if len(_txts) < 2:
|
| 644 |
return None
|
| 645 |
|
| 646 |
+
_res = self._eng._batch(_txts, _prog)
|
| 647 |
|
| 648 |
+
for _r in _res:
|
| 649 |
+
self._hist._add(_r)
|
| 650 |
|
| 651 |
+
_thc = _Th7('default')
|
| 652 |
+
return _PF4._batch_viz(_res, _thc)
|
| 653 |
|
| 654 |
+
@_err_wrap(default_return=(None, "No history available"))
|
| 655 |
+
def _hist_plot(self, _th: str = 'default'):
|
| 656 |
+
_hist = self._hist._get()
|
| 657 |
+
if len(_hist) < 2:
|
| 658 |
+
return None, f"Need at least 2 analyses for trends. Current: {len(_hist)}"
|
| 659 |
+
|
| 660 |
+
_thc = _Th7(_th)
|
| 661 |
+
|
| 662 |
+
with _fig_mgr(figsize=(12, 8)) as _f:
|
| 663 |
+
_gs = _f.add_gridspec(2, 1, hspace=0.3)
|
| 664 |
+
|
| 665 |
+
_idx = list(range(len(_hist)))
|
| 666 |
+
_pp = [_item['pos_prob'] for _item in _hist]
|
| 667 |
+
_confs = [_item['confidence'] for _item in _hist]
|
| 668 |
+
|
| 669 |
+
_ax1 = _f.add_subplot(_gs[0, 0])
|
| 670 |
+
_clr = [_thc._c['pos'] if _p > 0.5 else _thc._c['neg']
|
| 671 |
+
for _p in _pp]
|
| 672 |
+
_ax1.scatter(_idx, _pp, c=_clr, alpha=0.7, s=60)
|
| 673 |
+
_ax1.plot(_idx, _pp, alpha=0.5, linewidth=2)
|
| 674 |
+
_ax1.axhline(y=0.5, color='gray', linestyle='--', alpha=0.5)
|
| 675 |
+
_ax1.set_title('Sentiment History')
|
| 676 |
+
_ax1.set_ylabel('Positive Probability')
|
| 677 |
+
_ax1.grid(True, alpha=0.3)
|
| 678 |
+
|
| 679 |
+
_ax2 = _f.add_subplot(_gs[1, 0])
|
| 680 |
+
_ax2.bar(_idx, _confs, alpha=0.7, color='lightblue', edgecolor='navy')
|
| 681 |
+
_ax2.set_title('Confidence Over Time')
|
| 682 |
+
_ax2.set_xlabel('Analysis Number')
|
| 683 |
+
_ax2.set_ylabel('Confidence')
|
| 684 |
+
_ax2.grid(True, alpha=0.3)
|
| 685 |
+
|
| 686 |
+
_f.tight_layout()
|
| 687 |
+
return _f, f"History: {len(_hist)} analyses"
|
|
|
|
|
|
|
|
|
|
| 688 |
|
| 689 |
+
def _create_ui():
|
| 690 |
+
_app = _SA6()
|
|
|
|
|
|
|
| 691 |
|
| 692 |
+
with gr.Blocks(theme=gr.themes.Soft(), title="Movie Sentiment Analyzer") as _demo:
|
| 693 |
gr.Markdown("# 🎬 AI Movie Sentiment Analyzer")
|
| 694 |
gr.Markdown("Fast sentiment analysis with advanced deep learning explanations")
|
| 695 |
|
| 696 |
with gr.Tab("Quick Analysis"):
|
| 697 |
with gr.Row():
|
| 698 |
with gr.Column():
|
| 699 |
+
_ti = gr.Textbox(
|
| 700 |
label="Movie Review",
|
| 701 |
placeholder="Enter your movie review...",
|
| 702 |
lines=5
|
| 703 |
)
|
| 704 |
with gr.Row():
|
| 705 |
+
_ab = gr.Button("Analyze", variant="primary")
|
| 706 |
+
_ts = gr.Dropdown(
|
| 707 |
+
choices=list(_cfg._th.keys()),
|
| 708 |
value="default",
|
| 709 |
label="Theme"
|
| 710 |
)
|
| 711 |
|
| 712 |
gr.Examples(
|
| 713 |
+
examples=_app._ex,
|
| 714 |
+
inputs=_ti
|
| 715 |
)
|
| 716 |
|
| 717 |
with gr.Column():
|
| 718 |
+
_ro = gr.Textbox(label="Result", lines=3)
|
| 719 |
|
| 720 |
with gr.Row():
|
| 721 |
+
_pp = gr.Plot(label="Probabilities")
|
| 722 |
+
_gp = gr.Plot(label="Confidence")
|
| 723 |
|
| 724 |
with gr.Row():
|
| 725 |
+
_wp = gr.Plot(label="Word Cloud")
|
| 726 |
|
| 727 |
with gr.Tab("Advanced Analysis"):
|
| 728 |
with gr.Row():
|
| 729 |
with gr.Column():
|
| 730 |
+
_ati = gr.Textbox(
|
| 731 |
label="Movie Review",
|
| 732 |
placeholder="Enter your movie review for deep analysis...",
|
| 733 |
lines=5
|
| 734 |
)
|
| 735 |
with gr.Row():
|
| 736 |
+
_aab = gr.Button("Deep Analyze", variant="primary")
|
| 737 |
+
_ats = gr.Dropdown(
|
| 738 |
+
choices=list(_cfg._th.keys()),
|
| 739 |
value="default",
|
| 740 |
label="Theme"
|
| 741 |
)
|
| 742 |
|
| 743 |
gr.Examples(
|
| 744 |
+
examples=_app._ex,
|
| 745 |
+
inputs=_ati
|
| 746 |
)
|
| 747 |
|
| 748 |
with gr.Column():
|
| 749 |
+
_aro = gr.Textbox(label="Analysis Result", lines=4)
|
| 750 |
|
| 751 |
with gr.Row():
|
| 752 |
+
_lp = gr.Plot(label="LIME: Key Contributing Words")
|
| 753 |
+
_sp = gr.Plot(label="SHAP: Key Contributing Words")
|
| 754 |
|
| 755 |
with gr.Row():
|
| 756 |
+
_ho = gr.HTML(label="Word Importance Heatmap (LIME-based)")
|
| 757 |
|
| 758 |
with gr.Tab("Batch Analysis"):
|
| 759 |
with gr.Row():
|
| 760 |
with gr.Column():
|
| 761 |
+
_fu = gr.File(label="Upload File", file_types=[".csv", ".txt"])
|
| 762 |
+
_bi = gr.Textbox(
|
| 763 |
label="Reviews (one per line)",
|
| 764 |
lines=8
|
| 765 |
)
|
| 766 |
|
| 767 |
with gr.Column():
|
| 768 |
+
_lb = gr.Button("Load File")
|
| 769 |
+
_bb = gr.Button("Analyze Batch", variant="primary")
|
| 770 |
|
| 771 |
+
_bp = gr.Plot(label="Batch Results")
|
| 772 |
|
| 773 |
with gr.Tab("History & Export"):
|
| 774 |
with gr.Row():
|
| 775 |
+
_rb = gr.Button("Refresh")
|
| 776 |
+
_cb = gr.Button("Clear", variant="stop")
|
| 777 |
|
| 778 |
with gr.Row():
|
| 779 |
+
_csvb = gr.Button("Export CSV")
|
| 780 |
+
_jb = gr.Button("Export JSON")
|
| 781 |
+
|
| 782 |
+
_hs = gr.Textbox(label="Status")
|
| 783 |
+
_hp = gr.Plot(label="History Trends")
|
| 784 |
+
_csvf = gr.File(label="CSV Download", visible=True)
|
| 785 |
+
_jf = gr.File(label="JSON Download", visible=True)
|
| 786 |
+
|
| 787 |
+
_ab.click(
|
| 788 |
+
_app._fast_ana,
|
| 789 |
+
inputs=[_ti, _ts],
|
| 790 |
+
outputs=[_ro, _pp, _gp, _wp]
|
|
|
|
| 791 |
)
|
| 792 |
|
| 793 |
+
_aab.click(
|
| 794 |
+
_app._adv_ana,
|
| 795 |
+
inputs=[_ati, _ats],
|
| 796 |
+
outputs=[_aro, _lp, _sp, _ho]
|
|
|
|
| 797 |
)
|
| 798 |
|
| 799 |
+
_lb.click(_app._dh._proc, inputs=_fu, outputs=_bi)
|
| 800 |
+
_bb.click(_app._batch_ana, inputs=_bi, outputs=_bp)
|
|
|
|
| 801 |
|
| 802 |
+
_rb.click(
|
| 803 |
+
lambda _th: _app._hist_plot(_th),
|
| 804 |
+
inputs=_ts,
|
| 805 |
+
outputs=[_hp, _hs]
|
|
|
|
| 806 |
)
|
| 807 |
|
| 808 |
+
_cb.click(
|
| 809 |
+
lambda: f"Cleared {_app._hist._clr()} entries",
|
| 810 |
+
outputs=_hs
|
| 811 |
)
|
| 812 |
|
| 813 |
+
_csvb.click(
|
| 814 |
+
lambda: _app._dh._exp(_app._hist._get(), 'csv'),
|
| 815 |
+
outputs=[_csvf, _hs]
|
| 816 |
)
|
| 817 |
|
| 818 |
+
_jb.click(
|
| 819 |
+
lambda: _app._dh._exp(_app._hist._get(), 'json'),
|
| 820 |
+
outputs=[_jf, _hs]
|
| 821 |
)
|
| 822 |
|
| 823 |
+
return _demo
|
| 824 |
|
|
|
|
| 825 |
if __name__ == "__main__":
|
| 826 |
logging.basicConfig(level=logging.INFO)
|
| 827 |
+
_demo = _create_ui()
|
| 828 |
+
_demo.launch(share=True)
|