Files
bard/src/db.py
T

212 lines
10 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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