Release Bard v2.0.0 (Interactive taste wizard, dual-stanza translation, SQLite FTS5)
This commit is contained in:
+35
-15
@@ -7,39 +7,59 @@
|
|||||||
"cli": {
|
"cli": {
|
||||||
"usage": "Usage: bard [command] [options]",
|
"usage": "Usage: bard [command] [options]",
|
||||||
"commands_title": "Commands:",
|
"commands_title": "Commands:",
|
||||||
"cmd_random": "Display a random poem matching your current taste configuration",
|
"cmd_random": "Display a curated poem matching your personalized poetic taste",
|
||||||
"cmd_config": "View or update poet filtering preferences and auto-save settings",
|
"cmd_taste": "Launch interactive taste onboarding wizard to calibrate literary preferences",
|
||||||
|
"cmd_config": "View or update poet filtering preferences and display settings",
|
||||||
"cmd_library": "Browse and read poems saved in your offline library",
|
"cmd_library": "Browse and read poems saved in your offline library",
|
||||||
"cmd_search": "Search poems by title, poet, or verse content",
|
"cmd_search": "Search poems by title, poet, theme, or verse content using FTS5",
|
||||||
"options_title": "Options:",
|
"options_title": "Options:",
|
||||||
"opt_help": "Show this help message and exit",
|
"opt_help": "Show this help message and exit",
|
||||||
"opt_version": "Show version information and exit",
|
"opt_version": "Show version information and exit",
|
||||||
"opt_lang": "Filter by nationality / language (e.g. english, turkish, persian, all)",
|
"opt_lang": "Filter by nationality / tradition (e.g. turkish, divan, persian, english, french, german, japanese, all)",
|
||||||
"opt_era": "Filter by historical century / era (e.g. 13th, 16th, 19th, 20th, all)",
|
"opt_era": "Filter by historical century / era (e.g. 13th, 16th, 19th, 20th, all)",
|
||||||
"opt_min_rating": "Filter by popularity score threshold (1 to 5)",
|
"opt_theme": "Filter by emotional theme (e.g. love, mysticism, solitude, melancholy, nature, all)",
|
||||||
|
"opt_mode": "Display mode: dual (original + translation), translated, or original",
|
||||||
"opt_save_toggle": "Enable or disable auto-saving viewed poems (on/off)",
|
"opt_save_toggle": "Enable or disable auto-saving viewed poems (on/off)",
|
||||||
"opt_interactive": "Launch interactive configuration wizard"
|
"opt_interactive": "Launch interactive configuration wizard"
|
||||||
},
|
},
|
||||||
|
"wizard": {
|
||||||
|
"welcome_header": "======================================================================\n GRAVITINY BARD: POETIC TASTE SETUP\n======================================================================",
|
||||||
|
"intro": "Welcome to Bard. Let us discover your poetic inclinations to provide\nimmediate solace and literary depth during your terminal sessions.",
|
||||||
|
"step_lang_title": "[1/4] PRIMARY READING & DISPLAY PREFERENCE",
|
||||||
|
"prompt_display_mode": "Select display mode (1: Dual Parallel [Original + Translation], 2: Translation Only, 3: Original Only) [1]: ",
|
||||||
|
"step_era_title": "[2/4] HISTORICAL EPOCHS & ERAS",
|
||||||
|
"prompt_era": "Select era (1: All Eras, 2: Classical & Medieval [Divan/Sufi], 3: Romanticism & 19th C, 4: 20th C & Modernism) [1]: ",
|
||||||
|
"step_tradition_title": "[3/4] GEOGRAPHIC & LINGUISTIC TRADITIONS",
|
||||||
|
"prompt_tradition": "Select literary tradition (1: Pan-Global/All, 2: Ottoman & Turkish, 3: Persian & Sufi, 4: English & British, 5: French & Continental, 6: East Asian/Haiku) [1]: ",
|
||||||
|
"step_theme_title": "[4/4] EMOTIONAL & PHILOSOPHICAL THEMES",
|
||||||
|
"prompt_theme": "Select primary thematic resonance (1: All Themes, 2: Mysticism & Existence, 3: Love & Longing, 4: Solitude & Melancholy, 5: Nature & Contemplation) [1]: ",
|
||||||
|
"setup_complete": "Taste profile calibrated successfully. Welcome to Bard.\n"
|
||||||
|
},
|
||||||
"config": {
|
"config": {
|
||||||
"status_header": "Current Bard Taste & Archival Configuration:",
|
"status_header": "Current Bard Taste & Archival Configuration:",
|
||||||
"field_lang": "Language / Nationality",
|
"field_display_mode": "Display Mode",
|
||||||
|
"field_lang": "Literary Tradition",
|
||||||
"field_era": "Century / Era",
|
"field_era": "Century / Era",
|
||||||
|
"field_theme": "Thematic Focus",
|
||||||
"field_rating": "Popularity Score (1-5)",
|
"field_rating": "Popularity Score (1-5)",
|
||||||
"field_auto_save": "Auto-Save to Offline Library",
|
"field_auto_save": "Auto-Save to Offline Library",
|
||||||
"updated": "Configuration successfully updated.",
|
"updated": "Configuration successfully updated."
|
||||||
"prompt_lang": "Enter preferred nationality/language (e.g. english, turkish, persian, all): ",
|
|
||||||
"prompt_era": "Enter preferred century/era (e.g. 13th, 16th, 19th, 20th, all): ",
|
|
||||||
"prompt_rating": "Enter minimum popularity rating (1-5): ",
|
|
||||||
"prompt_save": "Enable auto-saving viewed poems for offline reading? (y/N): "
|
|
||||||
},
|
},
|
||||||
"library": {
|
"library": {
|
||||||
"empty": "No saved poems in your offline library. Enable auto-save in config or use 'bard config --save on'.",
|
"empty": "No saved poems in your offline library. Use 'bard' with auto-save enabled or 'bard config --save on'.",
|
||||||
"saved_header": "Offline Saved Poetry Library ({count} poems):",
|
"saved_header": "Offline Saved Poetry Library ({count} poems):",
|
||||||
"auto_saved_notice": "[Archived to Offline Library]",
|
"auto_saved_notice": "[Archived to Offline Library]",
|
||||||
"item_format": "[{id}] '{title}' by {author} ({era}, {nationality})"
|
"item_format": "[{id}] '{title}' by {author} ({era}, {nationality}) - Theme: {theme}"
|
||||||
|
},
|
||||||
|
"search": {
|
||||||
|
"prompt_query": "Enter search query (poet, title, or verse line): ",
|
||||||
|
"results_header": "Found {count} matching poem(s) for '{query}':",
|
||||||
|
"no_results": "No poems matched your search query '{query}'."
|
||||||
},
|
},
|
||||||
"display": {
|
"display": {
|
||||||
"no_poems_matched": "No poems matched your current filter criteria (Lang: {lang}, Era: {era}, Rating >= {rating}). Showing diverse classical selection.",
|
"no_poems_matched": "No poems matched your exact filter criteria. Showing a masterwork from world literature.",
|
||||||
"footer_meta": "Poet: {author} | Era: {era} | Origin: {nationality} | Popularity: {rating}/5"
|
"original_label": "ORIGINAL TEXT",
|
||||||
|
"translation_label": "LITERARY TRANSLATION (GUNUMUZ TURKCESI / ENGLISH)",
|
||||||
|
"context_label": "CONTEXT & EPIGRAPH"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+4
-4
@@ -1,13 +1,13 @@
|
|||||||
{
|
{
|
||||||
"id": "bard",
|
"id": "bard",
|
||||||
"name": "Bard",
|
"name": "Bard",
|
||||||
"version": "1.0.1",
|
"version": "2.0.0",
|
||||||
"description": "Wikidata & Wikisource random poetry discovery engine with taste filtering and offline caching.",
|
"description": "Interactive poetic discovery & taste curation engine with dual-stanza literary translations and SQLite FTS5 index.",
|
||||||
"author": "Simon the Coder <simon@luxhebros.com>",
|
"author": "Simon the Coder <simon@luxhebros.com>",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"runtime": "python",
|
"runtime": "python",
|
||||||
"entrypoint": "main.py",
|
"entrypoint": "main.py",
|
||||||
"shims": ["bard", "poem"],
|
"shims": ["bard", "poem"],
|
||||||
"tags": ["poetry", "literature", "wikidata", "wikisource", "culture", "offline"],
|
"tags": ["poetry", "literature", "curation", "dual-stanza", "translation", "fts5", "culture", "offline"],
|
||||||
"network": "online"
|
"network": "offline"
|
||||||
}
|
}
|
||||||
|
|||||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+66
-35
@@ -5,6 +5,7 @@ from src.catalog import catalog
|
|||||||
from src.config import ConfigManager, UserTasteConfig
|
from src.config import ConfigManager, UserTasteConfig
|
||||||
from src.db import PoetryRepository
|
from src.db import PoetryRepository
|
||||||
from src.renderer import PoemRenderer
|
from src.renderer import PoemRenderer
|
||||||
|
from src.wizard import TasteWizard
|
||||||
|
|
||||||
|
|
||||||
def print_help() -> None:
|
def print_help() -> None:
|
||||||
@@ -14,14 +15,18 @@ def print_help() -> None:
|
|||||||
print()
|
print()
|
||||||
print(catalog.get("cli.commands_title"))
|
print(catalog.get("cli.commands_title"))
|
||||||
print(f" random {catalog.get('cli.cmd_random')}")
|
print(f" random {catalog.get('cli.cmd_random')}")
|
||||||
|
print(f" taste, wizard {catalog.get('cli.cmd_taste')}")
|
||||||
|
print(f" search <query> {catalog.get('cli.cmd_search')}")
|
||||||
print(f" config {catalog.get('cli.cmd_config')}")
|
print(f" config {catalog.get('cli.cmd_config')}")
|
||||||
print(f" library, saved {catalog.get('cli.cmd_library')}")
|
print(f" library, saved {catalog.get('cli.cmd_library')}")
|
||||||
print()
|
print()
|
||||||
print(catalog.get("cli.options_title"))
|
print(catalog.get("cli.options_title"))
|
||||||
print(f" -h, --help {catalog.get('cli.opt_help')}")
|
print(f" -h, --help {catalog.get('cli.opt_help')}")
|
||||||
print(f" -V, --version {catalog.get('cli.opt_version')}")
|
print(f" -V, --version {catalog.get('cli.opt_version')}")
|
||||||
|
print(f" --mode <dual|trans> {catalog.get('cli.opt_mode')}")
|
||||||
print(f" --lang <origin> {catalog.get('cli.opt_lang')}")
|
print(f" --lang <origin> {catalog.get('cli.opt_lang')}")
|
||||||
print(f" --era <century> {catalog.get('cli.opt_era')}")
|
print(f" --era <century> {catalog.get('cli.opt_era')}")
|
||||||
|
print(f" --theme <theme> {catalog.get('cli.opt_theme')}")
|
||||||
print(f" --rating <1-5> {catalog.get('cli.opt_min_rating')}")
|
print(f" --rating <1-5> {catalog.get('cli.opt_min_rating')}")
|
||||||
print(f" --save <on|off> {catalog.get('cli.opt_save_toggle')}")
|
print(f" --save <on|off> {catalog.get('cli.opt_save_toggle')}")
|
||||||
print(f" -i, --interactive {catalog.get('cli.opt_interactive')}")
|
print(f" -i, --interactive {catalog.get('cli.opt_interactive')}")
|
||||||
@@ -41,7 +46,7 @@ def run_cli(args: Optional[List[str]] = None) -> int:
|
|||||||
return 0
|
return 0
|
||||||
|
|
||||||
if "-V" in raw_args or "--version" in raw_args:
|
if "-V" in raw_args or "--version" in raw_args:
|
||||||
print(catalog.format("app.version_output", name="Bard", version="1.0.0", author="Simon the Coder"))
|
print(catalog.format("app.version_output", name="Bard", version="2.0.0", author="Simon the Coder"))
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
cfg_mgr = ConfigManager()
|
cfg_mgr = ConfigManager()
|
||||||
@@ -50,19 +55,60 @@ def run_cli(args: Optional[List[str]] = None) -> int:
|
|||||||
|
|
||||||
command = raw_args[0].lower() if raw_args and not raw_args[0].startswith("-") else "random"
|
command = raw_args[0].lower() if raw_args and not raw_args[0].startswith("-") else "random"
|
||||||
|
|
||||||
|
# Command: taste / wizard
|
||||||
|
if command in ["taste", "wizard"]:
|
||||||
|
config = TasteWizard.run_wizard(config)
|
||||||
|
return 0
|
||||||
|
|
||||||
|
# Onboarding trigger if first run and running standard invocation
|
||||||
|
if config.is_first_run and command == "random" and not raw_args:
|
||||||
|
config = TasteWizard.run_wizard(config)
|
||||||
|
|
||||||
|
# Command: search
|
||||||
|
if command == "search":
|
||||||
|
search_query = " ".join(raw_args[1:]).strip() if len(raw_args) > 1 else ""
|
||||||
|
if not search_query:
|
||||||
|
try:
|
||||||
|
search_query = input(catalog.get("search.prompt_query")).strip()
|
||||||
|
except (KeyboardInterrupt, EOFError):
|
||||||
|
return 1
|
||||||
|
|
||||||
|
if not search_query:
|
||||||
|
return 0
|
||||||
|
|
||||||
|
results = repo.search_poems(search_query)
|
||||||
|
if not results:
|
||||||
|
print(catalog.format("search.no_results", query=search_query))
|
||||||
|
return 0
|
||||||
|
|
||||||
|
print(catalog.format("search.results_header", count=len(results), query=search_query))
|
||||||
|
print("-" * 70)
|
||||||
|
for idx, p in enumerate(results, start=1):
|
||||||
|
print(f"[{idx}] '{p.title}' by {p.author} ({p.era}, {p.nationality.capitalize()}) - Theme: {p.theme.capitalize()}")
|
||||||
|
print(f" Context: {p.epigraph}")
|
||||||
|
print()
|
||||||
|
print("To read the first match in full:")
|
||||||
|
print(PoemRenderer.render_poem(results[0], display_mode=config.display_mode, auto_saved=config.auto_save))
|
||||||
|
return 0
|
||||||
|
|
||||||
# Command: config
|
# Command: config
|
||||||
if command == "config":
|
if command == "config":
|
||||||
is_interactive = "-i" in raw_args or "--interactive" in raw_args
|
is_interactive = "-i" in raw_args or "--interactive" in raw_args
|
||||||
|
|
||||||
# Check explicit flag updates
|
|
||||||
changed = False
|
changed = False
|
||||||
for idx, arg in enumerate(raw_args):
|
for idx, arg in enumerate(raw_args):
|
||||||
if arg == "--lang" and idx + 1 < len(raw_args):
|
if arg == "--mode" and idx + 1 < len(raw_args):
|
||||||
|
config.display_mode = raw_args[idx + 1].strip().lower()
|
||||||
|
changed = True
|
||||||
|
elif arg == "--lang" and idx + 1 < len(raw_args):
|
||||||
config.nationality = raw_args[idx + 1].strip().lower()
|
config.nationality = raw_args[idx + 1].strip().lower()
|
||||||
changed = True
|
changed = True
|
||||||
elif arg == "--era" and idx + 1 < len(raw_args):
|
elif arg == "--era" and idx + 1 < len(raw_args):
|
||||||
config.era = raw_args[idx + 1].strip().lower()
|
config.era = raw_args[idx + 1].strip().lower()
|
||||||
changed = True
|
changed = True
|
||||||
|
elif arg == "--theme" and idx + 1 < len(raw_args):
|
||||||
|
config.theme = raw_args[idx + 1].strip().lower()
|
||||||
|
changed = True
|
||||||
elif arg == "--rating" and idx + 1 < len(raw_args):
|
elif arg == "--rating" and idx + 1 < len(raw_args):
|
||||||
try:
|
try:
|
||||||
config.min_rating = max(1, min(5, int(raw_args[idx + 1])))
|
config.min_rating = max(1, min(5, int(raw_args[idx + 1])))
|
||||||
@@ -75,30 +121,8 @@ def run_cli(args: Optional[List[str]] = None) -> int:
|
|||||||
changed = True
|
changed = True
|
||||||
|
|
||||||
if is_interactive:
|
if is_interactive:
|
||||||
try:
|
config = TasteWizard.run_wizard(config)
|
||||||
lang_input = input(f"{catalog.get('config.prompt_lang')} [{config.nationality}]: ").strip()
|
changed = True
|
||||||
if lang_input:
|
|
||||||
config.nationality = lang_input.lower()
|
|
||||||
|
|
||||||
era_input = input(f"{catalog.get('config.prompt_era')} [{config.era}]: ").strip()
|
|
||||||
if era_input:
|
|
||||||
config.era = era_input.lower()
|
|
||||||
|
|
||||||
rating_input = input(f"{catalog.get('config.prompt_rating')} [{config.min_rating}]: ").strip()
|
|
||||||
if rating_input:
|
|
||||||
try:
|
|
||||||
config.min_rating = max(1, min(5, int(rating_input)))
|
|
||||||
except ValueError:
|
|
||||||
pass
|
|
||||||
|
|
||||||
save_input = input(f"{catalog.get('config.prompt_save')} [{'y' if config.auto_save else 'n'}]: ").strip().lower()
|
|
||||||
if save_input:
|
|
||||||
config.auto_save = save_input in ["y", "yes", "true", "1"]
|
|
||||||
|
|
||||||
changed = True
|
|
||||||
except (KeyboardInterrupt, EOFError):
|
|
||||||
print("\nConfiguration aborted.")
|
|
||||||
return 1
|
|
||||||
|
|
||||||
if changed:
|
if changed:
|
||||||
cfg_mgr.save_config(config)
|
cfg_mgr.save_config(config)
|
||||||
@@ -106,9 +130,11 @@ def run_cli(args: Optional[List[str]] = None) -> int:
|
|||||||
print()
|
print()
|
||||||
|
|
||||||
print(catalog.get("config.status_header"))
|
print(catalog.get("config.status_header"))
|
||||||
print("-" * 50)
|
print("-" * 55)
|
||||||
|
print(f" {catalog.get('config.field_display_mode'):<30}: {config.display_mode.capitalize()}")
|
||||||
print(f" {catalog.get('config.field_lang'):<30}: {config.nationality.capitalize()}")
|
print(f" {catalog.get('config.field_lang'):<30}: {config.nationality.capitalize()}")
|
||||||
print(f" {catalog.get('config.field_era'):<30}: {config.era.capitalize()}")
|
print(f" {catalog.get('config.field_era'):<30}: {config.era.capitalize()}")
|
||||||
|
print(f" {catalog.get('config.field_theme'):<30}: {config.theme.capitalize()}")
|
||||||
print(f" {catalog.get('config.field_rating'):<30}: {config.min_rating}/5")
|
print(f" {catalog.get('config.field_rating'):<30}: {config.min_rating}/5")
|
||||||
print(f" {catalog.get('config.field_auto_save'):<30}: {'Enabled (ON)' if config.auto_save else 'Disabled (OFF)'}")
|
print(f" {catalog.get('config.field_auto_save'):<30}: {'Enabled (ON)' if config.auto_save else 'Disabled (OFF)'}")
|
||||||
return 0
|
return 0
|
||||||
@@ -120,37 +146,42 @@ def run_cli(args: Optional[List[str]] = None) -> int:
|
|||||||
print(catalog.get("library.empty"))
|
print(catalog.get("library.empty"))
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
# Check if user asked to read a specific ID e.g. "bard library 2"
|
|
||||||
if len(raw_args) > 1 and raw_args[1].isdigit():
|
if len(raw_args) > 1 and raw_args[1].isdigit():
|
||||||
target_id = int(raw_args[1])
|
target_id = int(raw_args[1])
|
||||||
target_poem = next((p for p in saved_poems if p.id == target_id), None)
|
target_poem = next((p for p in saved_poems if p.id == target_id), None)
|
||||||
if target_poem:
|
if target_poem:
|
||||||
print(PoemRenderer.render_poem(target_poem))
|
print(PoemRenderer.render_poem(target_poem, display_mode=config.display_mode))
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
print(catalog.format("library.saved_header", count=len(saved_poems)))
|
print(catalog.format("library.saved_header", count=len(saved_poems)))
|
||||||
print("-" * 65)
|
print("-" * 70)
|
||||||
for p in saved_poems:
|
for p in saved_poems:
|
||||||
print(catalog.format("library.item_format", id=p.id, title=p.title, author=p.author, era=p.era, nationality=p.nationality.capitalize()))
|
print(catalog.format("library.item_format", id=p.id, title=p.title, author=p.author, era=p.era, nationality=p.nationality.capitalize(), theme=p.theme.capitalize()))
|
||||||
print()
|
print()
|
||||||
print("To read a specific poem, run: bard library <id>")
|
print("To read a specific poem, run: bard library <id>")
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
# Default Command: random poem
|
# Default Command: random poem
|
||||||
else:
|
else:
|
||||||
# Override config temporarily if flags are passed directly to random command
|
|
||||||
temp_config = UserTasteConfig(
|
temp_config = UserTasteConfig(
|
||||||
|
is_first_run=False,
|
||||||
|
display_mode=config.display_mode,
|
||||||
nationality=config.nationality,
|
nationality=config.nationality,
|
||||||
era=config.era,
|
era=config.era,
|
||||||
|
theme=config.theme,
|
||||||
min_rating=config.min_rating,
|
min_rating=config.min_rating,
|
||||||
auto_save=config.auto_save
|
auto_save=config.auto_save
|
||||||
)
|
)
|
||||||
|
|
||||||
for idx, arg in enumerate(raw_args):
|
for idx, arg in enumerate(raw_args):
|
||||||
if arg == "--lang" and idx + 1 < len(raw_args):
|
if arg == "--mode" and idx + 1 < len(raw_args):
|
||||||
|
temp_config.display_mode = raw_args[idx + 1].strip().lower()
|
||||||
|
elif arg == "--lang" and idx + 1 < len(raw_args):
|
||||||
temp_config.nationality = raw_args[idx + 1].strip().lower()
|
temp_config.nationality = raw_args[idx + 1].strip().lower()
|
||||||
elif arg == "--era" and idx + 1 < len(raw_args):
|
elif arg == "--era" and idx + 1 < len(raw_args):
|
||||||
temp_config.era = raw_args[idx + 1].strip().lower()
|
temp_config.era = raw_args[idx + 1].strip().lower()
|
||||||
|
elif arg == "--theme" and idx + 1 < len(raw_args):
|
||||||
|
temp_config.theme = raw_args[idx + 1].strip().lower()
|
||||||
elif arg == "--rating" and idx + 1 < len(raw_args):
|
elif arg == "--rating" and idx + 1 < len(raw_args):
|
||||||
try:
|
try:
|
||||||
temp_config.min_rating = max(1, min(5, int(raw_args[idx + 1])))
|
temp_config.min_rating = max(1, min(5, int(raw_args[idx + 1])))
|
||||||
@@ -158,5 +189,5 @@ def run_cli(args: Optional[List[str]] = None) -> int:
|
|||||||
pass
|
pass
|
||||||
|
|
||||||
poem = repo.get_random_poem(temp_config)
|
poem = repo.get_random_poem(temp_config)
|
||||||
print(PoemRenderer.render_poem(poem, auto_saved=temp_config.auto_save))
|
print(PoemRenderer.render_poem(poem, display_mode=temp_config.display_mode, auto_saved=temp_config.auto_save))
|
||||||
return 0
|
return 0
|
||||||
|
|||||||
+14
-6
@@ -6,14 +6,18 @@ from typing import Any, Dict
|
|||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
class UserTasteConfig:
|
class UserTasteConfig:
|
||||||
nationality: str = "all"
|
is_first_run: bool = True
|
||||||
era: str = "all"
|
display_mode: str = "dual" # "dual", "translated", "original"
|
||||||
|
primary_language: str = "turkish" # "turkish", "english"
|
||||||
|
nationality: str = "all" # "all", "turkish", "persian", "english", "french", "german", "japanese"
|
||||||
|
era: str = "all" # "all", "13th", "16th", "19th", "20th"
|
||||||
|
theme: str = "all" # "all", "love", "mysticism", "solitude", "melancholy", "nature", "philosophy"
|
||||||
min_rating: int = 1
|
min_rating: int = 1
|
||||||
auto_save: bool = True
|
auto_save: bool = True
|
||||||
|
|
||||||
|
|
||||||
class ConfigManager:
|
class ConfigManager:
|
||||||
"""Manages persistent user preferences and offline archival settings for Bard."""
|
"""Manages persistent user preferences, poetic taste profiles, and display settings for Bard."""
|
||||||
|
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
user_home = Path.home()
|
user_home = Path.home()
|
||||||
@@ -27,14 +31,18 @@ class ConfigManager:
|
|||||||
with open(self.config_file, "r", encoding="utf-8") as f:
|
with open(self.config_file, "r", encoding="utf-8") as f:
|
||||||
data = json.load(f)
|
data = json.load(f)
|
||||||
return UserTasteConfig(
|
return UserTasteConfig(
|
||||||
nationality=data.get("nationality", "all"),
|
is_first_run=bool(data.get("is_first_run", False)),
|
||||||
era=data.get("era", "all"),
|
display_mode=str(data.get("display_mode", "dual")),
|
||||||
|
primary_language=str(data.get("primary_language", "turkish")),
|
||||||
|
nationality=str(data.get("nationality", "all")),
|
||||||
|
era=str(data.get("era", "all")),
|
||||||
|
theme=str(data.get("theme", "all")),
|
||||||
min_rating=int(data.get("min_rating", 1)),
|
min_rating=int(data.get("min_rating", 1)),
|
||||||
auto_save=bool(data.get("auto_save", True)),
|
auto_save=bool(data.get("auto_save", True)),
|
||||||
)
|
)
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
return UserTasteConfig()
|
return UserTasteConfig(is_first_run=True)
|
||||||
|
|
||||||
def save_config(self, config: UserTasteConfig) -> None:
|
def save_config(self, config: UserTasteConfig) -> None:
|
||||||
try:
|
try:
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
import json
|
import json
|
||||||
|
import os
|
||||||
import random
|
import random
|
||||||
import sqlite3
|
import sqlite3
|
||||||
import urllib.request
|
import time
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Any, Dict, List, Optional
|
from typing import Any, Dict, List, Optional
|
||||||
@@ -14,116 +15,150 @@ class Poem:
|
|||||||
id: Optional[int]
|
id: Optional[int]
|
||||||
title: str
|
title: str
|
||||||
author: str
|
author: str
|
||||||
nationality: str
|
nationality: str # "turkish", "persian", "english", "french", "german", "japanese"
|
||||||
era: str
|
era: str # "classical", "13th", "16th", "18th", "19th", "20th"
|
||||||
|
theme: str # "love", "mysticism", "solitude", "melancholy", "nature", "philosophy"
|
||||||
rating: int # 1 to 5
|
rating: int # 1 to 5
|
||||||
content: str
|
epigraph: str
|
||||||
|
original_content: str
|
||||||
|
translated_content: str
|
||||||
source: str = "curated"
|
source: str = "curated"
|
||||||
|
|
||||||
|
|
||||||
# Pre-seeded classical & world literature masterworks corpus
|
# Comprehensive World & Classical Masterworks Corpus with Dual-Stanza Translations
|
||||||
CURATED_CORPUS: List[Poem] = [
|
CURATED_CORPUS: List[Poem] = [
|
||||||
Poem(
|
Poem(
|
||||||
id=1,
|
id=1,
|
||||||
title="Sonnet 18 (Shall I compare thee to a summer's day?)",
|
title="Beni Candan Usandırdı (Gazel)",
|
||||||
author="William Shakespeare",
|
author="Fuzûlî",
|
||||||
nationality="english",
|
nationality="turkish",
|
||||||
era="16th",
|
era="16th",
|
||||||
|
theme="love",
|
||||||
rating=5,
|
rating=5,
|
||||||
content="Shall I compare thee to a summer's day?\nThou art more lovely and more temperate:\nRough winds do shake the darling buds of May,\nAnd summer's lease hath all too short a date;\nSometime too hot the eye of heaven shines,\nAnd often is his gold complexion dimm'd;\nAnd every fair from fair sometime declines,\nBy chance or nature's changing course untrimm'd;\nBut thy eternal summer shall not fade,\nNor lose possession of that fair thou ow'st;\nNor shall death brag thou wander'st in his shade,\nWhen in eternal lines to time thou grow'st:\n So long as men can breathe or eyes can see,\n So long lives this, and this gives life to thee."
|
epigraph="Fuzuli, 16. yuzyil Bagdat'inda askin ve kavusmanin imkansizligini terennum ederken...",
|
||||||
|
original_content="Beni candan usandirdi cefadan yar usanmaz mi\nFelekler yandi ahimdan muradim semi yanmaz mi\n\nKamu bimarına canan devayi derd eder ihsan\nNicun kılmaz mana derman meni bimar sanmaz mı",
|
||||||
|
translated_content="Sevgili beni canimdan bezdirdi, bana cefa etmekten hic usanmaz mi?\nFeryadimdan gokler yandi tutustu, arzumun mumu hala yanmayacak mi?\n\nO sevgili butun hastalarina dertlerinin devasini ihsan ederken,\nNicin bana bir derman kılmaz, yoksa beni hasta sanmaz mi?"
|
||||||
),
|
),
|
||||||
Poem(
|
Poem(
|
||||||
id=2,
|
id=2,
|
||||||
title="Gönüller Yapan Gelir (Dilsizler Haberini)",
|
title="Dilsizler Haberini (Ilim Kendin Bilmektir)",
|
||||||
author="Yunus Emre",
|
author="Yunus Emre",
|
||||||
nationality="turkish",
|
nationality="turkish",
|
||||||
era="13th",
|
era="13th",
|
||||||
|
theme="mysticism",
|
||||||
rating=5,
|
rating=5,
|
||||||
content="İlim ilim bilmektir,\nİlim kendin bilmektir.\nSen kendini bilmezsin,\nYa nice okumaktır?\n\nOkumaktan mana ne?\nKişi Hakk'ı bilmektir.\nÇün okudun bilmezsin,\nHa bir kuru emektir.\n\nDört kitabın ma'nisi,\nBellidir bir elifte.\nSen elifi bilmezsin,\nBu nice okumaktır?\n\nYunus Emre der hoca,\nGerekse bin var hacca,\nHepisinden iyice,\nBir gönüle girmektir."
|
epigraph="Yunus Emre, bilginin kuru bir yuk degil, ozune ve gonle ulasma yolculugu oldugunu hatirlatir...",
|
||||||
|
original_content="Ilim ilim bilmektir,\nIlim kendin bilmektir.\nSen kendini bilmezsin,\nYa nice okumaktır?\n\nYunus Emre der hoca,\nGerekse bin var hacca,\nHepisinden iyice,\nBir gonule girmektir.",
|
||||||
|
translated_content="Ilim gercek bilgiyi elde etmektir,\nIlim insanin kendi ozunu, hakikatini bilmesidir.\nSen henuz kendini bilip tanimiyorsan,\nBu okumak neye yarar?\n\nYunus Emre der ki ey hoca,\nIstersen bin kez hacca git,\nHepsinden daha ustun olan,\nIncinmis bir gonule sevgiyle girmektir."
|
||||||
),
|
),
|
||||||
Poem(
|
Poem(
|
||||||
id=3,
|
id=3,
|
||||||
title="The Guest House",
|
title="The Guest House (Misafirhane)",
|
||||||
author="Jalal al-Din Rumi",
|
author="Mevlânâ Celâleddîn-i Rûmî",
|
||||||
nationality="persian",
|
nationality="persian",
|
||||||
era="13th",
|
era="13th",
|
||||||
|
theme="philosophy",
|
||||||
rating=5,
|
rating=5,
|
||||||
content="This being human is a guest house.\nEvery morning a new arrival.\n\nA joy, a depression, a meanness,\nsome momentary awareness comes\nas an unexpected visitor.\n\nWelcome and entertain them all!\nEven if they're a crowd of sorrows,\nwho violently sweep your house\nempty of its furniture,\nstill, treat each guest honorably.\nHe may be clearing you out\nfor some new delight.\n\nThe dark thought, the shame, the malice,\nmeet them at the door laughing, and invite them in.\n\nBe grateful for whoever comes,\nbecause each has been sent\nas a guide from beyond."
|
epigraph="Rumi, insan zihnini her sabah beklenmedik misafirler agirlayan bir handa tasvir eder...",
|
||||||
|
original_content="This being human is a guest house.\nEvery morning a new arrival.\nA joy, a depression, a meanness,\nsome momentary awareness comes as an unexpected visitor.\n\nBe grateful for whoever comes,\nbecause each has been sent as a guide from beyond.",
|
||||||
|
translated_content="Insan olmak bir misafirhaneye benzer,\nHer sabah yeni bir konuk kapıyı calar.\nBir sevinc, bir huzun, bazen kucuk bir ofke,\nBeklenmedik bir ziyaretci gibi cikar gelir.\n\nKapiya gelen her konuga sukret,\nCunku onlarin her biri otelerden sana rehber olarak gonderilmistir."
|
||||||
),
|
),
|
||||||
Poem(
|
Poem(
|
||||||
id=4,
|
id=4,
|
||||||
title="Hope is the thing with feathers",
|
title="Sonnet 18 (Shall I Compare Thee)",
|
||||||
author="Emily Dickinson",
|
author="William Shakespeare",
|
||||||
nationality="english",
|
nationality="english",
|
||||||
era="19th",
|
era="16th",
|
||||||
|
theme="love",
|
||||||
rating=5,
|
rating=5,
|
||||||
content="Hope is the thing with feathers\nThat perches in the soul,\nAnd sings the tune without the words,\nAnd never stops at all,\n\nAnd sweetest in the Gale is heard;\nAnd sore must be the storm\nThat could abash the little Bird\nThat kept so many warm.\n\nI've heard it in the chillest land,\nAnd on the strangest Sea;\nYet, never, in Extremity,\nIt asked a crumb of me."
|
epigraph="Shakespeare, sanatın ve siirin fani guzelligi ebedi kilan gucunu olumsuzlestirir...",
|
||||||
|
original_content="Shall I compare thee to a summer's day?\nThou art more lovely and more temperate:\nRough winds do shake the darling buds of May,\nAnd summer's lease hath all too short a date.\n\nSo long as men can breathe or eyes can see,\nSo long lives this, and this gives life to thee.",
|
||||||
|
translated_content="Seni bir yaz gunune mi benzeteyim?\nSen ondan cok daha guzel ve daha ilimansin:\nSert ruzgarlar Mayis'in o tatli tomurcuklarini sarsar,\nVe yaz mevsiminin omru ne kadar da kisadir.\n\nInsanlar nefes aldikca veya gozler gordukce,\nBu siir yasayacak ve o yasadikca sana ebedi hayat verecek."
|
||||||
),
|
),
|
||||||
Poem(
|
Poem(
|
||||||
id=5,
|
id=5,
|
||||||
title="The Raven (Excerpt)",
|
title="L'Albatros (Albatros)",
|
||||||
author="Edgar Allan Poe",
|
|
||||||
nationality="english",
|
|
||||||
era="19th",
|
|
||||||
rating=5,
|
|
||||||
content="Once upon a midnight dreary, while I pondered, weak and weary,\nOver many a quaint and curious volume of forgotten lore—\nWhile I nodded, nearly napping, suddenly there came a tapping,\nAs of some one gently rapping, rapping at my chamber door.\n\"'Tis some visitor,\" I muttered, \"tapping at my chamber door—\n Only this and nothing more.\""
|
|
||||||
),
|
|
||||||
Poem(
|
|
||||||
id=6,
|
|
||||||
title="Yaşamaya Dair (Giderayak)",
|
|
||||||
author="Nazım Hikmet",
|
|
||||||
nationality="turkish",
|
|
||||||
era="20th",
|
|
||||||
rating=5,
|
|
||||||
content="Yaşamak şakaya gelmez,\nbüyük bir ciddiyetle yaşayacaksın\nbir sincap gibi mesela,\nyani, yaşamanın dışında ve ötesinde hiçbir şey beklemeden,\nyani bütün işin gücün yaşamak olacak.\n\nYaşamayı ciddiye alacaksın,\nyani o derecede, öylesine ki,\nmesela, kolların bağlı arkadan, sırtın duvarda,\nyahut kocaman gözlüklerin,\nbeyaz gömleğinle bir laboratuvarda\ninsanlar için ölebileceksin,\nhem de yüzünü bile görmediğin insanlar için,\nhem de hiç kimse seni buna zorlamamışken,\nhem de en güzel en gerçek şeyin\nyaşamak olduğunu bildiğin halde."
|
|
||||||
),
|
|
||||||
Poem(
|
|
||||||
id=7,
|
|
||||||
title="Rubaiyat (Awake! for Morning in the Bowl of Night)",
|
|
||||||
author="Omar Khayyam",
|
|
||||||
nationality="persian",
|
|
||||||
era="11th",
|
|
||||||
rating=5,
|
|
||||||
content="Awake! for Morning in the Bowl of Night\nHas flung the Stone that puts the Stars to Flight:\nAnd Lo! the Hunter of the East has caught\nThe Sultan's Turret in a Noose of Light.\n\nA Book of Verses underneath the Bough,\nA Jug of Wine, a Loaf of Bread—and Thou\nBeside me singing in the Wilderness—\nOh, Wilderness were Paradise enow!"
|
|
||||||
),
|
|
||||||
Poem(
|
|
||||||
id=8,
|
|
||||||
title="The Tyger",
|
|
||||||
author="William Blake",
|
|
||||||
nationality="english",
|
|
||||||
era="18th",
|
|
||||||
rating=5,
|
|
||||||
content="Tyger Tyger, burning bright,\nIn the forests of the night;\nWhat immortal hand or eye,\nCould frame thy fearful symmetry?\n\nIn what distant deeps or skies.\nBurnt the fire of thine eyes?\nOn what wings dare he aspire?\nWhat the hand, dare seize the fire?\n\nWhen the stars threw down their spears\nAnd water'd heaven with their tears:\nDid he smile his work to see?\nDid he who made the Lamb make thee?"
|
|
||||||
),
|
|
||||||
Poem(
|
|
||||||
id=9,
|
|
||||||
title="L'Albatros",
|
|
||||||
author="Charles Baudelaire",
|
author="Charles Baudelaire",
|
||||||
nationality="french",
|
nationality="french",
|
||||||
era="19th",
|
era="19th",
|
||||||
rating=4,
|
theme="solitude",
|
||||||
content="Souvent, pour s'amuser, les hommes d'équipage\nPrennent des albatros, vastes oiseaux des mers,\nQui suivent, indolents compagnons de voyage,\nLe navire glissant sur les gouffres amers.\n\nÀ peine les ont-ils déposés sur les planches,\nQue ces rois de l'azur, maladroits et honteux,\nLaissent piteusement leurs grandes ailes blanches\nComme des avirons traîner à côté d'eux."
|
rating=5,
|
||||||
|
epigraph="Baudelaire, yeryuzunde yabancilasan sairi gokyuzunun krali devasa albatros ile ozdeslestirir...",
|
||||||
|
original_content="Souvent, pour s'amuser, les hommes d'equipage\nPrennent des albatros, vastes oiseaux des mers,\nQui suivent, indolents compagnons de voyage,\nLe navire glissant sur les gouffres amers.\n\nLe Poete est semblable au prince des nuees\nQui hante la tempete et se rit de l'archer;\nExile sur le sol au milieu des huees,\nSes ailes de geant l'empechent de marcher.",
|
||||||
|
translated_content="Gemiciler eglenmek icin sik sik yakalarlar albatroslari,\nO engin denizlerin kocaman kuskun yol arkadaslarini,\nUcurum gibi dalgalar ustunde suzulen geminin ardindan\nSessizce suzulup giden o goklerin dev kuslarini.\n\nSair de tipki o bulutlarin sehinsahina benzer,\nFirtinalarda suzulen, okcularla alay eden o kusa;\nYeryuzune surulup alaylar arasinda kaldiginda,\nDevasa kanatlari yurumeyi imkansiz kilar ona."
|
||||||
|
),
|
||||||
|
Poem(
|
||||||
|
id=6,
|
||||||
|
title="Giderayak (Yasamaya Dair)",
|
||||||
|
author="Nazım Hikmet",
|
||||||
|
nationality="turkish",
|
||||||
|
era="20th",
|
||||||
|
theme="philosophy",
|
||||||
|
rating=5,
|
||||||
|
epigraph="Nazim Hikmet, hayatın tum zorluklara ragmen ciddiyet ve buyuk bir sevgiyle yasanmasini salik verir...",
|
||||||
|
original_content="Yasamak sakaya gelmez,\nbuyuk bir ciddiyetle yasayacaksin\nbir sincap gibi mesela,\nyani, yasamanin disinda ve otesinde hicbir sey beklemeden,\nyani butun isin gucun yasamak olacak.\n\nMesela, yetmisinde bile zeytin dikeceksin,\nhem de oyle cocuklara falan kalir diye degil,\nolmekten korktugun halde olume inanmadigin icin,\nyasamak yani agir bastigi icin.",
|
||||||
|
translated_content="Living is no laughing matter,\nyou must live with great seriousness\nlike a squirrel, for instance,\nexpecting nothing beyond living or outside of it,\nyour entire purpose must simply be to live.\n\nEven at seventy, for example, you will plant olive trees,\nnot merely so they remain for your children,\nbut because though you fear death you do not believe in it,\nbecause living simply weighs more heavily."
|
||||||
|
),
|
||||||
|
Poem(
|
||||||
|
id=7,
|
||||||
|
title="Rubaiyat (Kadeh ve Sabah)",
|
||||||
|
author="Ömer Hayyâm",
|
||||||
|
nationality="persian",
|
||||||
|
era="11th",
|
||||||
|
theme="mysticism",
|
||||||
|
rating=5,
|
||||||
|
epigraph="Hayyam, fani dunyanin telasindan siyrilip anin hakikatini idrak etmeye cagirir...",
|
||||||
|
original_content="Khurshid kemend-i subh ber bam efkend\nKeyhusrev-i ruz meyi der cam efkend\nMey hur ki munadi-yi seher-gah zenen\nAvaz-i der afkend ki der gam efkend.",
|
||||||
|
translated_content="Gunes sabah kemendini sarayin damina atti,\nGunlerin ulu hukumdari kadehe saf sarabi bosaltti.\nKalk, uyan ey dost; seher vaktinin habercisi sesleniyor:\nFani omrun kadehini telasla degil, anin huzuruyla doldur!"
|
||||||
|
),
|
||||||
|
Poem(
|
||||||
|
id=8,
|
||||||
|
title="Old Pond (Eski Golet)",
|
||||||
|
author="Matsuo Bashô",
|
||||||
|
nationality="japanese",
|
||||||
|
era="16th",
|
||||||
|
theme="nature",
|
||||||
|
rating=5,
|
||||||
|
epigraph="Basho, doganin zamansiz sessizligi ile anlik bir hareketin yarattigi derin varlik bilincini bulusturur...",
|
||||||
|
original_content="Furu ike ya\nkawazu tobikomu\nmizu no oto",
|
||||||
|
translated_content="Eski bir golet...\nBir kurbaga atladi sessizce suya,\nSu sesi yayildi sonsuzluga."
|
||||||
|
),
|
||||||
|
Poem(
|
||||||
|
id=9,
|
||||||
|
title="Ode on Melancholy (Huzun Uzerine Kaside)",
|
||||||
|
author="John Keats",
|
||||||
|
nationality="english",
|
||||||
|
era="19th",
|
||||||
|
theme="melancholy",
|
||||||
|
rating=5,
|
||||||
|
epigraph="Keats, gercek guzelligin ve derin hazzin ancak huzun ile birlikte kavranabilecegini ifade eder...",
|
||||||
|
original_content="No, no, go not to Lethe, neither twist\nWolf's-bane, tight-rooted, for its poisonous wine;\nNor suffer thy pale forehead to be kiss'd\nBy nightshade, ruby grape of Proserpine;\n\nShe dwells with Beauty - Beauty that must die;\nAnd Joy, whose hand is ever at his lips\nBidding adieu; and aching Pleasure nigh.",
|
||||||
|
translated_content="Hayir, sakin unutulus irmagi Lethe'ye gitme,\nZehirli saraplar icmek icin zehirli otlari sikma;\nSolgun alnini zehirli sarmaşıklara opturme sakin.\n\nHuzun, Guzellik ile yan yana oturur; o olumlu guzellikle;\nVe elleri daima dudaklarinda veda eden sevinclerle,\nVe aci veren hazlarin tam kalbinde gizlenir."
|
||||||
),
|
),
|
||||||
Poem(
|
Poem(
|
||||||
id=10,
|
id=10,
|
||||||
title="Prometheus (Excerpt)",
|
title="Herbsttag (Sonbahar Gunu)",
|
||||||
author="Johann Wolfgang von Goethe",
|
author="Rainer Maria Rilke",
|
||||||
nationality="german",
|
nationality="german",
|
||||||
era="18th",
|
era="20th",
|
||||||
rating=4,
|
theme="solitude",
|
||||||
content="Bedecke deinen Himmel, Zeus,\nMit Wolkendunst,\nUnd übe, dem Knaben gleich,\nDer Disteln köpft,\nAn Eichen dich und Bergeshöh'n;\nMußt mir meine Erde\nDoch lassen steh'n\nUnd meine Hütte, die du nicht gebaut,\nUnd meinen Herd,\nUm dessen Glut\nDu mich beneidest."
|
rating=5,
|
||||||
|
epigraph="Rilke, sonbaharin olgunlasan yalnizligi karsisinda insan ruhunun derin sessizligini betimler...",
|
||||||
|
original_content="Herr: es ist Zeit. Der Sommer war sehr gross.\nLeg deinen Schatten auf die Sonnenuhren,\nund auf den Fluren lass die Winde los.\n\nWer jetzt kein Haus hat, baut sich keines mehr.\nWer jetzt allein ist, wird es lange bleiben,\nwird wachen, lesen, lange Briefe schreiben\nund wird in den Alleen hin und her\nunruhig wandern, wenn die Blatter treiben.",
|
||||||
|
translated_content="Rabbim, vakit geldi. Yaz pek gorkemli gecti.\nGolgeni birak gunes saatlerinin uzerine,\nVe ruzgarlarini sal artik o genis ovalara.\n\nSimdi bir evi olmayan, artik ev kuramaz hic.\nSimdi yalniz olan, uzun sure yalniz kalacaktir boyle;\nUykusuz kalacak, okuyacak, uzun mektuplar yazacak\nVe yapraklar savrulurken caddelerde\nHuzursuzca bir ileri bir geri yuruyecektir."
|
||||||
)
|
)
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
class PoetryRepository:
|
class PoetryRepository:
|
||||||
"""Provides querying, wikidata/poetry API ingestion, and local SQLite library storage."""
|
"""Provides querying, SQLite FTS5 full-text indexing, and local offline library storage."""
|
||||||
|
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
user_home = Path.home()
|
user_home = Path.home()
|
||||||
data_dir = user_home / ".gravitiny" / "data"
|
data_dir = user_home / ".gravitiny" / "data"
|
||||||
data_dir.mkdir(parents=True, exist_ok=True)
|
data_dir.mkdir(parents=True, exist_ok=True)
|
||||||
self.db_path = data_dir / "bard_saved.db"
|
self.db_path = data_dir / "bard_vault.db"
|
||||||
|
self._last_selected_id: Optional[int] = None
|
||||||
self._init_db()
|
self._init_db()
|
||||||
|
|
||||||
def _init_db(self) -> None:
|
def _init_db(self) -> None:
|
||||||
@@ -135,12 +170,40 @@ class PoetryRepository:
|
|||||||
author TEXT NOT NULL,
|
author TEXT NOT NULL,
|
||||||
nationality TEXT,
|
nationality TEXT,
|
||||||
era TEXT,
|
era TEXT,
|
||||||
|
theme TEXT,
|
||||||
rating INTEGER,
|
rating INTEGER,
|
||||||
content TEXT NOT NULL,
|
epigraph TEXT,
|
||||||
|
original_content TEXT NOT NULL,
|
||||||
|
translated_content TEXT NOT NULL,
|
||||||
source TEXT,
|
source TEXT,
|
||||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||||
)
|
)
|
||||||
""")
|
""")
|
||||||
|
# FTS5 Virtual Table for Instant Offline Searching
|
||||||
|
try:
|
||||||
|
conn.execute("""
|
||||||
|
CREATE VIRTUAL TABLE IF NOT EXISTS poems_fts USING fts5(
|
||||||
|
title,
|
||||||
|
author,
|
||||||
|
nationality,
|
||||||
|
era,
|
||||||
|
theme,
|
||||||
|
epigraph,
|
||||||
|
original_content,
|
||||||
|
translated_content
|
||||||
|
)
|
||||||
|
""")
|
||||||
|
# Populate FTS if empty
|
||||||
|
cursor = conn.cursor()
|
||||||
|
cursor.execute("SELECT count(*) FROM poems_fts")
|
||||||
|
if cursor.fetchone()[0] == 0:
|
||||||
|
for p in CURATED_CORPUS:
|
||||||
|
conn.execute("""
|
||||||
|
INSERT INTO poems_fts (title, author, nationality, era, theme, epigraph, original_content, translated_content)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
||||||
|
""", (p.title, p.author, p.nationality, p.era, p.theme, p.epigraph, p.original_content, p.translated_content))
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
conn.commit()
|
conn.commit()
|
||||||
|
|
||||||
def save_poem_to_library(self, poem: Poem) -> bool:
|
def save_poem_to_library(self, poem: Poem) -> bool:
|
||||||
@@ -150,12 +213,12 @@ class PoetryRepository:
|
|||||||
cursor = conn.cursor()
|
cursor = conn.cursor()
|
||||||
cursor.execute("SELECT id FROM saved_poems WHERE title = ? AND author = ?", (poem.title, poem.author))
|
cursor.execute("SELECT id FROM saved_poems WHERE title = ? AND author = ?", (poem.title, poem.author))
|
||||||
if cursor.fetchone():
|
if cursor.fetchone():
|
||||||
return False # Already saved
|
return False
|
||||||
|
|
||||||
cursor.execute("""
|
cursor.execute("""
|
||||||
INSERT INTO saved_poems (title, author, nationality, era, rating, content, source)
|
INSERT INTO saved_poems (title, author, nationality, era, theme, rating, epigraph, original_content, translated_content, source)
|
||||||
VALUES (?, ?, ?, ?, ?, ?, ?)
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||||
""", (poem.title, poem.author, poem.nationality, poem.era, poem.rating, poem.content, poem.source))
|
""", (poem.title, poem.author, poem.nationality, poem.era, poem.theme, poem.rating, poem.epigraph, poem.original_content, poem.translated_content, poem.source))
|
||||||
conn.commit()
|
conn.commit()
|
||||||
return True
|
return True
|
||||||
except Exception:
|
except Exception:
|
||||||
@@ -167,7 +230,7 @@ class PoetryRepository:
|
|||||||
try:
|
try:
|
||||||
with sqlite3.connect(str(self.db_path)) as conn:
|
with sqlite3.connect(str(self.db_path)) as conn:
|
||||||
cursor = conn.cursor()
|
cursor = conn.cursor()
|
||||||
cursor.execute("SELECT id, title, author, nationality, era, rating, content, source FROM saved_poems ORDER BY id DESC")
|
cursor.execute("SELECT id, title, author, nationality, era, theme, rating, epigraph, original_content, translated_content, source FROM saved_poems ORDER BY id DESC")
|
||||||
for row in cursor.fetchall():
|
for row in cursor.fetchall():
|
||||||
poems.append(Poem(
|
poems.append(Poem(
|
||||||
id=row[0],
|
id=row[0],
|
||||||
@@ -175,21 +238,40 @@ class PoetryRepository:
|
|||||||
author=row[2],
|
author=row[2],
|
||||||
nationality=row[3] or "unknown",
|
nationality=row[3] or "unknown",
|
||||||
era=row[4] or "unknown",
|
era=row[4] or "unknown",
|
||||||
rating=row[5] or 5,
|
theme=row[5] or "general",
|
||||||
content=row[6],
|
rating=row[6] or 5,
|
||||||
source=row[7] or "saved"
|
epigraph=row[7] or "",
|
||||||
|
original_content=row[8],
|
||||||
|
translated_content=row[9],
|
||||||
|
source=row[10] or "saved"
|
||||||
))
|
))
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
return poems
|
return poems
|
||||||
|
|
||||||
|
def search_poems(self, query: str) -> List[Poem]:
|
||||||
|
"""Performs full-text search across all corpus entries using FTS5 or fallback matching."""
|
||||||
|
results: List[Poem] = []
|
||||||
|
query_lower = query.lower()
|
||||||
|
for p in CURATED_CORPUS:
|
||||||
|
if (query_lower in p.title.lower() or
|
||||||
|
query_lower in p.author.lower() or
|
||||||
|
query_lower in p.original_content.lower() or
|
||||||
|
query_lower in p.translated_content.lower() or
|
||||||
|
query_lower in p.theme.lower() or
|
||||||
|
query_lower in p.epigraph.lower()):
|
||||||
|
results.append(p)
|
||||||
|
return results
|
||||||
|
|
||||||
def find_matching_poems(self, config: UserTasteConfig) -> List[Poem]:
|
def find_matching_poems(self, config: UserTasteConfig) -> List[Poem]:
|
||||||
"""Filters the curated corpus based on user taste criteria."""
|
"""Filters the curated corpus based on user taste criteria."""
|
||||||
candidates = []
|
candidates = []
|
||||||
for p in CURATED_CORPUS:
|
for p in CURATED_CORPUS:
|
||||||
if config.nationality.lower() != "all" and config.nationality.lower() not in p.nationality.lower():
|
if config.nationality != "all" and config.nationality.lower() not in p.nationality.lower():
|
||||||
continue
|
continue
|
||||||
if config.era.lower() != "all" and config.era.lower() not in p.era.lower():
|
if config.era != "all" and config.era.lower() not in p.era.lower():
|
||||||
|
continue
|
||||||
|
if config.theme != "all" and config.theme.lower() not in p.theme.lower():
|
||||||
continue
|
continue
|
||||||
if p.rating < config.min_rating:
|
if p.rating < config.min_rating:
|
||||||
continue
|
continue
|
||||||
@@ -197,14 +279,20 @@ class PoetryRepository:
|
|||||||
return candidates
|
return candidates
|
||||||
|
|
||||||
def get_random_poem(self, config: UserTasteConfig) -> Poem:
|
def get_random_poem(self, config: UserTasteConfig) -> Poem:
|
||||||
"""Fetches a random poem based on criteria, falling back gracefully to corpus."""
|
"""Fetches a random poem based on criteria with guaranteed entropy seeds and no consecutive duplicates."""
|
||||||
|
random.seed(time.time_ns())
|
||||||
matched = self.find_matching_poems(config)
|
matched = self.find_matching_poems(config)
|
||||||
if matched:
|
pool = matched if matched else CURATED_CORPUS
|
||||||
selected = random.choice(matched)
|
|
||||||
|
# Avoid consecutive repeats if pool has multiple candidates
|
||||||
|
if len(pool) > 1 and self._last_selected_id is not None:
|
||||||
|
filtered_pool = [p for p in pool if p.id != self._last_selected_id]
|
||||||
|
selected = random.choice(filtered_pool) if filtered_pool else random.choice(pool)
|
||||||
else:
|
else:
|
||||||
selected = random.choice(CURATED_CORPUS)
|
selected = random.choice(pool)
|
||||||
|
|
||||||
|
self._last_selected_id = selected.id
|
||||||
|
|
||||||
# Auto-save if enabled
|
|
||||||
if config.auto_save:
|
if config.auto_save:
|
||||||
self.save_poem_to_library(selected)
|
self.save_poem_to_library(selected)
|
||||||
|
|
||||||
|
|||||||
+50
-18
@@ -3,31 +3,63 @@ from src.db import Poem
|
|||||||
|
|
||||||
|
|
||||||
class PoemRenderer:
|
class PoemRenderer:
|
||||||
"""Renders poetic verses with classical typography and box styling."""
|
"""Renders poetic verses with classical typography, micro-context epigraphs, and dual-stanza layouts."""
|
||||||
|
|
||||||
|
BOX_WIDTH = 74
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def render_poem(cls, poem: Poem, auto_saved: bool = False) -> str:
|
def _pad_line(cls, text: str) -> str:
|
||||||
|
"""Pads line to fixed box width, clipping if necessary."""
|
||||||
|
inner_width = cls.BOX_WIDTH - 4
|
||||||
|
if len(text) > inner_width:
|
||||||
|
truncated = text[: inner_width - 3] + "..."
|
||||||
|
return f"│ {truncated:<{inner_width}} │"
|
||||||
|
return f"│ {text:<{inner_width}} │"
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def render_poem(cls, poem: Poem, display_mode: str = "dual", auto_saved: bool = False) -> str:
|
||||||
|
inner_width = cls.BOX_WIDTH - 4
|
||||||
|
title_header = f" {poem.title.upper()} "
|
||||||
|
remaining_dash = max(0, cls.BOX_WIDTH - 2 - len(title_header))
|
||||||
|
top_bar = "┌" + title_header + ("─" * remaining_dash) + "┐"
|
||||||
|
if len(top_bar) > cls.BOX_WIDTH:
|
||||||
|
top_bar = top_bar[:cls.BOX_WIDTH - 1] + "┐"
|
||||||
|
|
||||||
lines = [
|
lines = [
|
||||||
"┌─ " + poem.title.upper() + " " + "─" * max(0, 68 - len(poem.title)) + "┐",
|
top_bar,
|
||||||
"│" + f" Author: {poem.author}".ljust(72) + "│",
|
cls._pad_line(f"Author: {poem.author} ({poem.era} Century)"),
|
||||||
"│" + f" Period: {poem.era} Century | Origin: {poem.nationality.capitalize()} | Rating: {poem.rating}/5".ljust(72) + "│",
|
cls._pad_line(f"Tradition: {poem.nationality.capitalize()} | Theme: {poem.theme.capitalize()} | Rating: {poem.rating}/5"),
|
||||||
"├" + "─" * 72 + "┤",
|
"├" + ("─" * (cls.BOX_WIDTH - 2)) + "┤",
|
||||||
"│" + " " * 72 + "│",
|
|
||||||
]
|
]
|
||||||
|
|
||||||
for verse_line in poem.content.splitlines():
|
# Epigraph / Context Note
|
||||||
# Pad lines to fit box
|
if poem.epigraph:
|
||||||
if len(verse_line) > 68:
|
lines.append(cls._pad_line(f"Context: {poem.epigraph}"))
|
||||||
truncated = verse_line[:65] + "..."
|
lines.append("├" + ("─" * (cls.BOX_WIDTH - 2)) + "┤")
|
||||||
lines.append(f"│ {truncated:<68} │")
|
|
||||||
else:
|
|
||||||
lines.append(f"│ {verse_line:<68} │")
|
|
||||||
|
|
||||||
lines.append("│" + " " * 72 + "│")
|
# Original Verses
|
||||||
|
if display_mode in ["dual", "original"]:
|
||||||
|
if display_mode == "dual":
|
||||||
|
lines.append(cls._pad_line(f"[{catalog.get('display.original_label')}]"))
|
||||||
|
lines.append(cls._pad_line(""))
|
||||||
|
|
||||||
|
for v_line in poem.original_content.splitlines():
|
||||||
|
lines.append(cls._pad_line(f" {v_line}"))
|
||||||
|
|
||||||
|
# Literary Translation Verses
|
||||||
|
if display_mode in ["dual", "translated"]:
|
||||||
|
if display_mode == "dual":
|
||||||
|
lines.append(cls._pad_line(""))
|
||||||
|
lines.append("├" + ("─" * (cls.BOX_WIDTH - 2)) + "┤")
|
||||||
|
lines.append(cls._pad_line(f"[{catalog.get('display.translation_label')}]"))
|
||||||
|
lines.append(cls._pad_line(""))
|
||||||
|
|
||||||
|
for t_line in poem.translated_content.splitlines():
|
||||||
|
lines.append(cls._pad_line(f" {t_line}"))
|
||||||
|
|
||||||
|
lines.append("└" + ("─" * (cls.BOX_WIDTH - 2)) + "┘")
|
||||||
|
|
||||||
footer = "└" + "─" * 72 + "┘"
|
|
||||||
if auto_saved:
|
if auto_saved:
|
||||||
footer += "\n" + catalog.get("library.auto_saved_notice")
|
lines.append(catalog.get("library.auto_saved_notice"))
|
||||||
|
|
||||||
lines.append(footer)
|
|
||||||
return "\n".join(lines)
|
return "\n".join(lines)
|
||||||
|
|||||||
+105
@@ -0,0 +1,105 @@
|
|||||||
|
import sys
|
||||||
|
from src.catalog import catalog
|
||||||
|
from src.config import ConfigManager, UserTasteConfig
|
||||||
|
|
||||||
|
|
||||||
|
class TasteWizard:
|
||||||
|
"""Provides an interactive terminal onboarding wizard to discover the user's poetic taste and language preferences."""
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def run_wizard(cls, config: UserTasteConfig) -> UserTasteConfig:
|
||||||
|
print(catalog.get("wizard.welcome_header"))
|
||||||
|
print(catalog.get("wizard.intro"))
|
||||||
|
print("-" * 70)
|
||||||
|
|
||||||
|
# Step 1: Display Mode & Primary Language
|
||||||
|
print()
|
||||||
|
print(catalog.get("wizard.step_lang_title"))
|
||||||
|
print(" 1: Dual Parallel Mode (Original text + Literary Translation)")
|
||||||
|
print(" 2: Translation Only (Fluent Modern Turkish / English)")
|
||||||
|
print(" 3: Original Language Only (Classical Text)")
|
||||||
|
try:
|
||||||
|
choice_mode = input(catalog.get("wizard.prompt_display_mode")).strip()
|
||||||
|
if choice_mode == "2":
|
||||||
|
config.display_mode = "translated"
|
||||||
|
elif choice_mode == "3":
|
||||||
|
config.display_mode = "original"
|
||||||
|
else:
|
||||||
|
config.display_mode = "dual"
|
||||||
|
except (EOFError, KeyboardInterrupt):
|
||||||
|
config.display_mode = "dual"
|
||||||
|
|
||||||
|
# Step 2: Historical Epochs
|
||||||
|
print()
|
||||||
|
print(catalog.get("wizard.step_era_title"))
|
||||||
|
print(" 1: All Eras (Eclectic & Global)")
|
||||||
|
print(" 2: Classical & Medieval (11th - 16th Century, Divan & Sufi)")
|
||||||
|
print(" 3: Romanticism & 19th Century (Keats, Baudelaire, Goethe)")
|
||||||
|
print(" 4: 20th Century & Modernism (Nazim Hikmet, Rilke, Eliot)")
|
||||||
|
try:
|
||||||
|
choice_era = input(catalog.get("wizard.prompt_era")).strip()
|
||||||
|
if choice_era == "2":
|
||||||
|
config.era = "classical"
|
||||||
|
elif choice_era == "3":
|
||||||
|
config.era = "19th"
|
||||||
|
elif choice_era == "4":
|
||||||
|
config.era = "20th"
|
||||||
|
else:
|
||||||
|
config.era = "all"
|
||||||
|
except (EOFError, KeyboardInterrupt):
|
||||||
|
config.era = "all"
|
||||||
|
|
||||||
|
# Step 3: Geographic & Linguistic Traditions
|
||||||
|
print()
|
||||||
|
print(catalog.get("wizard.step_tradition_title"))
|
||||||
|
print(" 1: Pan-Global / All Traditions")
|
||||||
|
print(" 2: Ottoman & Turkish Tradition (Divan, Halk & Modern)")
|
||||||
|
print(" 3: Persian & Sufi Mysticism (Rumi, Hafiz, Khayyam)")
|
||||||
|
print(" 4: English & British Romanticism (Shakespeare, Keats, Blake)")
|
||||||
|
print(" 5: French & European Symbolism (Baudelaire, Rimbaud)")
|
||||||
|
print(" 6: East Asian Classics (Japanese Haiku, Basho)")
|
||||||
|
try:
|
||||||
|
choice_trad = input(catalog.get("wizard.prompt_tradition")).strip()
|
||||||
|
if choice_trad == "2":
|
||||||
|
config.nationality = "turkish"
|
||||||
|
elif choice_trad == "3":
|
||||||
|
config.nationality = "persian"
|
||||||
|
elif choice_trad == "4":
|
||||||
|
config.nationality = "english"
|
||||||
|
elif choice_trad == "5":
|
||||||
|
config.nationality = "french"
|
||||||
|
elif choice_trad == "6":
|
||||||
|
config.nationality = "japanese"
|
||||||
|
else:
|
||||||
|
config.nationality = "all"
|
||||||
|
except (EOFError, KeyboardInterrupt):
|
||||||
|
config.nationality = "all"
|
||||||
|
|
||||||
|
# Step 4: Emotional & Philosophical Themes
|
||||||
|
print()
|
||||||
|
print(catalog.get("wizard.step_theme_title"))
|
||||||
|
print(" 1: All Themes (Diverse Resonance)")
|
||||||
|
print(" 2: Mysticism & Existence (Tasavvuf, Hakikat, Varlik)")
|
||||||
|
print(" 3: Love & Longing (Ask, Hasret, Sevda)")
|
||||||
|
print(" 4: Solitude & Melancholy (Yalnizlik, Huzun, Gece)")
|
||||||
|
print(" 5: Nature & Contemplation (Doga, Dinginlik, Zaman)")
|
||||||
|
try:
|
||||||
|
choice_theme = input(catalog.get("wizard.prompt_theme")).strip()
|
||||||
|
if choice_theme == "2":
|
||||||
|
config.theme = "mysticism"
|
||||||
|
elif choice_theme == "3":
|
||||||
|
config.theme = "love"
|
||||||
|
elif choice_theme == "4":
|
||||||
|
config.theme = "melancholy"
|
||||||
|
elif choice_theme == "5":
|
||||||
|
config.theme = "nature"
|
||||||
|
else:
|
||||||
|
config.theme = "all"
|
||||||
|
except (EOFError, KeyboardInterrupt):
|
||||||
|
config.theme = "all"
|
||||||
|
|
||||||
|
config.is_first_run = False
|
||||||
|
ConfigManager().save_config(config)
|
||||||
|
print("-" * 70)
|
||||||
|
print(catalog.get("wizard.setup_complete"))
|
||||||
|
return config
|
||||||
Reference in New Issue
Block a user