Add app.py
Browse files
app.py
ADDED
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import logging
|
2 |
+
from flask import Flask, request, jsonify
|
3 |
+
from transformers import pipeline
|
4 |
+
import gradio as gr
|
5 |
+
import os
|
6 |
+
import torch
|
7 |
+
|
8 |
+
# Cấu hình logging
|
9 |
+
logging.basicConfig(level=logging.INFO)
|
10 |
+
|
11 |
+
app = Flask(__name__)
|
12 |
+
|
13 |
+
# Load mô hình
|
14 |
+
logging.info("Loading nguyenvulebinh/vi-mrc-base...")
|
15 |
+
qa_pipeline = pipeline(
|
16 |
+
"question-answering",
|
17 |
+
model="nguyenvulebinh/vi-mrc-base",
|
18 |
+
device=0 if torch.cuda.is_available() else -1
|
19 |
+
)
|
20 |
+
|
21 |
+
@app.route("/api/answer", methods=["POST"])
|
22 |
+
def answer():
|
23 |
+
try:
|
24 |
+
data = request.json
|
25 |
+
question = data.get("question")
|
26 |
+
context = data.get("context")
|
27 |
+
if not question or not context:
|
28 |
+
return jsonify({"error": "Missing question or context"}), 400
|
29 |
+
result = qa_pipeline(question=question, context=context)
|
30 |
+
logging.info(f"Question: {question}, Answer: {result['answer']}")
|
31 |
+
return jsonify({"answer": result["answer"]})
|
32 |
+
except Exception as e:
|
33 |
+
logging.error(f"API error: {e}")
|
34 |
+
return jsonify({"error": str(e)}), 500
|
35 |
+
|
36 |
+
# Giao diện Gradio để thử nghiệm
|
37 |
+
def gradio_answer(question, context):
|
38 |
+
result = qa_pipeline(question=question, context=context)
|
39 |
+
return result["answer"]
|
40 |
+
|
41 |
+
iface = gr.Interface(
|
42 |
+
fn=gradio_answer,
|
43 |
+
inputs=["text", "text"],
|
44 |
+
outputs="text",
|
45 |
+
title="AgriBot: Hỏi đáp nông nghiệp",
|
46 |
+
description="Nhập câu hỏi và ngữ cảnh để nhận câu trả lời về nông nghiệp."
|
47 |
+
)
|
48 |
+
|
49 |
+
if __name__ == "__main__":
|
50 |
+
# Chạy Flask trên port 7860 (mặc định của Hugging Face Spaces)
|
51 |
+
app.run(host="0.0.0.0", port=7860)
|