import sqlite3
from flask import Flask, request, jsonify, render_template, redirect
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM, Dense, Embedding
import tensorflow as tf
import numpy as np
print(tf.__version__)
app = Flask(__name__)
vocab_size = 5000
embedding_dim = 64
lstm_units = 64
model = Sequential([
Embedding(input_dim=10000, output_dim=128),
LSTM(units=128),
Dense(units=1, activation='sigmoid')
])
model.summary()
def dummy_tokenizer(text):
return np.array([0] * len(text))
def dummy_detokenizer(tokens):
return ''.join(['a'] * len(tokens))
def text_generator(prompt, max_length=150):
input_tokens = dummy_tokenizer(prompt)
generated_tokens = []
for _ in range(max_length):
preds = model.predict(np.array([input_tokens]))
next_token = np.argmax(preds, axis=-1)[0]
if next_token == 0:
break
generated_tokens.append(next_token)
input_tokens = np.append(input_tokens, next_token)
return dummy_detokenizer(generated_tokens)
def init_db():
conn = sqlite3.connect('knowledge.db')
cursor = conn.cursor()
cursor.execute('''CREATE TABLE IF NOT EXISTS knowledge
(id INTEGER PRIMARY KEY, title TEXT, content TEXT, tags TEXT)''')
conn.commit()
conn.close()
@app.route('/add_knowledge', methods=['POST'])
def add_knowledge():
title = request.form['title']
content = request.form['content']
tags = request.form['tags']
conn = sqlite3.connect('knowledge.db')
cursor = conn.cursor()
cursor.execute("INSERT INTO knowledge (title, content, tags) VALUES (?, ?, ?)",
(title, content, tags))
conn.commit()
conn.close()
return '知識添加成功!', 201
@app.route('/wiki/<path:subpath>', methods=['GET'])
def wiki(subpath):
tag = request.args.get('tag')
conn = sqlite3.connect('knowledge.db')
cursor = conn.cursor()
cursor.execute("SELECT * FROM knowledge WHERE tags LIKE ?", ('%' + tag + '%',))
conn.close()
return redirect(f'http://localhost/{subpath}', code=302)
@app.route('/update_knowledge/<int:id>', methods=['PUT'])
def update_knowledge(id):
content = request.form['content']
conn = sqlite3.connect('knowledge.db')
cursor = conn.cursor()
cursor.execute("UPDATE knowledge SET content = ? WHERE id = ?", (content, id))
conn.commit()
conn.close()
return '知識更新成功!', 200
@app.route('/delete_knowledge/<int:id>', methods=['DELETE'])
def delete_knowledge(id):
conn = sqlite3.connect('knowledge.db')
cursor = conn.cursor()
cursor.execute("DELETE FROM knowledge WHERE id = ?", (id,))
conn.commit()
conn.close()
return '知識刪除成功!', 200
@app.route('/')
def index():
return render_template('index.html')
@app.route('/ask', methods=['POST'])
def ask():
question = request.form.get('question')
try:
answer = text_generator(question)
except Exception as e:
return jsonify({'answer': '錯誤: ' + str(e)}), 501
return jsonify({'answer': answer})
if __name__ == '__main__':
init_db()
app.run(debug=True, port=5001)
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM, Dense, Embedding
怎麼試都說無法解析匯入,重新安裝也沒用
先註解掉,確認一下版本吧
應該是版本差異
# from tensorflow.keras.models import Sequential
# from tensorflow.keras.layers import LSTM, Dense, Embedding
import tensorflow as tf
print(tf.__version__)
以這幾篇來看似乎新版的已不在 model 下
Create the model
tf.keras.Sequential
The Sequential class
from tensorflow.keras import Sequential
tf.keras.Sequential(
layers=None, trainable=True, name=None
)
謝謝
我找到方法了,改成這樣就行
from tf_keras.models import Sequential
from tf_keras.layers import LSTM, Dense, Embedding