Spaces:
Build error
Build error
Update app.py
Browse files
app.py
CHANGED
|
@@ -5,31 +5,30 @@ import json
|
|
| 5 |
import io
|
| 6 |
from PIL import Image
|
| 7 |
import torch
|
| 8 |
-
from transformers import AutoProcessor, AutoModelForCausalLM, BitsAndBytesConfig
|
| 9 |
|
| 10 |
-
# --- CẤU HÌNH VÀ TẢI MÔ HÌNH ---
|
| 11 |
-
# Sử dụng GPU nếu có, nếu không thì dùng CPU
|
| 12 |
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 13 |
print(f"Đang sử dụng thiết bị: {device}")
|
| 14 |
|
| 15 |
-
# 1. Tải mô hình OCR (
|
| 16 |
-
print("Đang tải mô hình OCR (Florence-2)...")
|
| 17 |
-
ocr_model_id = "microsoft/Florence-2-
|
| 18 |
ocr_processor = AutoProcessor.from_pretrained(ocr_model_id, trust_remote_code=True)
|
| 19 |
quantization_config = BitsAndBytesConfig(load_in_4bit=True)
|
| 20 |
ocr_model = AutoModelForCausalLM.from_pretrained(
|
| 21 |
ocr_model_id,
|
| 22 |
-
device_map=
|
| 23 |
torch_dtype=torch.bfloat16,
|
| 24 |
quantization_config=quantization_config,
|
| 25 |
trust_remote_code=True
|
| 26 |
)
|
| 27 |
print("Tải xong mô hình OCR.")
|
| 28 |
|
| 29 |
-
# 2. Tải mô hình LLM (
|
| 30 |
-
print("Đang tải mô hình LLM (
|
| 31 |
-
|
| 32 |
-
|
| 33 |
llm_pipeline = pipeline(
|
| 34 |
"text-generation",
|
| 35 |
model=llm_model_id,
|
|
@@ -38,10 +37,10 @@ llm_pipeline = pipeline(
|
|
| 38 |
)
|
| 39 |
print("Tải xong mô hình LLM.")
|
| 40 |
|
| 41 |
-
|
|
|
|
| 42 |
|
| 43 |
def run_ocr(image: Image.Image) -> str:
|
| 44 |
-
"""Hàm chạy OCR để đọc chữ từ ảnh"""
|
| 45 |
if image is None: return "Lỗi: Vui lòng cung cấp hình ảnh."
|
| 46 |
prompt = "<OCR>"
|
| 47 |
inputs = ocr_processor(text=prompt, images=image, return_tensors="pt").to(device)
|
|
@@ -56,7 +55,6 @@ def run_ocr(image: Image.Image) -> str:
|
|
| 56 |
return parsed_text['<OCR>']
|
| 57 |
|
| 58 |
def extract_order_from_text(text: str) -> dict:
|
| 59 |
-
"""Hàm chạy LLM để trích xuất thông tin từ văn bản"""
|
| 60 |
prompt = f"""You are an expert assistant for extracting order information from unstructured text. Based on the following text, extract the information and return it as a valid JSON object. The JSON object must contain: "ten_khach_hang": The customer's name (null if not found). "danh_sach_hang": An array of items. Each item must have: "ten_hang", "so_luong" (as a number), "don_vi", "ma_hang" (null if not found), and "ghi_chu" (null if not found). Output only the JSON object, with no additional text or explanation. --- Text Content --- {text} --- End Text Content ---"""
|
| 61 |
messages = [{"role": "system", "content": "You are an assistant that only outputs valid JSON."}, {"role": "user", "content": prompt},]
|
| 62 |
terminators = [llm_pipeline.tokenizer.eos_token_id, llm_pipeline.tokenizer.convert_tokens_to_ids("<|eot_id|>")]
|
|
@@ -66,7 +64,6 @@ def extract_order_from_text(text: str) -> dict:
|
|
| 66 |
except json.JSONDecodeError: return {"error": "AI trả về định dạng không hợp lệ", "raw_response": response_text}
|
| 67 |
|
| 68 |
def create_excel_file(order_data: dict):
|
| 69 |
-
"""Hàm tạo file Excel từ dữ liệu đã trích xuất"""
|
| 70 |
if not order_data or "danh_sach_hang" not in order_data or not order_data["danh_sach_hang"]: return None
|
| 71 |
flat_data = [{'Khách hàng': order_data.get('ten_khach_hang', 'N/A'), **item} for item in order_data['danh_sach_hang']]
|
| 72 |
df = pd.DataFrame(flat_data)
|
|
@@ -77,7 +74,6 @@ def create_excel_file(order_data: dict):
|
|
| 77 |
return (filename, output.getvalue())
|
| 78 |
|
| 79 |
def process_image_and_extract(image):
|
| 80 |
-
"""Hàm tổng hợp, gọi OCR rồi đến LLM"""
|
| 81 |
if image is None: return "Vui lòng dán ảnh vào.", None, None
|
| 82 |
extracted_text = run_ocr(image)
|
| 83 |
if not extracted_text.strip(): return "Không đọc được chữ từ hình ảnh.", None, None
|
|
@@ -91,7 +87,7 @@ def process_image_and_extract(image):
|
|
| 91 |
return extracted_text, df_display, filename
|
| 92 |
else: return extracted_text, df_display, None
|
| 93 |
|
| 94 |
-
# --- XÂY DỰNG GIAO DIỆN GRADIO ---
|
| 95 |
|
| 96 |
with gr.Blocks(theme=gr.themes.Soft()) as app:
|
| 97 |
gr.Markdown("# Ứng dụng Trích xuất Đơn hàng từ Ảnh chụp màn hình")
|
|
|
|
| 5 |
import io
|
| 6 |
from PIL import Image
|
| 7 |
import torch
|
| 8 |
+
from transformers import AutoProcessor, AutoModelForCausalLM, BitsAndBytesConfig, pipeline
|
| 9 |
|
| 10 |
+
# --- CẤU HÌNH VÀ TẢI MÔ HÌNH (PHIÊN BẢN NHẸ HƠN) ---
|
|
|
|
| 11 |
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 12 |
print(f"Đang sử dụng thiết bị: {device}")
|
| 13 |
|
| 14 |
+
# 1. Tải mô hình OCR (Sử dụng phiên bản 'base' thay vì 'large')
|
| 15 |
+
print("Đang tải mô hình OCR (Florence-2-base)...")
|
| 16 |
+
ocr_model_id = "microsoft/Florence-2-base" # THAY ĐỔI 1: Dùng model base nhỏ hơn
|
| 17 |
ocr_processor = AutoProcessor.from_pretrained(ocr_model_id, trust_remote_code=True)
|
| 18 |
quantization_config = BitsAndBytesConfig(load_in_4bit=True)
|
| 19 |
ocr_model = AutoModelForCausalLM.from_pretrained(
|
| 20 |
ocr_model_id,
|
| 21 |
+
device_map="auto", # Để transformers tự quyết định device map
|
| 22 |
torch_dtype=torch.bfloat16,
|
| 23 |
quantization_config=quantization_config,
|
| 24 |
trust_remote_code=True
|
| 25 |
)
|
| 26 |
print("Tải xong mô hình OCR.")
|
| 27 |
|
| 28 |
+
# 2. Tải mô hình LLM (Sử dụng phiên bản đã được nén sẵn)
|
| 29 |
+
print("Đang tải mô hình LLM (Unsloth Llama 3 8B 4-bit)...")
|
| 30 |
+
# THAY ĐỔI 2: Dùng phiên bản Llama-3 đã được nén sẵn của Unsloth, rất hiệu quả về bộ nhớ
|
| 31 |
+
llm_model_id = "unsloth/llama-3-8b-Instruct-bnb-4bit"
|
| 32 |
llm_pipeline = pipeline(
|
| 33 |
"text-generation",
|
| 34 |
model=llm_model_id,
|
|
|
|
| 37 |
)
|
| 38 |
print("Tải xong mô hình LLM.")
|
| 39 |
|
| 40 |
+
|
| 41 |
+
# --- CÁC HÀM XỬ LÝ (GIỮ NGUYÊN) ---
|
| 42 |
|
| 43 |
def run_ocr(image: Image.Image) -> str:
|
|
|
|
| 44 |
if image is None: return "Lỗi: Vui lòng cung cấp hình ảnh."
|
| 45 |
prompt = "<OCR>"
|
| 46 |
inputs = ocr_processor(text=prompt, images=image, return_tensors="pt").to(device)
|
|
|
|
| 55 |
return parsed_text['<OCR>']
|
| 56 |
|
| 57 |
def extract_order_from_text(text: str) -> dict:
|
|
|
|
| 58 |
prompt = f"""You are an expert assistant for extracting order information from unstructured text. Based on the following text, extract the information and return it as a valid JSON object. The JSON object must contain: "ten_khach_hang": The customer's name (null if not found). "danh_sach_hang": An array of items. Each item must have: "ten_hang", "so_luong" (as a number), "don_vi", "ma_hang" (null if not found), and "ghi_chu" (null if not found). Output only the JSON object, with no additional text or explanation. --- Text Content --- {text} --- End Text Content ---"""
|
| 59 |
messages = [{"role": "system", "content": "You are an assistant that only outputs valid JSON."}, {"role": "user", "content": prompt},]
|
| 60 |
terminators = [llm_pipeline.tokenizer.eos_token_id, llm_pipeline.tokenizer.convert_tokens_to_ids("<|eot_id|>")]
|
|
|
|
| 64 |
except json.JSONDecodeError: return {"error": "AI trả về định dạng không hợp lệ", "raw_response": response_text}
|
| 65 |
|
| 66 |
def create_excel_file(order_data: dict):
|
|
|
|
| 67 |
if not order_data or "danh_sach_hang" not in order_data or not order_data["danh_sach_hang"]: return None
|
| 68 |
flat_data = [{'Khách hàng': order_data.get('ten_khach_hang', 'N/A'), **item} for item in order_data['danh_sach_hang']]
|
| 69 |
df = pd.DataFrame(flat_data)
|
|
|
|
| 74 |
return (filename, output.getvalue())
|
| 75 |
|
| 76 |
def process_image_and_extract(image):
|
|
|
|
| 77 |
if image is None: return "Vui lòng dán ảnh vào.", None, None
|
| 78 |
extracted_text = run_ocr(image)
|
| 79 |
if not extracted_text.strip(): return "Không đọc được chữ từ hình ảnh.", None, None
|
|
|
|
| 87 |
return extracted_text, df_display, filename
|
| 88 |
else: return extracted_text, df_display, None
|
| 89 |
|
| 90 |
+
# --- XÂY DỰNG GIAO DIỆN GRADIO (GIỮ NGUYÊN) ---
|
| 91 |
|
| 92 |
with gr.Blocks(theme=gr.themes.Soft()) as app:
|
| 93 |
gr.Markdown("# Ứng dụng Trích xuất Đơn hàng từ Ảnh chụp màn hình")
|