chore(release): bump version to v1.0.1

This commit is contained in:
2026-10-03 06:39:20 +03:00
commit 9e937755ee
14 changed files with 609 additions and 0 deletions
+44
View File
@@ -0,0 +1,44 @@
# Bard
Wikidata & Wikisource Powered Curated Random Poetry Discovery & Archival Engine.
Author: **Dr. Simon Vance (Simon the Coder)** (`simonthecoder`)
---
## Features
- **Taste Configuration:** Configure language / nationality (English, Turkish, Persian, French, German, etc.), historical era/century, and minimum popularity score (1 to 5).
- **Random Poem Discovery:** Displays random world masterworks and archival verses matching your preference.
- **Offline Library & Auto-Save:** When `--save on` is configured, every poem read is archived into local SQLite storage for offline reading.
- **Pre-Seeded Masterworks:** 100% functional offline from the first second.
---
## Usage
```bash
# Read a random poem matching current configuration
bard
# Read a random Turkish poem from the 13th century
bard --lang turkish --era 13th
# Configure preferences interactively
bard config --interactive
# Toggle auto-saving on/off
bard config --save on
# Browse your saved offline library
bard library
# Read a specific saved poem from library
bard library 1
```
---
## License
MIT License.
+45
View File
@@ -0,0 +1,45 @@
{
"app": {
"name": "Bard",
"tagline": "Curated Poetry Discovery & Archival Engine",
"version_output": "{name} v{version} by {author}"
},
"cli": {
"usage": "Usage: bard [command] [options]",
"commands_title": "Commands:",
"cmd_random": "Display a random poem matching your current taste configuration",
"cmd_config": "View or update poet filtering preferences and auto-save settings",
"cmd_library": "Browse and read poems saved in your offline library",
"cmd_search": "Search poems by title, poet, or verse content",
"options_title": "Options:",
"opt_help": "Show this help message and exit",
"opt_version": "Show version information and exit",
"opt_lang": "Filter by nationality / language (e.g. english, turkish, persian, 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_save_toggle": "Enable or disable auto-saving viewed poems (on/off)",
"opt_interactive": "Launch interactive configuration wizard"
},
"config": {
"status_header": "Current Bard Taste & Archival Configuration:",
"field_lang": "Language / Nationality",
"field_era": "Century / Era",
"field_rating": "Popularity Score (1-5)",
"field_auto_save": "Auto-Save to Offline Library",
"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": {
"empty": "No saved poems in your offline library. Enable auto-save in config or use 'bard config --save on'.",
"saved_header": "Offline Saved Poetry Library ({count} poems):",
"auto_saved_notice": "[Archived to Offline Library]",
"item_format": "[{id}] '{title}' by {author} ({era}, {nationality})"
},
"display": {
"no_poems_matched": "No poems matched your current filter criteria (Lang: {lang}, Era: {era}, Rating >= {rating}). Showing diverse classical selection.",
"footer_meta": "Poet: {author} | Era: {era} | Origin: {nationality} | Popularity: {rating}/5"
}
}
+12
View File
@@ -0,0 +1,12 @@
import sys
from pathlib import Path
# Add applet root to sys.path
applet_root = Path(__file__).resolve().parent
if str(applet_root) not in sys.path:
sys.path.insert(0, str(applet_root))
from src.cli import run_cli
if __name__ == "__main__":
sys.exit(run_cli())
+13
View File
@@ -0,0 +1,13 @@
{
"id": "bard",
"name": "Bard",
"version": "1.0.1",
"description": "Wikidata & Wikisource random poetry discovery engine with taste filtering and offline caching.",
"author": "Simon the Coder <simon@luxhebros.com>",
"license": "MIT",
"runtime": "python",
"entrypoint": "main.py",
"shims": ["bard", "poem"],
"tags": ["poetry", "literature", "wikidata", "wikisource", "culture", "offline"],
"network": "online"
}
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+45
View File
@@ -0,0 +1,45 @@
import json
import os
from typing import Any, Dict
class StringCatalog:
"""Centralized string catalog loader for Bard applet."""
_instance = None
_catalog: Dict[str, Any] = {}
def __new__(cls):
if cls._instance is None:
cls._instance = super(StringCatalog, cls).__new__(cls)
cls._instance._load_catalog()
return cls._instance
def _load_catalog(self) -> None:
base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
catalog_path = os.path.join(base_dir, "catalog", "strings.json")
if os.path.exists(catalog_path):
with open(catalog_path, "r", encoding="utf-8") as f:
self._catalog = json.load(f)
else:
self._catalog = {}
def get(self, key_path: str, default: str = "") -> str:
parts = key_path.split(".")
current = self._catalog
for part in parts:
if isinstance(current, dict) and part in current:
current = current[part]
else:
return default
return str(current) if current is not None else default
def format(self, key_path: str, **kwargs: Any) -> str:
template = self.get(key_path, "")
try:
return template.format(**kwargs)
except KeyError:
return template
catalog = StringCatalog()
+162
View File
@@ -0,0 +1,162 @@
import sys
from typing import List, Optional
from src.catalog import catalog
from src.config import ConfigManager, UserTasteConfig
from src.db import PoetryRepository
from src.renderer import PoemRenderer
def print_help() -> None:
print(f"{catalog.get('app.name')} - {catalog.get('app.tagline')}")
print()
print(catalog.get("cli.usage"))
print()
print(catalog.get("cli.commands_title"))
print(f" random {catalog.get('cli.cmd_random')}")
print(f" config {catalog.get('cli.cmd_config')}")
print(f" library, saved {catalog.get('cli.cmd_library')}")
print()
print(catalog.get("cli.options_title"))
print(f" -h, --help {catalog.get('cli.opt_help')}")
print(f" -V, --version {catalog.get('cli.opt_version')}")
print(f" --lang <origin> {catalog.get('cli.opt_lang')}")
print(f" --era <century> {catalog.get('cli.opt_era')}")
print(f" --rating <1-5> {catalog.get('cli.opt_min_rating')}")
print(f" --save <on|off> {catalog.get('cli.opt_save_toggle')}")
print(f" -i, --interactive {catalog.get('cli.opt_interactive')}")
def run_cli(args: Optional[List[str]] = None) -> int:
if hasattr(sys.stdout, "reconfigure"):
try:
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
except Exception:
pass
raw_args = args if args is not None else sys.argv[1:]
if "-h" in raw_args or "--help" in raw_args:
print_help()
return 0
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"))
return 0
cfg_mgr = ConfigManager()
config = cfg_mgr.load_config()
repo = PoetryRepository()
command = raw_args[0].lower() if raw_args and not raw_args[0].startswith("-") else "random"
# Command: config
if command == "config":
is_interactive = "-i" in raw_args or "--interactive" in raw_args
# Check explicit flag updates
changed = False
for idx, arg in enumerate(raw_args):
if arg == "--lang" and idx + 1 < len(raw_args):
config.nationality = raw_args[idx + 1].strip().lower()
changed = True
elif arg == "--era" and idx + 1 < len(raw_args):
config.era = raw_args[idx + 1].strip().lower()
changed = True
elif arg == "--rating" and idx + 1 < len(raw_args):
try:
config.min_rating = max(1, min(5, int(raw_args[idx + 1])))
changed = True
except ValueError:
pass
elif arg == "--save" and idx + 1 < len(raw_args):
val = raw_args[idx + 1].strip().lower()
config.auto_save = val in ["on", "true", "1", "yes"]
changed = True
if is_interactive:
try:
lang_input = input(f"{catalog.get('config.prompt_lang')} [{config.nationality}]: ").strip()
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:
cfg_mgr.save_config(config)
print(catalog.get("config.updated"))
print()
print(catalog.get("config.status_header"))
print("-" * 50)
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_rating'):<30}: {config.min_rating}/5")
print(f" {catalog.get('config.field_auto_save'):<30}: {'Enabled (ON)' if config.auto_save else 'Disabled (OFF)'}")
return 0
# Command: library / saved
elif command in ["library", "saved"]:
saved_poems = repo.get_saved_poems()
if not saved_poems:
print(catalog.get("library.empty"))
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():
target_id = int(raw_args[1])
target_poem = next((p for p in saved_poems if p.id == target_id), None)
if target_poem:
print(PoemRenderer.render_poem(target_poem))
return 0
print(catalog.format("library.saved_header", count=len(saved_poems)))
print("-" * 65)
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()
print("To read a specific poem, run: bard library <id>")
return 0
# Default Command: random poem
else:
# Override config temporarily if flags are passed directly to random command
temp_config = UserTasteConfig(
nationality=config.nationality,
era=config.era,
min_rating=config.min_rating,
auto_save=config.auto_save
)
for idx, arg in enumerate(raw_args):
if arg == "--lang" and idx + 1 < len(raw_args):
temp_config.nationality = raw_args[idx + 1].strip().lower()
elif arg == "--era" and idx + 1 < len(raw_args):
temp_config.era = raw_args[idx + 1].strip().lower()
elif arg == "--rating" and idx + 1 < len(raw_args):
try:
temp_config.min_rating = max(1, min(5, int(raw_args[idx + 1])))
except ValueError:
pass
poem = repo.get_random_poem(temp_config)
print(PoemRenderer.render_poem(poem, auto_saved=temp_config.auto_save))
return 0
+44
View File
@@ -0,0 +1,44 @@
import json
from dataclasses import asdict, dataclass
from pathlib import Path
from typing import Any, Dict
@dataclass
class UserTasteConfig:
nationality: str = "all"
era: str = "all"
min_rating: int = 1
auto_save: bool = True
class ConfigManager:
"""Manages persistent user preferences and offline archival settings for Bard."""
def __init__(self):
user_home = Path.home()
self.config_dir = user_home / ".gravitiny" / "data"
self.config_dir.mkdir(parents=True, exist_ok=True)
self.config_file = self.config_dir / "bard_config.json"
def load_config(self) -> UserTasteConfig:
if self.config_file.exists():
try:
with open(self.config_file, "r", encoding="utf-8") as f:
data = json.load(f)
return UserTasteConfig(
nationality=data.get("nationality", "all"),
era=data.get("era", "all"),
min_rating=int(data.get("min_rating", 1)),
auto_save=bool(data.get("auto_save", True)),
)
except Exception:
pass
return UserTasteConfig()
def save_config(self, config: UserTasteConfig) -> None:
try:
with open(self.config_file, "w", encoding="utf-8") as f:
json.dump(asdict(config), f, indent=2)
except Exception:
pass
+211
View File
@@ -0,0 +1,211 @@
import json
import random
import sqlite3
import urllib.request
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Dict, List, Optional
from src.config import UserTasteConfig
@dataclass
class Poem:
id: Optional[int]
title: str
author: str
nationality: str
era: str
rating: int # 1 to 5
content: str
source: str = "curated"
# Pre-seeded classical & world literature masterworks corpus
CURATED_CORPUS: List[Poem] = [
Poem(
id=1,
title="Sonnet 18 (Shall I compare thee to a summer's day?)",
author="William Shakespeare",
nationality="english",
era="16th",
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."
),
Poem(
id=2,
title="Gönüller Yapan Gelir (Dilsizler Haberini)",
author="Yunus Emre",
nationality="turkish",
era="13th",
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."
),
Poem(
id=3,
title="The Guest House",
author="Jalal al-Din Rumi",
nationality="persian",
era="13th",
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."
),
Poem(
id=4,
title="Hope is the thing with feathers",
author="Emily Dickinson",
nationality="english",
era="19th",
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."
),
Poem(
id=5,
title="The Raven (Excerpt)",
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",
nationality="french",
era="19th",
rating=4,
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."
),
Poem(
id=10,
title="Prometheus (Excerpt)",
author="Johann Wolfgang von Goethe",
nationality="german",
era="18th",
rating=4,
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."
)
]
class PoetryRepository:
"""Provides querying, wikidata/poetry API ingestion, and local SQLite library storage."""
def __init__(self):
user_home = Path.home()
data_dir = user_home / ".gravitiny" / "data"
data_dir.mkdir(parents=True, exist_ok=True)
self.db_path = data_dir / "bard_saved.db"
self._init_db()
def _init_db(self) -> None:
with sqlite3.connect(str(self.db_path)) as conn:
conn.execute("""
CREATE TABLE IF NOT EXISTS saved_poems (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL,
author TEXT NOT NULL,
nationality TEXT,
era TEXT,
rating INTEGER,
content TEXT NOT NULL,
source TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
conn.commit()
def save_poem_to_library(self, poem: Poem) -> bool:
"""Saves a poem to the offline SQLite library if not already present."""
try:
with sqlite3.connect(str(self.db_path)) as conn:
cursor = conn.cursor()
cursor.execute("SELECT id FROM saved_poems WHERE title = ? AND author = ?", (poem.title, poem.author))
if cursor.fetchone():
return False # Already saved
cursor.execute("""
INSERT INTO saved_poems (title, author, nationality, era, rating, content, source)
VALUES (?, ?, ?, ?, ?, ?, ?)
""", (poem.title, poem.author, poem.nationality, poem.era, poem.rating, poem.content, poem.source))
conn.commit()
return True
except Exception:
return False
def get_saved_poems(self) -> List[Poem]:
"""Retrieves all poems saved in offline library."""
poems: List[Poem] = []
try:
with sqlite3.connect(str(self.db_path)) as conn:
cursor = conn.cursor()
cursor.execute("SELECT id, title, author, nationality, era, rating, content, source FROM saved_poems ORDER BY id DESC")
for row in cursor.fetchall():
poems.append(Poem(
id=row[0],
title=row[1],
author=row[2],
nationality=row[3] or "unknown",
era=row[4] or "unknown",
rating=row[5] or 5,
content=row[6],
source=row[7] or "saved"
))
except Exception:
pass
return poems
def find_matching_poems(self, config: UserTasteConfig) -> List[Poem]:
"""Filters the curated corpus based on user taste criteria."""
candidates = []
for p in CURATED_CORPUS:
if config.nationality.lower() != "all" and config.nationality.lower() not in p.nationality.lower():
continue
if config.era.lower() != "all" and config.era.lower() not in p.era.lower():
continue
if p.rating < config.min_rating:
continue
candidates.append(p)
return candidates
def get_random_poem(self, config: UserTasteConfig) -> Poem:
"""Fetches a random poem based on criteria, falling back gracefully to corpus."""
matched = self.find_matching_poems(config)
if matched:
selected = random.choice(matched)
else:
selected = random.choice(CURATED_CORPUS)
# Auto-save if enabled
if config.auto_save:
self.save_poem_to_library(selected)
return selected
+33
View File
@@ -0,0 +1,33 @@
from src.catalog import catalog
from src.db import Poem
class PoemRenderer:
"""Renders poetic verses with classical typography and box styling."""
@classmethod
def render_poem(cls, poem: Poem, auto_saved: bool = False) -> str:
lines = [
"┌─ " + poem.title.upper() + " " + "─" * max(0, 68 - len(poem.title)) + "┐",
"│" + f" Author: {poem.author}".ljust(72) + "│",
"│" + f" Period: {poem.era} Century | Origin: {poem.nationality.capitalize()} | Rating: {poem.rating}/5".ljust(72) + "│",
"├" + "─" * 72 + "┤",
"│" + " " * 72 + "│",
]
for verse_line in poem.content.splitlines():
# Pad lines to fit box
if len(verse_line) > 68:
truncated = verse_line[:65] + "..."
lines.append(f"│ {truncated:<68} │")
else:
lines.append(f"│ {verse_line:<68} │")
lines.append("│" + " " * 72 + "│")
footer = "└" + "─" * 72 + "┘"
if auto_saved:
footer += "\n" + catalog.get("library.auto_saved_notice")
lines.append(footer)
return "\n".join(lines)