Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add button that finds missing OCR captions #32

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 51 additions & 2 deletions anki_ocr/gui.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,13 @@
logger = create_ocr_logger()


def on_run_ocr(browser: Browser):
def on_run_ocr(browser: Browser, nids=None):
time_start = time.time()

selected_nids = browser.selectedNotes()
if nids is None:
selected_nids = browser.selectedNotes()
else:
selected_nids = nids
config = mw.addonManager.getConfig(__name__)
num_notes = len(selected_nids)
num_batches = ceil(num_notes / config["batch_size"])
Expand Down Expand Up @@ -128,11 +131,57 @@ def on_menu_setup(browser: Browser):
act_rm_ocr_fields.triggered.connect(lambda b=browser: on_rm_ocr_fields(browser))
anki_ocr_menu.addAction(act_rm_ocr_fields)

act_missing_ocr = QAction(browser, text="Find missing captions")
act_missing_ocr.triggered.connect(lambda b=browser: find_missing_caption(browser, False))
anki_ocr_menu.addAction(act_missing_ocr)

act_auto_missing_ocr = QAction(browser, text="Run AnkiOCR on all missing captions")
act_auto_missing_ocr.triggered.connect(lambda b=browser: find_missing_caption(browser, True))
anki_ocr_menu.addAction(act_auto_missing_ocr)

browser_cards_menu = browser.form.menu_Cards
browser_cards_menu.addSeparator()
browser_cards_menu.addMenu(anki_ocr_menu)


def find_missing_caption(browser: Browser, OCR):
all_id_flds = mw.col.db.all("select id, mid, flds from notes")

id_missing_OCR = []
for aif in all_id_flds:
cid = aif[0]
f = aif[2].replace("\n", " ").replace("\r", " ")

found = f.count("<img ") - f.count(".svg") - f.count(".gif")
if found > 0:
title = f.count(" title=")
if found - title > 0:
id_missing_OCR.append(cid)

if id_missing_OCR:
if OCR is True:
on_run_ocr(browser, nids=id_missing_OCR) # OCR cards
return True
mw.requireReset()
try:
mw.col.tags.bulkAdd([x[0] for x in all_id_flds], "missing_OCR", False)
mw.col.tags.bulkAdd(id_missing_OCR, "missing_OCR", True)
except Exception as e:
print(f"Error: {e}")
finally:
mw.maybeReset()

browser.activateWindow()
browser.form.searchEdit.lineEdit().setText("tag:missing_OCR")
if hasattr(browser, 'onSearch'):
browser.onSearch()
else:
browser.onSearchActivated()

return True



def create_menu():
from anki.hooks import addHook
addHook("browser.setupMenus", on_menu_setup)