File size: 2,632 Bytes
04a8968
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
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)