Update app.py
Browse files
app.py
CHANGED
|
@@ -1,132 +1,111 @@
|
|
| 1 |
-
# ✅ app.py - 升級 TinyLlama-1.1B-Chat 版本
|
| 2 |
-
|
| 3 |
-
import json
|
| 4 |
-
import os
|
| 5 |
import gradio as gr
|
| 6 |
-
import faiss
|
| 7 |
import torch
|
| 8 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
from sentence_transformers import SentenceTransformer
|
| 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 |
-
qa_data = json.load(f)
|
| 37 |
-
with open(DOCS_FILE, "r", encoding="utf-8") as f:
|
| 38 |
-
docs = json.load(f)
|
| 39 |
-
index = faiss.read_index(VECTOR_FILE)
|
| 40 |
-
embedder = SentenceTransformer(EMBED_MODEL)
|
| 41 |
-
tokenizer = AutoTokenizer.from_pretrained(GEN_MODEL, trust_remote_code=True)
|
| 42 |
-
model = AutoModelForCausalLM.from_pretrained(GEN_MODEL, trust_remote_code=True).to("cuda" if torch.cuda.is_available() else "cpu")
|
| 43 |
-
model.eval()
|
| 44 |
-
|
| 45 |
-
# ✅ QA 快速匹配
|
| 46 |
-
|
| 47 |
-
def retrieve_qa_context(user_input):
|
| 48 |
for item in qa_data:
|
| 49 |
if item["match"] == "OR":
|
| 50 |
-
if any(k in
|
| 51 |
return item["response"]
|
| 52 |
elif item["match"] == "AND":
|
| 53 |
-
if all(k in
|
| 54 |
return item["response"]
|
| 55 |
return None
|
| 56 |
|
| 57 |
-
#
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
[
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
問題:
|
| 84 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 85 |
|
| 86 |
-
|
| 87 |
-
|
|
|
|
| 88 |
|
| 89 |
-
|
| 90 |
-
|
|
|
|
| 91 |
|
| 92 |
-
|
| 93 |
-
|
|
|
|
| 94 |
|
| 95 |
-
|
| 96 |
-
回答:可從台南火車站搭乘公車,或經永康交流道開車約 10 分鐘抵達。
|
| 97 |
|
| 98 |
-
|
| 99 |
-
|
| 100 |
|
| 101 |
-
[
|
| 102 |
-
{user_input}
|
| 103 |
-
"""
|
| 104 |
-
inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
|
| 105 |
-
outputs = model.generate(**inputs, max_new_tokens=150)
|
| 106 |
-
response = tokenizer.decode(outputs[0], skip_special_tokens=True).strip()
|
| 107 |
-
for line in response.splitlines()[::-1]:
|
| 108 |
-
if len(line.strip()) > 10 and not line.startswith("你是"):
|
| 109 |
-
return line.strip()
|
| 110 |
-
return response[-90:]
|
| 111 |
|
| 112 |
-
|
|
|
|
| 113 |
|
| 114 |
-
def answer(user_input):
|
| 115 |
-
direct = retrieve_qa_context(user_input)
|
| 116 |
-
if direct:
|
| 117 |
-
return direct
|
| 118 |
-
else:
|
| 119 |
-
context = search_context_faiss(user_input)
|
| 120 |
-
return generate_answer(user_input, context)
|
| 121 |
-
|
| 122 |
-
# ✅ Gradio 介面
|
| 123 |
-
interface = gr.Interface(
|
| 124 |
-
fn=answer,
|
| 125 |
-
inputs=gr.Textbox(lines=2, placeholder="請輸入與南臺科技大學相關的問題..."),
|
| 126 |
-
outputs="text",
|
| 127 |
-
title="南臺科技大學 問答機器人(TinyLlama 1.1B)",
|
| 128 |
-
description="支援 QA 關鍵字與語意檢索,自動建立嵌入庫,輸出繁體中文自然回答。",
|
| 129 |
-
theme="default"
|
| 130 |
-
)
|
| 131 |
-
|
| 132 |
-
interface.launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
|
|
|
| 2 |
import torch
|
| 3 |
+
import json
|
| 4 |
+
import tempfile
|
| 5 |
+
import faiss
|
| 6 |
+
from gtts import gTTS
|
| 7 |
+
from transformers import pipeline, AutoTokenizer, AutoModelForCausalLM
|
| 8 |
from sentence_transformers import SentenceTransformer
|
| 9 |
+
import numpy as np
|
| 10 |
+
|
| 11 |
+
# 模型
|
| 12 |
+
MODEL_NAME = "openbmb/MiniCPM-2B-sft-bf16"
|
| 13 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME, trust_remote_code=True)
|
| 14 |
+
model = AutoModelForCausalLM.from_pretrained(MODEL_NAME, trust_remote_code=True).eval()
|
| 15 |
+
|
| 16 |
+
# 語音辨識 Whisper
|
| 17 |
+
asr = pipeline("automatic-speech-recognition", model="openai/whisper-small", device=0 if torch.cuda.is_available() else -1)
|
| 18 |
+
|
| 19 |
+
# 向量模型
|
| 20 |
+
encoder = SentenceTransformer("shibing624/text2vec-base-chinese")
|
| 21 |
+
index = faiss.read_index("vector_store.faiss")
|
| 22 |
+
with open("documents.json", "r", encoding="utf-8") as f:
|
| 23 |
+
documents = json.load(f)
|
| 24 |
+
|
| 25 |
+
# QA固定問答(可選)
|
| 26 |
+
try:
|
| 27 |
+
with open("qa.json", "r", encoding="utf-8") as f:
|
| 28 |
+
qa_data = json.load(f)
|
| 29 |
+
except:
|
| 30 |
+
qa_data = []
|
| 31 |
+
|
| 32 |
+
# QA match(選擇性)
|
| 33 |
+
def match_qa(user_input):
|
| 34 |
+
cleaned_input = user_input.replace(" ", "")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
for item in qa_data:
|
| 36 |
if item["match"] == "OR":
|
| 37 |
+
if any(k.replace(" ", "") in cleaned_input for k in item["keywords"]):
|
| 38 |
return item["response"]
|
| 39 |
elif item["match"] == "AND":
|
| 40 |
+
if all(k.replace(" ", "") in cleaned_input for k in item["keywords"]):
|
| 41 |
return item["response"]
|
| 42 |
return None
|
| 43 |
|
| 44 |
+
# 文字生成
|
| 45 |
+
def generate_answer(text):
|
| 46 |
+
messages = [{"role": "user", "content": text}]
|
| 47 |
+
input_ids = tokenizer.apply_chat_template(messages, return_tensors="pt")
|
| 48 |
+
with torch.no_grad():
|
| 49 |
+
outputs = model.generate(input_ids, max_new_tokens=200)
|
| 50 |
+
response = tokenizer.decode(outputs[0][input_ids.shape[-1]:], skip_special_tokens=True)
|
| 51 |
+
return response.strip()
|
| 52 |
+
|
| 53 |
+
# 向量比對
|
| 54 |
+
def search_vector_db(query, top_k=1):
|
| 55 |
+
q_vec = encoder.encode([query])
|
| 56 |
+
D, I = index.search(np.array(q_vec), top_k)
|
| 57 |
+
results = [documents[i] for i in I[0] if i < len(documents)]
|
| 58 |
+
return results
|
| 59 |
+
|
| 60 |
+
# 回答邏輯整合
|
| 61 |
+
def answer(text):
|
| 62 |
+
# 1. QA 固定資料庫
|
| 63 |
+
fixed = match_qa(text)
|
| 64 |
+
if fixed:
|
| 65 |
+
return fixed
|
| 66 |
+
|
| 67 |
+
# 2. RAG 取資料輔助
|
| 68 |
+
related_docs = search_vector_db(text)
|
| 69 |
+
context = "\n".join(related_docs)
|
| 70 |
+
prompt = f"以下是一些關於南臺科技大學的資料:\n{context}\n\n根據上面的資料,請用中文簡短回答這個問題:{text}"
|
| 71 |
+
return generate_answer(prompt)
|
| 72 |
+
|
| 73 |
+
# TTS
|
| 74 |
+
def text_to_speech(text):
|
| 75 |
+
tts = gTTS(text, lang='zh')
|
| 76 |
+
tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".mp3")
|
| 77 |
+
tts.save(tmp.name)
|
| 78 |
+
return tmp.name
|
| 79 |
+
|
| 80 |
+
# 主流程
|
| 81 |
+
def voice_assistant(audio_input=None, text_input=None):
|
| 82 |
+
if audio_input:
|
| 83 |
+
result = asr(audio_input)
|
| 84 |
+
user_text = result["text"]
|
| 85 |
+
elif text_input:
|
| 86 |
+
user_text = text_input
|
| 87 |
+
else:
|
| 88 |
+
return "請輸入語音或文字", None
|
| 89 |
|
| 90 |
+
response = answer(user_text)
|
| 91 |
+
speech_file = text_to_speech(response)
|
| 92 |
+
return response, speech_file
|
| 93 |
|
| 94 |
+
# Gradio UI
|
| 95 |
+
with gr.Blocks() as demo:
|
| 96 |
+
gr.Markdown("## 🎓 南臺科技大學 AI 語音助理(MiniCPM + Whisper + 向量式 RAG)")
|
| 97 |
|
| 98 |
+
with gr.Row():
|
| 99 |
+
mic = gr.Audio(source="microphone", type="filepath", label="語音輸入")
|
| 100 |
+
text_input = gr.Textbox(label="文字輸入", placeholder="請輸入您的問題")
|
| 101 |
|
| 102 |
+
submit_btn = gr.Button("送出")
|
|
|
|
| 103 |
|
| 104 |
+
output_text = gr.Textbox(label="回答")
|
| 105 |
+
output_audio = gr.Audio(label="語音播放", type="filepath")
|
| 106 |
|
| 107 |
+
submit_btn.click(fn=voice_assistant, inputs=[mic, text_input], outputs=[output_text, output_audio])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 108 |
|
| 109 |
+
if __name__ == "__main__":
|
| 110 |
+
demo.launch()
|
| 111 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|