-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path__init__.py
More file actions
144 lines (108 loc) · 4.34 KB
/
Copy path__init__.py
File metadata and controls
144 lines (108 loc) · 4.34 KB
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
import json
import os
import threading
from flask import Flask, request, jsonify
from aqt import mw, gui_hooks
from anki.notes import Note
app = Flask(__name__)
def create_note_type_if_not_exists():
model_name = "Basic with videos in answers"
model = mw.col.models.by_name(model_name)
if not model:
model = mw.col.models.new(model_name)
# Add fields
fields = ["Front", "videos", "backand"]
for field_name in fields:
fld = mw.col.models.new_field(field_name)
mw.col.models.add_field(model, fld)
# Add template
tmpl = mw.col.models.new_template("Card 1")
tmpl['qfmt'] = "{{Front}}"
tmpl['afmt'] = "{{Front}}<hr id=answer>{{videos}}<br>{{backand}}" # Simple template to show videos in answer
mw.col.models.add_template(model, tmpl)
mw.col.models.add(model)
mw.col.models.save(model)
return model
@app.route('/add_card', methods=['POST'])
def add_card():
data = request.json
deck_name = data.get('deck_name')
word = data.get('word')
part_of_speech = data.get('part_of_speech')
variants = data.get('variants')
tags = data.get('tags', []) # Optional list of tags
if not all([deck_name, word, variants]):
return jsonify({"error": "Missing data"}), 400
is_success = True
error_msg = "[no error]"
def perform_add():
nonlocal is_success, error_msg
#is_success = False
#error_msg = f"error"
#return
# Create or get note type
model = create_note_type_if_not_exists()
# Get or create deck
did = mw.col.decks.id(deck_name)
# Create note
note = Note(mw.col, model)
count_str= f' <span style="color: green">({len(variants)})' if len(variants)>1 else ""
part_of_speech_str = f'<span style="color: gray">({part_of_speech})</span>' if part_of_speech!="other" else ""
note["Front"] = f'<b>{word}</b> {part_of_speech_str}{count_str} '
# Process videos: Add to media and build HTML for videos field
videos_html = []
for var in variants:
file_name = var.get('file')
if not file_name:
is_success = False
error_msg = f"Missing file name in variant"
return
if not mw.col.media.have(file_name):
is_success = False
error_msg = f"Video file '{file_name}' not found in Anki media collection"
return
# Add file to Anki media
#media_name = os.path.basename(file_path)
#mw.col.media.add_file(file_path)
# Build <video> tag with start time
#start = var.get('start', 0)
video_tag = f'[sound:{file_name}]'
videos_html.append(video_tag)
note["videos"] = "".join(videos_html)
def escape_quotes(obj):
if isinstance(obj, str):
return obj.replace('\\', r'\\').replace('"', r'\"')
elif isinstance(obj, list):
return [escape_quotes(v) for v in obj]
elif isinstance(obj, dict):
return {k: escape_quotes(v) for k, v in obj.items()}
else:
return obj
# backand: JSON of variants
note["Back"] = json.dumps(escape_quotes(variants))
# Assign deck
note.note_type()['did'] = did
if tags and isinstance(tags, list):
note.tags.extend(tags)
# Add note to collection
try:
mw.col.add_note(note, did)
mw.col.save()
except Exception as e:
is_success = False
error_msg = f"Failed to add note: {str(e)}"
# Run the addition on the main thread to avoid thread-safety issues
perform_add()
#mw.taskman.run_on_main(perform_add)
if not is_success:
return jsonify({"success": False, "error": error_msg}), 400 if "file name" in error_msg else 500
return jsonify({"success": True}), 200
def run_server():
app.run(port=5001, debug=True, use_reloader=False)
# Start the server in a background thread when the add-on loads
thread = threading.Thread(target=run_server, daemon=True)
thread.start()
# Optional: Hook to ensure note type is created on Anki startup
def on_profile_loaded():
create_note_type_if_not_exists()
gui_hooks.profile_did_open.append(on_profile_loaded)