Here's the final code structured as a proper Anki add-on with manifest and Python files. This version uses Yandex Images via SerpApi with caching, threading, and UI improvements.
📁 Folder Structure
YandexImageSearch/
├── __init__.py
├── manifest.json
✅ manifest.json (Add-on Metadata)
{
"package": "YandexImageSearch",
"name": "Yandex Image Search for Anki",
"version": "1.0",
"author": "Your Name",
"homepage": "https://example.com",
"description": "Search Yandex Images for selected text and insert into Anki notes",
"supported_api_version": 6
}
🐍 __init__.py (Main Code)
# File: YandexImageSearch/__init__.py
from aqt import mw
from aqt.editor import Editor
from aqt.utils import showInfo, tooltip, getText
from PyQt5.QtWidgets import QAction, QDialog, QVBoxLayout, QLabel, QPushButton, QHBoxLayout, QComboBox
from PyQt5.QtGui import QPixmap, QCursor
from PyQt5.QtCore import Qt, QThread, pyqtSignal
import requests
from io import BytesIO
import json
import os
import tempfile
# Configuration (requires SerpApi key)
SERP_API_KEY = "YOUR_API_KEY_HERE" # Replace with your SerpApi key
CACHE_DIR = os.path.join(tempfile.gettempdir(), "anki_yandex_image_cache")
# Ensure cache directory exists
os.makedirs(CACHE_DIR, exist_ok=True)
class ImageSearchWorker(QThread):
finished = pyqtSignal(list)
def __init__(self, query):
super().__init__()
self.query = query
def run(self):
"""Background thread to fetch images from Yandex via SerpApi"""
if not SERP_API_KEY or SERP_API_KEY == "YOUR_API_KEY_HERE":
tooltip("Please configure your SerpApi API key")
self.finished.emit([])
return
# Use cached results if available
cache_path = os.path.join(CACHE_DIR, f"{self.query}.json")
if os.path.exists(cache_path):
try:
with open(cache_path, "r") as f:
self.finished.emit(json.load(f))
return
except Exception:
pass
# Build request
params = {
"api_key": SERP_API_KEY,
"engine": "yandex_images",
"text": self.query,
"num": 10
}
try:
response = requests.get("https://serpapi.com/search", params=params, timeout=15)
data = response.json()
image_urls = [img.get("original") for img in data.get("images_results", [])[:10]]
# Save to cache
with open(cache_path, "w") as f:
json.dump(image_urls, f)
self.finished.emit(image_urls)
except Exception as e:
tooltip(f"Image search error: {str(e)}")
self.finished.emit([])
class ImageSearchDialog(QDialog):
def __init__(self, images, fields, parent=None):
super().__init__(parent)
self.images = images
self.current_idx = 0
self.fields = fields
self.initUI()
def initUI(self):
self.setWindowTitle('Yandex Image Search')
layout = QVBoxLayout()
layout.setSpacing(10)
# Field selection
self.field_selector = QComboBox()
self.field_selector.addItems(self.fields)
layout.addWidget(self.field_selector)
# Image display
self.image_label = QLabel()
self.image_label.setFixedSize(300, 300)
self.image_label.setAlignment(Qt.AlignCenter)
self.image_label.setStyleSheet("border: 1px solid #ccc;")
layout.addWidget(self.image_label, alignment=Qt.AlignCenter)
# Navigation buttons
nav_layout = QHBoxLayout()
prev_btn = QPushButton("⬅️ Previous")
next_btn = QPushButton("Next ➡️")
prev_btn.clicked.connect(self.prev_image)
next_btn.clicked.connect(self.next_image)
nav_layout.addWidget(prev_btn)
nav_layout.addWidget(next_btn)
layout.addLayout(nav_layout)
# Status label
self.status_label = QLabel("Loading...")
self.status_label.setAlignment(Qt.AlignCenter)
layout.addWidget(self.status_label)
# Load first image
if self.images:
self.status_label.setText("")
self.load_current_image()
else:
self.status_label.setText("No images found")
self.setLayout(layout)
def load_current_image(self):
if not self.images:
return
image_url = self.images[self.current_idx]
try:
response = requests.get(image_url, timeout=5)
img_data = BytesIO(response.content)
pixmap = QPixmap()
pixmap.loadFromData(img_data.getvalue())
self.image_label.setPixmap(pixmap.scaled(
self.image_label.size(),
aspectRatioMode=Qt.KeepAspectRatio
))
except Exception as e:
self.status_label.setText(f"Error loading image\n{str(e)}")
def prev_image(self):
if self.current_idx > 0:
self.current_idx -= 1
self.status_label.setText("")
self.load_current_image()
def next_image(self):
if self.current_idx < len(self.images) - 1:
self.current_idx += 1
self.status_label.setText("")
self.load_current_image()
def on_insert_image(editor):
selected_text = editor.web.selectedText().strip()
if not selected_text:
showInfo("Please select some text to search for images")
return
# Get note fields
model = editor.note.model()
fields = mw.col.models.fieldNames(model)
# Create worker thread for search
worker = ImageSearchWorker(selected_text)
dialog = ImageSearchDialog([], fields, editor.parentWindow)
dialog.setWindowTitle("Searching Yandex Images...")
dialog.status_label.setText("Searching...")
dialog.show()
def on_search_complete(images):
dialog.setWindowTitle("Yandex Image Search")
dialog.images = images
if images:
dialog.status_label.setText("")
dialog.load_current_image()
else:
dialog.status_label.setText("No images found")
worker.finished.connect(on_search_complete)
worker.start()
if dialog.exec_():
selected_field = dialog.field_selector.currentText()
selected_url = images[dialog.current_idx]
editor.note[selected_field] = f'<img src="{selected_url}">'
editor.loadNote()
tooltip("Image inserted successfully!")
def setup_editor_button(editor):
action = QAction("🔍 Yandex Image Search", editor.widget)
action.setToolTip("Search Yandex Images for selected text")
action.triggered.connect(lambda: on_insert_image(editor))
editor.form.buttonBox.addButton(action, 0x0200)
from aqt.hooks import addHook
addHook("setupEditorButtons", setup_editor_button)
🧰 Installation Instructions
-
Create Add-on Folder
- On Anki desktop:
Tools > Add-ons > Open Add-ons Folder
- Create a new folder named
YandexImageSearch
-
Copy Files
- Place both
__init__.py and manifest.json into the YandexImageSearch folder
-
Install Dependencies
pip install google-search-results
-
Configure API Key
- Replace
"YOUR_API_KEY_HERE" in __init__.py with your actual SerpApi key
-
Restart Anki
📝 Usage
- Select text in the Anki editor
- Click the new 🔍 Yandex Image Search button
- Choose a field to insert the image
- Navigate images with Previous/Next buttons
- Click OK to insert the selected image
💡 Notes
- Free Tier: SerpApi provides 100 free searches/month
- Caching: Search results are cached to reduce API usage
- Threaded Search: Prevents Anki from freezing during image loading
- Error Handling: Gracefully handles network issues and missing results
Let me know if you'd like a version using Unsplash, Bing, or local image search instead!