-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathexporters.py
More file actions
485 lines (413 loc) · 17.8 KB
/
exporters.py
File metadata and controls
485 lines (413 loc) · 17.8 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
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
import csv
import json
from datetime import datetime
from pathlib import Path
from typing import Any, Dict, List, Optional
def normalize_book(book: Dict[str, Any]) -> Dict[str, Any]:
"""
Normalize book data from API response to standard format.
Handles nested book objects and various field names.
Extracts comprehensive metadata for StoryGraph compatibility.
"""
# Handle None or invalid book objects
if not book or not isinstance(book, dict):
return {
"title": "",
"subtitle": "",
"authors": [],
"isbn": None,
"imprint": None,
"page_count": None,
"published_date": None,
"description": "",
"cover_image": "",
"genres": [],
"storygraph_genres": [],
"moods": [],
"content_warnings": [],
"status": None,
"rating": None,
"review": "",
"review_summary_liked": "",
"review_summary_disliked": "",
"review_summary_disagreed": "",
"contains_spoilers": None,
"did_not_finish": None,
"review_created_at": None,
"added_at": None,
"started_reading_at": "",
"finished_reading_at": "",
"current_page": None,
"total_pages": None,
"characters_rating": None,
"plot_rating": None,
"writing_style_rating": None,
"setting_rating": None,
"attributes": [],
"emoji_reaction": "",
"spicy_level": None,
}
# If book data is nested under 'book' key, extract it
book_data = book.get("book", book) if isinstance(book.get("book"), dict) else book
# Safely get authors
authors = book_data.get("authors") or book.get("authors") or []
if not isinstance(authors, list):
authors = []
# Extract genres
genres = []
if book_data.get("genres"):
genres = [g.get("name") for g in book_data.get("genres", []) if isinstance(g, dict) and g.get("name")]
# Extract StoryGraph tags (moods, content warnings)
storygraph_tags = book_data.get("storygraph_tags") or {}
moods = storygraph_tags.get("moods", []) if isinstance(storygraph_tags, dict) else []
content_warnings = storygraph_tags.get("content_warnings", []) if isinstance(storygraph_tags, dict) else []
storygraph_genres = storygraph_tags.get("genres", []) if isinstance(storygraph_tags, dict) else []
# Extract review summary
review_summary = book_data.get("review_summary") or {}
liked = review_summary.get("liked") if isinstance(review_summary, dict) else ""
disliked = review_summary.get("disliked") if isinstance(review_summary, dict) else ""
disagreed = review_summary.get("disagreed") if isinstance(review_summary, dict) else ""
# Extract reading progress
reading_progress = book_data.get("reading_progress") or {}
read_status = reading_progress.get("status") if isinstance(reading_progress, dict) else ""
current_page = reading_progress.get("current_page")
total_pages = reading_progress.get("page_count")
# Extract detailed ratings (from review if available)
characters_rating = book.get("characters_rating")
plot_rating = book.get("plot_rating")
writing_style_rating = book.get("writing_style_rating")
setting_rating = book.get("setting_rating")
# Extract attributes/labels
attributes = book.get("attributes", []) or []
if not isinstance(attributes, list):
attributes = []
attribute_names = [a.get("name") for a in attributes if isinstance(a, dict) and a.get("name")]
# Extract cover image URL
cover_image = book_data.get("cover_image") or ""
return {
"title": book_data.get("title") or book.get("title"),
"subtitle": book_data.get("subtitle") or "",
"authors": authors,
"isbn": book_data.get("isbn") or book.get("isbn"),
"imprint": book_data.get("publisher") or book_data.get("imprint") or book.get("publisher"),
"page_count": book_data.get("page_count") or book_data.get("pages") or book.get("page_count"),
"published_date": book_data.get("published_date") or book_data.get("publish_date") or book.get("published_date"),
"description": book_data.get("description") or "",
"cover_image": cover_image,
"genres": genres,
"storygraph_genres": storygraph_genres,
"moods": moods,
"content_warnings": content_warnings,
"status": read_status or book.get("status"),
"rating": book.get("rating"),
"review": book.get("review") or "",
"review_summary_liked": liked,
"review_summary_disliked": disliked,
"review_summary_disagreed": disagreed,
"contains_spoilers": book.get("contains_spoilers"),
"did_not_finish": book.get("did_not_finish"),
"review_created_at": book.get("review_created_at") or book.get("created_at"),
"added_at": book.get("added_at"),
"started_reading_at": book_data.get("started_reading_at") or "",
"finished_reading_at": book_data.get("finished_reading_at") or "",
"current_page": current_page,
"total_pages": total_pages,
"characters_rating": characters_rating,
"plot_rating": plot_rating,
"writing_style_rating": writing_style_rating,
"setting_rating": setting_rating,
"attributes": attribute_names,
"emoji_reaction": book.get("emoji_reaction") or (book.get("emoji") or {}).get("content") or "",
"spicy_level": book.get("spicy_level"),
}
def format_author_name(name: str) -> str:
"""Format author name for display."""
return name.strip() if name else ""
def format_authors_list(authors: List[Any]) -> str:
"""Convert authors list to comma-separated string."""
if not authors or not isinstance(authors, list):
return ""
author_names = []
for author in authors:
if isinstance(author, dict):
name = author.get("name", "")
elif isinstance(author, str):
name = author
else:
name = ""
if name:
author_names.append(name)
return ", ".join(author_names)
def extract_isbn(isbn: Optional[str]) -> tuple[str, str]:
"""Split ISBN into ISBN-10 and ISBN-13."""
if not isbn:
return "", ""
normalized = isbn.replace("-", "")
if len(normalized) == 10:
return normalized, ""
if len(normalized) == 13:
return "", normalized
return normalized, ""
def format_date(date_str: Optional[str]) -> str:
"""Convert ISO date to readable format."""
if not date_str:
return ""
try:
dt = datetime.fromisoformat(date_str.replace("Z", "+00:00"))
return dt.strftime("%Y-%m-%d")
except (ValueError, AttributeError):
return ""
def export_to_csv(books: List[Dict[str, Any]], output_path: Path) -> Path:
"""
Export books to CSV format with comprehensive metadata for StoryGraph.
Args:
books: List of book dictionaries
output_path: Path to write CSV file
Returns:
Path to created CSV file
"""
if not books:
raise ValueError("No books to export")
fieldnames = [
"Title",
"Subtitle",
"Author(s)",
"ISBN-10",
"ISBN-13",
"Publisher",
"Pages",
"Published Date",
"Genres",
"Moods",
"Content Warnings",
"Status",
"Rating",
"Characters Rating",
"Plot Rating",
"Writing Style Rating",
"Setting Rating",
"Review",
"Review Summary - Liked",
"Review Summary - Disliked",
"Review Summary - Disagreed",
"Attributes/Tags",
"Emoji Reaction",
"Contains Spoilers",
"Did Not Finish",
"Started Reading",
"Finished Reading",
"Date Added",
]
output_path.parent.mkdir(parents=True, exist_ok=True)
with open(output_path, "w", newline="", encoding="utf-8") as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
for book in books:
if book is None:
continue
book = normalize_book(book)
isbn10, isbn13 = extract_isbn(book.get("isbn"))
authors = book.get("authors", [])
row = {
"Title": book.get("title", ""),
"Subtitle": book.get("subtitle", ""),
"Author(s)": format_authors_list(authors),
"ISBN-10": isbn10,
"ISBN-13": isbn13,
"Publisher": book.get("imprint", ""),
"Pages": book.get("page_count", ""),
"Published Date": format_date(book.get("published_date")),
"Genres": "; ".join(book.get("genres", [])),
"Moods": "; ".join(book.get("moods", [])),
"Content Warnings": "; ".join(book.get("content_warnings", [])),
"Status": book.get("status", ""),
"Rating": book.get("rating", ""),
"Characters Rating": book.get("characters_rating", ""),
"Plot Rating": book.get("plot_rating", ""),
"Writing Style Rating": book.get("writing_style_rating", ""),
"Setting Rating": book.get("setting_rating", ""),
"Review": book.get("review", ""),
"Review Summary - Liked": book.get("review_summary_liked", ""),
"Review Summary - Disliked": book.get("review_summary_disliked", ""),
"Review Summary - Disagreed": book.get("review_summary_disagreed", ""),
"Attributes/Tags": "; ".join(book.get("attributes", [])),
"Emoji Reaction": book.get("emoji_reaction", ""),
"Contains Spoilers": "Yes" if book.get("contains_spoilers") else "No",
"Did Not Finish": "Yes" if book.get("did_not_finish") else "No",
"Started Reading": format_date(book.get("started_reading_at")),
"Finished Reading": format_date(book.get("finished_reading_at")),
"Date Added": format_date(
book.get("review_created_at")
or book.get("added_at")
or book.get("created_at")
),
}
writer.writerow(row)
return output_path
return output_path
def export_to_json(books: List[Dict[str, Any]], output_path: Path) -> Path:
"""
Export books to JSON format with comprehensive metadata for StoryGraph.
Args:
books: List of book dictionaries
output_path: Path to write JSON file
Returns:
Path to created JSON file
"""
if not books:
raise ValueError("No books to export")
output_path.parent.mkdir(parents=True, exist_ok=True)
# Clean up books for JSON export
clean_books = []
for book in books:
if book is None:
continue
book = normalize_book(book)
isbn10, isbn13 = extract_isbn(book.get("isbn"))
authors = book.get("authors", [])
clean_book = {
"title": book.get("title"),
"subtitle": book.get("subtitle"),
"authors": format_authors_list(authors),
"isbn10": isbn10,
"isbn13": isbn13,
"publisher": book.get("imprint"),
"pages": book.get("page_count"),
"published_date": format_date(book.get("published_date")),
"description": book.get("description"),
"cover_image": book.get("cover_image"),
"genres": book.get("genres"),
"moods": book.get("moods"),
"content_warnings": book.get("content_warnings"),
"status": book.get("status"),
"rating": float(book.get("rating")) if book.get("rating") else None,
"detailed_ratings": {
"characters": float(book.get("characters_rating")) if book.get("characters_rating") else None,
"plot": float(book.get("plot_rating")) if book.get("plot_rating") else None,
"writing_style": float(book.get("writing_style_rating")) if book.get("writing_style_rating") else None,
"setting": float(book.get("setting_rating")) if book.get("setting_rating") else None,
},
"review": book.get("review"),
"review_summary": {
"liked": book.get("review_summary_liked"),
"disliked": book.get("review_summary_disliked"),
"disagreed": book.get("review_summary_disagreed"),
},
"contains_spoilers": book.get("contains_spoilers"),
"did_not_finish": book.get("did_not_finish"),
"attributes": book.get("attributes"),
"emoji_reaction": book.get("emoji_reaction"),
"spicy_level": book.get("spicy_level"),
"started_reading": format_date(book.get("started_reading_at")),
"finished_reading": format_date(book.get("finished_reading_at")),
"current_page": book.get("current_page"),
"total_pages": book.get("total_pages"),
"date_added": format_date(
book.get("review_created_at")
or book.get("added_at")
or book.get("created_at")
),
}
clean_books.append(clean_book)
with open(output_path, "w", encoding="utf-8") as jsonfile:
json.dump(
clean_books, jsonfile, indent=2, ensure_ascii=False, default=str
)
return output_path
def export_to_markdown(books: List[Dict[str, Any]], output_path: Path) -> Path:
"""
Export books to Markdown format with comprehensive metadata for StoryGraph.
Args:
books: List of book dictionaries
output_path: Path to write Markdown file
Returns:
Path to created Markdown file
"""
if not books:
raise ValueError("No books to export")
output_path.parent.mkdir(parents=True, exist_ok=True)
lines = [
"# My Fable Book Library\n",
f"Exported on: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n",
f"Total books: {len(books)}\n",
"\n---\n",
]
# Group by status
by_status = {}
for book in books:
if book is None:
continue
book = normalize_book(book)
status = book.get("status", "unknown")
if status not in by_status:
by_status[status] = []
by_status[status].append(book)
status_order = ["finished", "reading", "unread"]
status_labels = {
"finished": "Finished",
"reading": "Currently Reading",
"unread": "Want to Read",
}
for status in status_order:
if status in by_status:
status_title = status_labels.get(status, status.title())
lines.append(f"\n## {status_title} ({len(by_status[status])})\n")
for book in by_status[status]:
title = book.get("title", "Unknown")
subtitle = book.get("subtitle", "")
authors = format_authors_list(book.get("authors", []))
rating = book.get("rating")
review = book.get("review")
genres = book.get("genres", [])
moods = book.get("moods", [])
attributes = book.get("attributes", [])
started = format_date(book.get("started_reading_at"))
finished = format_date(book.get("finished_reading_at"))
emoji = book.get("emoji_reaction", "")
# Detailed ratings
char_rating = book.get("characters_rating")
plot_rating = book.get("plot_rating")
writing_rating = book.get("writing_style_rating")
setting_rating = book.get("setting_rating")
lines.append(f"### {title}\n")
if subtitle:
lines.append(f"*{subtitle}*\n\n")
if authors:
lines.append(f"**Author(s):** {authors}\n")
if rating:
emoji_str = f" {emoji}" if emoji else ""
lines.append(f"**Rating:** {rating}/5{emoji_str}\n")
# Detailed ratings
has_detailed_ratings = any([char_rating, plot_rating, writing_rating, setting_rating])
if has_detailed_ratings:
lines.append(f"**Detailed Ratings:**\n")
if char_rating:
lines.append(f"- Characters: {char_rating}/5\n")
if plot_rating:
lines.append(f"- Plot: {plot_rating}/5\n")
if writing_rating:
lines.append(f"- Writing Style: {writing_rating}/5\n")
if setting_rating:
lines.append(f"- Setting: {setting_rating}/5\n")
if genres:
lines.append(f"**Genres:** {', '.join(genres)}\n")
if moods:
lines.append(f"**Moods:** {', '.join(moods)}\n")
if attributes:
lines.append(f"**Tags:** {', '.join(attributes)}\n")
if started or finished:
lines.append(f"**Read Dates:** ")
if started:
lines.append(f"Started {started}")
if finished:
if started:
lines.append(f" → Finished {finished}")
else:
lines.append(f"Finished {finished}")
lines.append("\n")
if review:
lines.append(f"\n**Review:**\n\n{review}\n")
lines.append("\n---\n")
with open(output_path, "w", encoding="utf-8") as mdfile:
mdfile.writelines(lines)
return output_path