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 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 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 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 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 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989
|
""" image_annotator_ollama_fixed_v2.py GUI (PyQt6) tool to analyze images using local Ollama llava:13b model. Features: - True local (offline) usage via localhost:11434 (Ollama) — no external network calls. - Preprocessing (thread pool) for base64/thumb generation. - Single-consumer queue for GPU inference (to avoid concurrent model OOM). - Robust parsing and improved prompt for rich, detailed descriptions. - Save/Load analysis progress (analysis_state.json in script dir). - SQLite DB to store results (Original Schema: rel_path, key, key_zh, descript, descript_zh, extra_json, updated_at). - Search and Stats tabs (with matplotlib bar chart for keyword ranking). - Stop/Resume, Save progress button. - Integrated local translation (Helsinki opus-mt or Ollama fallback). """
import os import subprocess import sys import io import json import time import base64 import sqlite3 import threading import traceback import platform from queue import Queue, Empty from concurrent.futures import ThreadPoolExecutor, as_completed from datetime import datetime from collections import Counter
import requests from PIL import Image, ImageFilter, ImageStat
try: from transformers import AutoModelForSeq2SeqLM, AutoTokenizer
HF_TRANSLATOR_AVAILABLE = True except Exception: HF_TRANSLATOR_AVAILABLE = False
from PyQt6.QtWidgets import ( QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, QLabel, QPushButton, QFileDialog, QListWidget, QListWidgetItem, QProgressBar, QTabWidget, QLineEdit, QTableWidget, QTableWidgetItem, QHeaderView, QMessageBox, QSpinBox, QSizePolicy ) from PyQt6.QtCore import Qt, QSize, QThread, pyqtSignal, QTimer from PyQt6.QtGui import QPixmap
from matplotlib.figure import Figure import numpy as np
try: from matplotlib.backends.backend_qt6agg import FigureCanvasQTAgg as FigureCanvas except ImportError: from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
OLLAMA_API_URL = "http://localhost:11434/api/generate" OLLAMA_MODEL = "llava:13b" OLLAMA_TIMEOUT = 120 OLLAMA_RETRIES = 2 HF_TRANSLATE_MODEL = "Helsinki-NLP/opus-mt-en-zh"
DB_FILE = os.path.join(os.path.dirname(__file__), "image_annotations.db") STATE_FILE = os.path.join(os.path.dirname(__file__), "analysis_state.json") THUMB_SIZE = (160, 90) SUPPORTED_EXT = {'.jpg', '.jpeg', '.png', '.bmp', '.gif', '.webp', '.tiff'} MAX_PREPROCESS_THREADS = 6
def clean_ollama_text(text): """ Attempts to clean up raw Ollama text output that might contain JSON or unwanted boilerplate/metadata, aiming to return only the natural language part. """ if not isinstance(text, str): return ""
cleaned_text = text
first_brace = cleaned_text.find('{', 10) if first_brace > -1 and first_brace < len( cleaned_text) / 2: cleaned_text = cleaned_text[:first_brace].strip()
if 'Keywords:' in cleaned_text: parts = cleaned_text.split("Keywords:", 1) description_part = parts[0].strip() first_brace_desc = description_part.find('{', len(description_part) // 2) if first_brace_desc > -1: description_part = description_part[:first_brace_desc].strip()
cleaned_text = description_part + (f" Keywords:{parts[1]}" if len(parts) > 1 else "")
cleaned_text = cleaned_text.strip()
if cleaned_text.startswith('"') and cleaned_text.endswith('"'): cleaned_text = cleaned_text.strip('"')
return cleaned_text
def init_db(path=DB_FILE): conn = sqlite3.connect(path, check_same_thread=False) cur = conn.cursor() cur.execute(''' CREATE TABLE IF NOT EXISTS images ( id INTEGER PRIMARY KEY AUTOINCREMENT, rel_path TEXT UNIQUE, key TEXT, key_zh TEXT, descript TEXT, descript_zh TEXT, extra_json TEXT, updated_at TEXT ) ''') conn.commit() return conn
DB_CONN = init_db()
def upsert_record(rel_path, descript_en, keywords_en_str, key_zh, descript_zh, extra_json_dict=None): now = datetime.utcnow().isoformat() cur = DB_CONN.cursor() cur.execute(''' INSERT INTO images(rel_path, key, key_zh, descript, descript_zh, extra_json, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?) ON CONFLICT(rel_path) DO UPDATE SET key =excluded.key, key_zh=excluded.key_zh, descript=excluded.descript, descript_zh=excluded.descript_zh, extra_json=excluded.extra_json, updated_at=excluded.updated_at ''', (rel_path, keywords_en_str, key_zh, descript_en, descript_zh, json.dumps(extra_json_dict or {}), now)) DB_CONN.commit()
def query_records_by_term(term): cur = DB_CONN.cursor() like = f"%{term}%" cur.execute( 'SELECT rel_path, key, key_zh, descript, descript_zh FROM images WHERE key LIKE ? OR key_zh LIKE ? OR descript LIKE ? OR descript_zh LIKE ?', (like, like, like, like)) return cur.fetchall()
def get_keyword_rank(limit=50): cur = DB_CONN.cursor() cur.execute('SELECT key FROM images') rows = cur.fetchall() counter = Counter() total = 0 for (k,) in rows: if not k: continue total += 1 for part in k.split(','): w = part.strip().lower() if w: counter[w] += 1 items = counter.most_common(limit) return items, total
def make_thumbnail(path, size=THUMB_SIZE): try: img = Image.open(path).convert("RGBA") img.thumbnail(size, Image.Resampling.LANCZOS) buf = io.BytesIO() img.save(buf, format='PNG') buf.seek(0) pix = QPixmap() pix.loadFromData(buf.read(), "PNG") return pix except Exception: return QPixmap()
def image_to_b64(path, max_dim=1024): img = Image.open(path).convert("RGB") w, h = img.size max_side = max(w, h) if max_side > max_dim: scale = max_dim / max_side img = img.resize((int(w * scale), int(h * scale)), Image.Resampling.LANCZOS) buf = io.BytesIO() img.save(buf, format='JPEG', quality=85) return base64.b64encode(buf.getvalue()).decode('utf-8')
class Translator: def __init__(self): self.hf_available = HF_TRANSLATOR_AVAILABLE self.model = None self.tokenizer = None if self.hf_available: try: print("Loading HF translator model (this may take time)...") self.tokenizer = AutoTokenizer.from_pretrained(HF_TRANSLATE_MODEL) self.model = AutoModelForSeq2SeqLM.from_pretrained(HF_TRANSLATE_MODEL) except Exception as e: print("HF translation model load failed, will fallback to Ollama. Error:", e) self.hf_available = False
def translate_en_to_zh(self, text): if not text: return "" if self.hf_available and self.model: try: inputs = self.tokenizer(text, return_tensors="pt", truncation=True, max_length=512) out = self.model.generate(**inputs, max_new_tokens=256) zh = self.tokenizer.decode(out[0], skip_special_tokens=True) return zh except Exception as e: print("HF translate failed, falling back to Ollama:", e)
prompt = f"Translate the following English text to Chinese (Simplified) preserving meaning and punctuation. Return only the translation.\n\nText:\n{text}\n\nTranslation:" payload = { "model": "gemma:2b", "prompt": prompt, "stream": False, } try: resp = requests.post(OLLAMA_API_URL, json=payload, timeout=20) resp.raise_for_status() j = resp.json() for k in ('output', 'text', 'result', 'response'): if k in j and isinstance(j[k], str): return j[k].strip().splitlines()[0] return str(j).strip() except Exception as e: print("Ollama fallback translate failed:", e) return ""
def call_ollama_model(base64_image, prompt_text, model=OLLAMA_MODEL, timeout=OLLAMA_TIMEOUT, retries=OLLAMA_RETRIES): """ Call local Ollama server with image base64 and prompt. Retries internally. Returns (success:bool, text:str) """
payload = { "model": model, "prompt": prompt_text, "stream": False, "images": [base64_image] } for attempt in range(retries + 1): try: resp = requests.post(OLLAMA_API_URL, json=payload, timeout=timeout) resp.raise_for_status()
try: j = resp.json() except Exception: txt = resp.text return True, txt
if isinstance(j, dict): for k in ('response', 'output', 'text', 'result'): if k in j and isinstance(j[k], str): return True, j[k] if 'choices' in j and isinstance(j['choices'], list) and j['choices']: ch = j['choices'][0] if isinstance(ch, dict) and 'message' in ch: return True, ch['message'].get('content', str(ch)) else: return True, str(ch) return True, json.dumps(j, ensure_ascii=False) else: return True, str(j)
except Exception as e: last_err = str(e) time.sleep(1 + attempt * 2) continue return False, f"Ollama request failed after {retries + 1} attempts: {last_err}"
class OllamaWorker(threading.Thread): def __init__(self, task_queue, result_callback, translator: Translator): super().__init__(daemon=True) self.q = task_queue self._stop = threading.Event() self.result_callback = result_callback self.translator = translator
def stop(self): self._stop.set()
def run(self): while not self._stop.is_set(): try: task = self.q.get(timeout=0.5) except Empty: continue
rel, b64, prompt = task success, text = call_ollama_model(b64, prompt)
keywords_en_str = "" descript_en = "" key_zh = "" descript_zh = ""
if success: cleaned_text = clean_ollama_text(text) print(f"1:cleaned text (before split): {cleaned_text[:200]}...")
descript_en = "" keywords_en_str = ""
keywords_delimiter = "Keywords:" index = -1
lower_cleaned_text = cleaned_text.lower() index = lower_cleaned_text.rfind(keywords_delimiter.lower())
if index != -1:
descript_en = cleaned_text[:index].strip() keywords_raw = cleaned_text[index + len(keywords_delimiter):].strip()
if not descript_en and keywords_raw: descript_en = "N/A: Model failed to provide rich description."
kws = [t.strip() for t in keywords_raw.split(',') if 2 <= len(t.strip()) <= 30] keywords_en_str = ",".join(kws[:8])
print(f"2:descript (after split): {descript_en[:50]}...") print(f"3:keywords (after split): {keywords_en_str[:50]}...")
else: descript_en = cleaned_text.strip() keywords_en_str = "" print( f"Warning: Keywords delimiter '{keywords_delimiter}' not found in model output for {rel}. Keywords will be empty. (Model failure to follow prompt)")
if keywords_en_str: key_zh = self.translator.translate_en_to_zh(keywords_en_str) if descript_en: descript_zh = self.translator.translate_en_to_zh(descript_en)
try: self.result_callback(rel, success, descript_en, keywords_en_str, key_zh, descript_zh) except Exception: traceback.print_exc() self.q.task_done()
class AnalyzerThread(QThread): sig_update = pyqtSignal(str, str) sig_progress = pyqtSignal(int, int) sig_done = pyqtSignal()
def __init__(self, root_dir, task_queue, main_window_ref): super().__init__() self.root_dir = root_dir self._stop = False self.task_queue = task_queue self.main_window_ref = main_window_ref
def request_stop(self): self._stop = True
def run(self): all_files = [] for dp, dns, fns in os.walk(self.root_dir): for fn in fns: if os.path.splitext(fn)[1].lower() in SUPPORTED_EXT: abs_path = os.path.join(dp, fn) rel = os.path.relpath(abs_path, self.root_dir) cur = DB_CONN.cursor() cur.execute('SELECT 1 FROM images WHERE rel_path=?', (rel,)) if cur.fetchone() is None: all_files.append((abs_path, rel))
total_remaining = len(all_files) processed_count = 0
preprocess_results = {} with ThreadPoolExecutor(max_workers=MAX_PREPROCESS_THREADS) as ex: future_to_rel = {ex.submit(image_to_b64, abs_path): rel for abs_path, rel in all_files} for fut in as_completed(future_to_rel): if self._stop: break rel = future_to_rel[fut] try: b64 = fut.result() preprocess_results[rel] = b64 except Exception as e: print(f"Preprocess failed for {rel}: {e}") preprocess_results[rel] = None
if self._stop: self.sig_done.emit() return
for abs_path, rel in all_files: if self._stop: self.sig_update.emit(rel, "Stopped") break
b64 = preprocess_results.get(rel) if not b64: self.sig_update.emit(rel, "Preprocess failed") processed_count += 1 self.sig_progress.emit(processed_count, total_remaining) continue
self.sig_update.emit(rel, "Queued")
prompt = ( "You are a detailed image analyst. For the supplied image, produce a multi-sentence, " "rich natural-language description that includes: people (approx. number, age group, clothing, pose, expression), " "objects, background/setting, lighting, colors, mood, and any notable details. " "Then provide a short comma-separated list of 5-10 keywords labeled 'Keywords:'. " "Return plain text only.\n\nExample:\nA young woman... \nKeywords: woman,smile,indoor,white-sweater,portrait" )
self.task_queue.put((rel, b64, prompt))
processed_count += 1 self.sig_progress.emit(processed_count, total_remaining)
self.task_queue.join()
if not self._stop: self.sig_progress.emit(total_remaining, total_remaining)
self.sig_done.emit()
class MainWindow(QMainWindow): def __init__(self): super().__init__() self.setWindowTitle("Image Annotator - llava:13b (Local Ollama)") self.setMinimumSize(1100, 700) self.root_dir = None self.translator = Translator()
self.task_queue = Queue() self.ollama_worker = OllamaWorker(self.task_queue, self.on_worker_result, self.translator) self.ollama_worker.start()
self.analyzer = None
tabs = QTabWidget() tabs.addTab(self.build_analysis_tab(), "Analysis") tabs.addTab(self.build_search_tab(), "Search") tabs.addTab(self.build_stats_tab(), "Stats") self.setCentralWidget(tabs)
self._check_load_state()
def _check_load_state(self): if os.path.exists(STATE_FILE): try: with open(STATE_FILE, 'r', encoding='utf-8') as f: st = json.load(f) if st.get('root_dir'): resp = QMessageBox.question(self, "Resume previous session", f"Found previous analysis state for directory:\n{st.get('root_dir')}\nLoad it?", QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No) if resp == QMessageBox.StandardButton.Yes: self.root_dir = st.get('root_dir') self.dir_label.setText(self.root_dir) self.populate_list_from_dir() except Exception: pass
def _save_basic_state(self, running=False): st = {"root_dir": self.root_dir, "running": running, "saved_at": datetime.utcnow().isoformat()} try: with open(STATE_FILE, 'w', encoding='utf-8') as f: json.dump(st, f, ensure_ascii=False, indent=2) except Exception: pass
def save_state(self): if not self.root_dir: QMessageBox.warning(self, "No dir", "Select directory first") return self._save_basic_state(running=False) QMessageBox.information(self, "Saved", f"Basic state saved to {STATE_FILE}")
def clear_db_prompt(self): ok = QMessageBox.question(self, "Clear DB", "This will delete all saved image analysis records. Continue?", QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No) if ok != QMessageBox.StandardButton.Yes: return cur = DB_CONN.cursor() cur.execute('DELETE FROM images') DB_CONN.commit() QMessageBox.information(self, "Cleared", "Database cleared.") self.populate_list_from_dir()
def build_analysis_tab(self): w = QWidget() v = QVBoxLayout() h = QHBoxLayout() self.dir_label = QLabel("No directory selected") btn_select = QPushButton("Select Directory") btn_select.clicked.connect(self.select_dir) self.btn_start = QPushButton("Start Analysis") self.btn_start.clicked.connect(self.start_analysis) self.btn_stop = QPushButton("Stop") self.btn_stop.clicked.connect(self.stop_analysis) self.btn_stop.setEnabled(False) btn_save = QPushButton("Save Progress") btn_save.clicked.connect(self.save_state) btn_clear = QPushButton("Clear DB") btn_clear.clicked.connect(self.clear_db_prompt)
h.addWidget(self.dir_label) h.addWidget(btn_select) h.addWidget(self.btn_start) h.addWidget(self.btn_stop) h.addWidget(btn_save) h.addWidget(btn_clear) v.addLayout(h)
self.progress = QProgressBar() v.addWidget(self.progress)
self.list_widget = QListWidget() v.addWidget(self.list_widget, 1)
w.setLayout(v) return w
def select_dir(self): d = QFileDialog.getExistingDirectory(self, "Select root image directory", os.path.expanduser("~")) if not d: return self.root_dir = d self.dir_label.setText(d) self.populate_list_from_dir() self._save_basic_state()
def populate_list_from_dir(self): self.list_widget.clear() if not self.root_dir: return for dp, dns, fns in os.walk(self.root_dir): for fn in fns: if os.path.splitext(fn)[1].lower() in SUPPORTED_EXT: rel = os.path.relpath(os.path.join(dp, fn), self.root_dir) cur = DB_CONN.cursor() cur.execute('SELECT 1 FROM images WHERE rel_path=?', (rel,)) has = cur.fetchone() is not None status = "Done" if has else "Pending" self.list_widget.addItem(f"{rel} - {status}")
def start_analysis(self): if not self.root_dir: QMessageBox.warning(self, "No directory", "Please select an image directory first.") return try: r = requests.get(OLLAMA_API_URL.replace('/api/generate', '/api/tags'), timeout=3) r.raise_for_status() except Exception as e: QMessageBox.critical(self, "Ollama unreachable", f"Cannot reach Ollama at {OLLAMA_API_URL.replace('/api/generate', '')}.\nStart Ollama server and ensure model {OLLAMA_MODEL} is loaded.\nError: {e}") return
self.btn_start.setEnabled(False) self.btn_stop.setEnabled(True) self.populate_list_from_dir()
self.analyzer = AnalyzerThread(self.root_dir, self.task_queue, self) self.analyzer.sig_update.connect(self.on_analyzer_update) self.analyzer.sig_progress.connect(self.on_analyzer_progress) self.analyzer.sig_done.connect(self.on_analyzer_done) self.analyzer.start() self._save_basic_state(running=True)
def stop_analysis(self): if self.analyzer: self.analyzer.request_stop()
QTimer.singleShot(500, self._finalize_stop)
def _finalize_stop(self): self.btn_stop.setEnabled(False) self.btn_start.setEnabled(True) self._save_basic_state(running=False)
def on_analyzer_update(self, rel, status): for i in range(self.list_widget.count()): it = self.list_widget.item(i) if it.text().startswith(rel + " -"): it.setText(f"{rel} - {status}") return self.list_widget.addItem(f"{rel} - {status}")
def on_analyzer_progress(self, processed, total): if total: self.progress.setValue(int(processed * 100 / total)) else: self.progress.setValue(0)
def _open_file_in_system(self, file_path): """使用系统默认应用打开文件(跨平台兼容)。""" if not os.path.exists(file_path): QMessageBox.warning(self, "File Not Found", f"Image file not found at: {file_path}") return
system = platform.system() try: if system == "Windows": os.startfile(file_path) elif system == "Darwin": subprocess.run(["open", file_path], check=True) else: subprocess.run(["xdg-open", file_path], check=True) except Exception as e: QMessageBox.critical(self, "Open Failed", f"Could not open file {file_path}. Error: {e}")
def open_image_from_row(self, row, column): """处理表格双击事件,打开图片文件。""" if hasattr(self, '_search_results_rel_paths') and row < len(self._search_results_rel_paths): rel = self._search_results_rel_paths[row] if self.root_dir: abs_path = os.path.join(self.root_dir, rel) self._open_file_in_system(abs_path) else: QMessageBox.warning(self, "Error", "根目录未设置 (Root directory is not set).") else: QMessageBox.warning(self, "Error", "无法获取文件路径 (Could not retrieve file path for this row).")
def on_analyzer_done(self): QMessageBox.information(self, "Analysis", "Analysis finished or stopped.") self.btn_start.setEnabled(True) self.btn_stop.setEnabled(False) self._save_basic_state(running=False) self.progress.setValue(100) self.populate_list_from_dir()
def on_worker_result(self, rel, success, descript_en, keywords_en_str, key_zh, descript_zh): try: upsert_record(rel, descript_en, keywords_en_str, key_zh, descript_zh, {"raw_ollama": descript_en, "keywords": keywords_en_str.split(',')}) except Exception as e: print("DB save error:", e) traceback.print_exc()
status = "Done" if success else "Failed" QTimer.singleShot(0, lambda: self.on_analyzer_update(rel, status))
print(f"[Worker] {rel} -> {'OK' if success else 'ERR'}")
def build_search_tab(self): w = QWidget() v = QVBoxLayout() h = QHBoxLayout() self.search_input = QLineEdit() self.search_input.setPlaceholderText("Enter keyword or text (English or Chinese), press Enter to search") self.search_input.returnPressed.connect(self.perform_search) btn = QPushButton("Search") btn.clicked.connect(self.perform_search) h.addWidget(self.search_input) h.addWidget(btn) v.addLayout(h)
self.table = QTableWidget(0, 5) self.table.setHorizontalHeaderLabels( ["Thumbnail", "Filename", "Keywords (EN/ZH)", "Description (EN)", "Description (ZH)"]) self.table.verticalHeader().setVisible(False) self.table.setWordWrap(True)
self.table.cellDoubleClicked.connect(self.open_image_from_row)
self.table.horizontalHeader().setSectionResizeMode(0, QHeaderView.ResizeMode.Fixed) self.table.horizontalHeader().setSectionResizeMode(1, QHeaderView.ResizeMode.Fixed) self.table.horizontalHeader().setSectionResizeMode(2, QHeaderView.ResizeMode.Fixed) self.table.horizontalHeader().setSectionResizeMode(3, QHeaderView.ResizeMode.Stretch) self.table.horizontalHeader().setSectionResizeMode(4, QHeaderView.ResizeMode.Stretch)
self.table.setColumnWidth(0, 180) self.table.horizontalHeader().setStretchLastSection(True)
v.addWidget(self.table, 1) w.setLayout(v) return w
def perform_search(self): term = self.search_input.text().strip() if not term: QMessageBox.information(self, "Empty", "Enter a search term.") return
rows = query_records_by_term(term) self.table.setRowCount(0)
self._search_results_rel_paths = []
for rel, key_en, key_zh, desc_en, desc_zh in rows: self._search_results_rel_paths.append(rel)
r = self.table.rowCount() self.table.insertRow(r)
abs_path = os.path.join(self.root_dir or os.path.expanduser("~"), rel) pix = make_thumbnail(abs_path) lbl = QLabel() lbl.setPixmap(pix.scaled(QSize(160, 90), Qt.AspectRatioMode.KeepAspectRatio, Qt.TransformationMode.SmoothTransformation)) self.table.setCellWidget(r, 0, lbl) self.table.setRowHeight(r, 100)
self.table.setItem(r, 1, QTableWidgetItem(os.path.basename(rel)))
keywords_text = f"EN: {key_en or 'N/A'}\nZH: {key_zh or 'N/A'}" item_key = QTableWidgetItem(keywords_text) item_key.setTextAlignment(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter) self.table.setItem(r, 2, item_key)
item_desc_en = QTableWidgetItem(desc_en or 'N/A') item_desc_en.setTextAlignment(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignTop) self.table.setItem(r, 3, item_desc_en)
item_desc_zh = QTableWidgetItem(desc_zh or 'N/A') item_desc_zh.setTextAlignment(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignTop) self.table.setItem(r, 4, item_desc_zh)
self.table.resizeRowToContents(r)
def build_stats_tab(self): w = QWidget() v = QVBoxLayout() h = QHBoxLayout() h.addWidget(QLabel("Top N")) self.spin_top = QSpinBox() self.spin_top.setRange(5, 200) self.spin_top.setValue(30) btn_refresh = QPushButton("Refresh Stats") btn_refresh.clicked.connect(self.refresh_stats) btn_export = QPushButton("Export CSV") btn_export.clicked.connect(self.export_stats) h.addWidget(self.spin_top) h.addWidget(btn_refresh) h.addWidget(btn_export) v.addLayout(h)
self.fig = Figure(figsize=(6, 3)) self.canvas = FigureCanvas(self.fig) v.addWidget(self.canvas, 1) w.setLayout(v) return w
def refresh_stats(self): topn = self.spin_top.value() items, total = get_keyword_rank(limit=topn)
kws = [k for k, c in items] counts = [c for k, c in items]
self.fig.clear() ax = self.fig.add_subplot(111)
y_pos = np.arange(len(kws)) ax.barh(y_pos, counts) ax.set_yticks(y_pos) ax.set_yticklabels(kws, fontsize=8) ax.invert_yaxis() ax.set_xlabel("Count") ax.set_title(f"Top {len(kws)} keywords (total images indexed: {total})")
self.fig.tight_layout() self.canvas.draw()
def export_stats(self): topn = self.spin_top.value() items, total = get_keyword_rank(limit=topn)
path, _ = QFileDialog.getSaveFileName(self, "Save CSV", os.path.expanduser("~"), "CSV files (*.csv)") if not path: return
try: with open(path, 'w', encoding='utf-8') as f: f.write("keyword,count\n") for k, c in items: f.write(f'"{k}",{c}\n') QMessageBox.information(self, "Saved", f"Saved to {path}") except Exception as e: QMessageBox.warning(self, "Export failed", f"Failed: {e}")
def closeEvent(self, event): self.ollama_worker.stop() self.ollama_worker.join() if self.analyzer and self.analyzer.isRunning(): self.analyzer.request_stop() self.analyzer.wait() DB_CONN.close() super().closeEvent(event)
def main(): app = QApplication(sys.argv) try: if FigureCanvas.__name__ == 'FigureCanvasQTAgg': print("Using Matplotlib with PyQt6 backend.") except Exception: print("Matplotlib backend check failed.")
mw = MainWindow() mw.show() sys.exit(app.exec())
if __name__ == "__main__": main()
|