VocabLine / api_words.py
dayuian's picture
Create api_words.py
04a8968 verified
from flask import Flask, request, jsonify
from vocab import get_words_from_source
from sentences import get_sentence, save_sentence
from ai_sentence import generate_sentence, MODEL_LIST
import random
app = Flask(__name__)
@app.route('/api/words', methods=['GET'])
def handle_words():
action = request.args.get('action')
source = request.args.get('source', 'common3000')
num = int(request.args.get('num', 5))
word = request.args.get('word')
model = request.args.get('model', 'gpt2')
if action == 'daily':
words_data = get_words_from_source(source)
selected_words = random.sample(words_data, 30)
result = []
for word_data in selected_words:
w = word_data['word']
phonetic = word_data['phonetic']
sentence_data = get_sentence(w)
sentence = sentence_data[2] if sentence_data else "例句暫無"
result.append({"word": w, "phonetic": phonetic, "sentence": sentence})
return jsonify({"words": result})
elif action == 'random':
words_data = get_words_from_source(source)
selected_words = random.sample(words_data, num)
result = []
for word_data in selected_words:
w = word_data['word']
phonetic = word_data['phonetic']
sentence_data = get_sentence(w)
sentence = sentence_data[2] if sentence_data else "例句暫無"
result.append({"word": w, "phonetic": phonetic, "sentence": sentence})
return jsonify({"words": result})
elif action == 'query':
if not word:
return jsonify({"error": "缺少 word 參數"}), 400
sentence_data = get_sentence(word)
if sentence_data:
return jsonify({"word": word, "phonetic": sentence_data[1], "sentence": sentence_data[2]})
else:
return jsonify({"word": word, "phonetic": "未知", "sentence": "例句暫無"})
elif action == 'ai_generate':
if not word:
return jsonify({"error": "缺少 word 參數"}), 400
if model not in MODEL_LIST:
return jsonify({"error": "無效的模型"}), 400
try:
sentence = generate_sentence(word, model)
save_sentence(word, "未知", sentence, source="ai", model=model)
return jsonify({"word": word, "phonetic": "未知", "sentence": sentence})
except Exception as e:
return jsonify({"error": f"AI 生成失敗: {str(e)}"}), 500
else:
return jsonify({"error": "無效的 action"}), 400
if __name__ == '__main__':
app.run(host='0.0.0.0', port=7860)