import sqlite3 import os DATA_DIR = "./data" DB_PATH = os.path.join(DATA_DIR, "sentences.db") # 初始化資料表(保險起見,但你本地應該已建過了) def init_db(): conn = sqlite3.connect(DB_PATH) c = conn.cursor() c.execute(''' CREATE TABLE IF NOT EXISTS sentences ( word TEXT, phonetic TEXT, sentence TEXT, source TEXT, model TEXT, created_at DATETIME DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (word, source, model) ) ''') conn.commit() conn.close() # 查詢某個單字的所有例句,包含來源 & 模型 def get_sentences_by_word(word): conn = sqlite3.connect(DB_PATH) c = conn.cursor() c.execute('SELECT word, phonetic, sentence, source, model FROM sentences WHERE word=?', (word,)) results = c.fetchall() conn.close() return results # 儲存句子(GPT 生成 or 句庫) def save_sentence(word, phonetic, sentence, source, model): conn = sqlite3.connect(DB_PATH) c = conn.cursor() c.execute(''' INSERT INTO sentences (word, phonetic, sentence, source, model) VALUES (?, ?, ?, ?, ?) ON CONFLICT(word, source, model) DO UPDATE SET sentence=excluded.sentence, phonetic=excluded.phonetic ''', (word, phonetic, sentence, source, model)) conn.commit() conn.close()