Spaces:
Sleeping
Sleeping
Toan2004-ai commited on
Commit ·
d67e63b
0
Parent(s):
sync code
Browse files- Dockerfile +15 -0
- app.py +77 -0
- main.py +385 -0
- requirements.txt +10 -0
Dockerfile
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.11-slim
|
| 2 |
+
|
| 3 |
+
WORKDIR /app
|
| 4 |
+
|
| 5 |
+
COPY requirements.txt .
|
| 6 |
+
RUN pip install --no-cache-dir -r requirements.txt
|
| 7 |
+
|
| 8 |
+
COPY . .
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
# TRƯỜNG HỢP A: Nếu bạn muốn chạy giao diện Web Gradio
|
| 12 |
+
# CMD ["python", "app.py"]
|
| 13 |
+
|
| 14 |
+
# TRƯỜNG HỢP B: Nếu bạn đã chuyển main.py thành API FastAPI
|
| 15 |
+
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8080"]
|
app.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
|
| 3 |
+
import gradio as gr
|
| 4 |
+
import json
|
| 5 |
+
import sys
|
| 6 |
+
|
| 7 |
+
sys.path.append(".")
|
| 8 |
+
# Tải hàm xử lý lõi từ file main.py chung thư mục
|
| 9 |
+
from main import final_process_eme_technical_guided
|
| 10 |
+
|
| 11 |
+
def parse_energy_plan(text_input):
|
| 12 |
+
if not text_input or not text_input.strip():
|
| 13 |
+
return json.dumps({"error": "Đầu vào không được để trống"}, indent=2)
|
| 14 |
+
|
| 15 |
+
try:
|
| 16 |
+
# --- TẦNG GIẢI MÃ ĐỒNG BỘ PAYLOAD CLOUD ---
|
| 17 |
+
try:
|
| 18 |
+
parsed_json = json.loads(text_input)
|
| 19 |
+
|
| 20 |
+
# Kiểm tra xem người dùng có paste cấu trúc {"instances": [{"raw_text": "..."}]} của GCP không
|
| 21 |
+
if isinstance(parsed_json, dict) and "instances" in parsed_json:
|
| 22 |
+
raw_payload = parsed_json["instances"][0]["raw_text"]
|
| 23 |
+
|
| 24 |
+
try:
|
| 25 |
+
# Nếu raw_text bên trong lại là một chuỗi JSON dạng chuỗi, giải mã tiếp một lần nữa
|
| 26 |
+
raw_text_processed = json.loads(raw_payload)
|
| 27 |
+
if isinstance(raw_text_processed, (dict, list)):
|
| 28 |
+
final_input = json.dumps(raw_text_processed)
|
| 29 |
+
else:
|
| 30 |
+
final_input = str(raw_payload)
|
| 31 |
+
except Exception:
|
| 32 |
+
final_input = str(raw_payload)
|
| 33 |
+
else:
|
| 34 |
+
final_input = text_input
|
| 35 |
+
except json.JSONDecodeError:
|
| 36 |
+
# Nếu người dùng nhập văn bản thô (Unstructured Text)
|
| 37 |
+
final_input = text_input
|
| 38 |
+
|
| 39 |
+
# --- TẦNG XỬ LÝ ENGINE & TRẢ KẾT QUẢ ---
|
| 40 |
+
result = final_process_eme_technical_guided(final_input)
|
| 41 |
+
|
| 42 |
+
# SỬA LỖI TẠI ĐÂY: Kiểm tra nếu kết quả trả về là Pydantic Object thì chuyển về dict
|
| 43 |
+
if hasattr(result, "model_dump"):
|
| 44 |
+
result_dict = result.model_dump()
|
| 45 |
+
elif hasattr(result, "dict"):
|
| 46 |
+
result_dict = result.dict() # Hỗ trợ tương thích Pydantic v1 nếu có
|
| 47 |
+
else:
|
| 48 |
+
result_dict = result # Trường hợp đã là dict sẵn
|
| 49 |
+
|
| 50 |
+
return json.dumps(result_dict, indent=2, ensure_ascii=False)
|
| 51 |
+
|
| 52 |
+
except Exception as e:
|
| 53 |
+
return json.dumps({"error": str(e)}, indent=2, ensure_ascii=False)
|
| 54 |
+
|
| 55 |
+
# --- CẤU HÌNH GIAO DIỆN GRADIO ---
|
| 56 |
+
demo = gr.Interface(
|
| 57 |
+
fn=parse_energy_plan,
|
| 58 |
+
inputs=gr.Textbox(
|
| 59 |
+
label="Energy Plan Input (Text thô hoặc Cấu trúc JSON Cloud)",
|
| 60 |
+
placeholder="Dán văn bản thô của gói cước, file plan.json hoặc cấu trúc chứa {'instances': [...]} tại đây...",
|
| 61 |
+
lines=12
|
| 62 |
+
),
|
| 63 |
+
outputs=gr.Code(label="Extracted Schema (Đầu ra chuẩn hóa)", language="json"),
|
| 64 |
+
title="⚡ Volta Energy Plan Parser",
|
| 65 |
+
description="Hệ thống trích xuất dữ liệu có cấu trúc từ các gói năng lượng Úc - Đồng bộ kiểm thử đa nền tảng."
|
| 66 |
+
)
|
| 67 |
+
|
| 68 |
+
if __name__ == "__main__":
|
| 69 |
+
port = int(os.environ.get("PORT", 8080))
|
| 70 |
+
|
| 71 |
+
print(f"--- [Cloud Run] Đang khởi chạy giao diện Gradio trên cổng {port}... ---")
|
| 72 |
+
|
| 73 |
+
demo.launch(
|
| 74 |
+
server_name="0.0.0.0",
|
| 75 |
+
server_port=port,
|
| 76 |
+
share=False
|
| 77 |
+
)
|
main.py
ADDED
|
@@ -0,0 +1,385 @@
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI
|
| 2 |
+
from pydantic import BaseModel, ValidationError
|
| 3 |
+
from typing import List, Optional
|
| 4 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM
|
| 5 |
+
from json_repair import repair_json
|
| 6 |
+
import torch, json, re, os
|
| 7 |
+
|
| 8 |
+
# Tối ưu hóa số luồng xử lý trên CPU của Cloud Run
|
| 9 |
+
torch.set_num_threads(4)
|
| 10 |
+
|
| 11 |
+
MODEL_PATH = "NLP-Volta-Energy-AI/volta-energy-parser"
|
| 12 |
+
HF_TOKEN = os.environ.get("HF_TOKEN")
|
| 13 |
+
|
| 14 |
+
# Khởi tạo biến toàn cục ở trạng thái rỗng
|
| 15 |
+
model = None
|
| 16 |
+
tokenizer = None
|
| 17 |
+
|
| 18 |
+
# Hàm Lazy Loading: Chỉ tải khi có request đầu tiên gọi đến
|
| 19 |
+
def get_model_and_tokenizer():
|
| 20 |
+
global model, tokenizer
|
| 21 |
+
if model is None or tokenizer is None:
|
| 22 |
+
print("--- [LAZY LOADING] Phát hiện request đầu tiên. Bắt đầu tải mô hình từ Hugging Face... ---")
|
| 23 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 24 |
+
MODEL_PATH, trust_remote_code=True, token=HF_TOKEN
|
| 25 |
+
)
|
| 26 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 27 |
+
MODEL_PATH,
|
| 28 |
+
torch_dtype=torch.float32, # Giữ nguyên float32 để tính toán chuẩn trên CPU
|
| 29 |
+
low_cpu_mem_usage=True, # Tối ưu hóa dung lượng RAM khi khởi tạo
|
| 30 |
+
device_map="cpu", # Ép buộc chạy hoàn toàn trên CPU
|
| 31 |
+
trust_remote_code=True,
|
| 32 |
+
token=HF_TOKEN
|
| 33 |
+
)
|
| 34 |
+
print("--- [LAZY LOADING] Mô hình đã nạp vào RAM thành công! ---")
|
| 35 |
+
return model, tokenizer
|
| 36 |
+
|
| 37 |
+
# Khởi tạo ứng dụng FastAPI duy nhất
|
| 38 |
+
app = FastAPI(title="⚡ Volta Energy Plan Parser API")
|
| 39 |
+
|
| 40 |
+
# --- HỆ THỐNG PYDANTIC SCHEMAS (Giữ nguyên cấu trúc chuẩn của bạn) ---
|
| 41 |
+
class EligibilitySchema(BaseModel):
|
| 42 |
+
customer_type: Optional[str] = None
|
| 43 |
+
is_victorian: bool = False
|
| 44 |
+
is_new_customer: bool = False
|
| 45 |
+
is_moving_customer: bool = False
|
| 46 |
+
is_existing_customer: bool = False
|
| 47 |
+
distributor: Optional[str] = None
|
| 48 |
+
requires_solar: bool = False
|
| 49 |
+
requires_net_metered_solar: bool = False
|
| 50 |
+
requires_ev: bool = False
|
| 51 |
+
requires_smart_meter: bool = False
|
| 52 |
+
requires_interval_meter: bool = False
|
| 53 |
+
tariff_types: List[str] = []
|
| 54 |
+
consumption_tier: Optional[str] = None
|
| 55 |
+
loyalty_program: Optional[str] = None
|
| 56 |
+
requires_abn: bool = False
|
| 57 |
+
requires_seniors_card: bool = False
|
| 58 |
+
requires_concession_card: bool = False
|
| 59 |
+
channel: Optional[str] = None
|
| 60 |
+
comparator_name: Optional[str] = None
|
| 61 |
+
requires_direct_debit: bool = False
|
| 62 |
+
requires_ebilling: bool = False
|
| 63 |
+
has_feed_in_tariff: bool = False
|
| 64 |
+
is_generally_available: bool = False
|
| 65 |
+
|
| 66 |
+
class FeeSchema(BaseModel):
|
| 67 |
+
fee_type: Optional[str] = None
|
| 68 |
+
amount_type: Optional[str] = None
|
| 69 |
+
value: Optional[float] = None
|
| 70 |
+
value_display: Optional[str] = None
|
| 71 |
+
tax_inclusive: bool = True
|
| 72 |
+
payment_method: Optional[str] = None
|
| 73 |
+
is_waived: bool = False
|
| 74 |
+
waived_for: Optional[str] = None
|
| 75 |
+
trigger_context: Optional[str] = None
|
| 76 |
+
is_variable: bool = False
|
| 77 |
+
is_pass_through: bool = False
|
| 78 |
+
|
| 79 |
+
class IncentiveSchema(BaseModel):
|
| 80 |
+
incentive_type: Optional[str] = None
|
| 81 |
+
raw_category: Optional[str] = None
|
| 82 |
+
display_name: Optional[str] = None
|
| 83 |
+
amount_aud: Optional[float] = None
|
| 84 |
+
points_value: Optional[float] = None
|
| 85 |
+
percent_value: Optional[float] = None
|
| 86 |
+
recurring_amount_aud: Optional[float] = None
|
| 87 |
+
tax_inclusive: bool = True
|
| 88 |
+
value_display: Optional[str] = None
|
| 89 |
+
loyalty_program: Optional[str] = None
|
| 90 |
+
reward_card_network: Optional[str] = None
|
| 91 |
+
is_recurring: bool = False
|
| 92 |
+
customer_scope: List[str] = []
|
| 93 |
+
channel_required: Optional[str] = None
|
| 94 |
+
membership_required: Optional[str] = None
|
| 95 |
+
trigger: Optional[str] = None
|
| 96 |
+
timing_days: Optional[int] = None
|
| 97 |
+
timing_months: Optional[int] = None
|
| 98 |
+
min_stay_days: Optional[int] = None
|
| 99 |
+
limit_per_account: Optional[str] = None
|
| 100 |
+
is_transferable: bool = False
|
| 101 |
+
|
| 102 |
+
class DiscountSchema(BaseModel):
|
| 103 |
+
discount_type: Optional[str] = None
|
| 104 |
+
raw_category: Optional[str] = None
|
| 105 |
+
display_name: Optional[str] = None
|
| 106 |
+
method: Optional[str] = None
|
| 107 |
+
rate: Optional[float] = None
|
| 108 |
+
amount_aud: Optional[float] = None
|
| 109 |
+
applies_to: Optional[str] = None
|
| 110 |
+
discount_condition: List[str] = []
|
| 111 |
+
requires_direct_debit: bool = False
|
| 112 |
+
requires_ebilling: bool = False
|
| 113 |
+
requires_pay_on_time: bool = False
|
| 114 |
+
requires_online_signup: bool = False
|
| 115 |
+
excludes_greenpower: bool = False
|
| 116 |
+
excludes_demand_charges: bool = False
|
| 117 |
+
excludes_fees: bool = False
|
| 118 |
+
is_estimated: bool = False
|
| 119 |
+
is_ongoing: bool = False
|
| 120 |
+
duration_months: Optional[int] = None
|
| 121 |
+
min_supply_months: Optional[int] = None
|
| 122 |
+
time_window: Optional[str] = None
|
| 123 |
+
installment_schedule: Optional[str] = None
|
| 124 |
+
|
| 125 |
+
class EnergyTargetSchema(BaseModel):
|
| 126 |
+
eligibility: EligibilitySchema
|
| 127 |
+
fees: List[FeeSchema] = []
|
| 128 |
+
incentives: List[IncentiveSchema] = []
|
| 129 |
+
discounts: List[DiscountSchema] = []
|
| 130 |
+
|
| 131 |
+
# --- HÀM XỬ LÝ ENGINE LÕI ---
|
| 132 |
+
def final_process_eme_technical_guided(input_text):
|
| 133 |
+
# Gọi hàm lazy loading để lấy model/tokenizer ra làm việc
|
| 134 |
+
curr_model, curr_tokenizer = get_model_and_tokenizer()
|
| 135 |
+
|
| 136 |
+
prompt = f"""<|im_start|>system
|
| 137 |
+
Bạn là chuyên gia trích xuất dữ liệu năng lượng. Hãy chuyển JSON EME thô sang đúng Schema 76 trường.<|im_end|>
|
| 138 |
+
<|im_start|>user
|
| 139 |
+
{input_text}<|im_end|>
|
| 140 |
+
<|im_start|>assistant
|
| 141 |
+
"""
|
| 142 |
+
inputs = curr_tokenizer([prompt], return_tensors="pt").to("cpu")
|
| 143 |
+
eos_token_id = curr_tokenizer.convert_tokens_to_ids("<|im_end|>")
|
| 144 |
+
|
| 145 |
+
with torch.no_grad():
|
| 146 |
+
outputs = curr_model.generate(
|
| 147 |
+
**inputs,
|
| 148 |
+
max_new_tokens=768,
|
| 149 |
+
temperature=0.1,
|
| 150 |
+
top_p=0.9,
|
| 151 |
+
use_cache=True,
|
| 152 |
+
do_sample=False,
|
| 153 |
+
eos_token_id=eos_token_id,
|
| 154 |
+
pad_token_id=curr_tokenizer.eos_token_id
|
| 155 |
+
)
|
| 156 |
+
|
| 157 |
+
full_response = curr_tokenizer.decode(outputs[0], skip_special_tokens=False)
|
| 158 |
+
json_part = full_response.split("<|im_start|>assistant")[-1].split("<|im_end|>")[0].strip()
|
| 159 |
+
|
| 160 |
+
try:
|
| 161 |
+
parsed_json = json.loads(json_part)
|
| 162 |
+
except json.JSONDecodeError:
|
| 163 |
+
print("Cảnh báo: JSON không hợp lệ, đang cố gắng sửa chữa...")
|
| 164 |
+
repaired_json_str = repair_json(json_part)
|
| 165 |
+
parsed_json = json.loads(repaired_json_str)
|
| 166 |
+
|
| 167 |
+
if isinstance(parsed_json, list):
|
| 168 |
+
parsed_json = parsed_json[0] if len(parsed_json) > 0 else {}
|
| 169 |
+
if not isinstance(parsed_json, dict):
|
| 170 |
+
parsed_json = {}
|
| 171 |
+
|
| 172 |
+
# Bọc Try-Except phòng trường hợp input_text truyền vào không phải chuỗi JSON hợp lệ
|
| 173 |
+
try:
|
| 174 |
+
original_input_data = json.loads(input_text)
|
| 175 |
+
except json.JSONDecodeError:
|
| 176 |
+
original_input_data = {}
|
| 177 |
+
|
| 178 |
+
electricity_contract = original_input_data.get("electricity_contract", {})
|
| 179 |
+
|
| 180 |
+
# 1. Chuẩn hóa ELIGIBILITY
|
| 181 |
+
model_eligibility = parsed_json.get("eligibility", {})
|
| 182 |
+
if not isinstance(model_eligibility, dict):
|
| 183 |
+
model_eligibility = {}
|
| 184 |
+
|
| 185 |
+
if not model_eligibility.get("customer_type"):
|
| 186 |
+
model_eligibility["customer_type"] = original_input_data.get("customer_type") or "RESIDENTIAL"
|
| 187 |
+
|
| 188 |
+
distributor_value = original_input_data.get("distributor")
|
| 189 |
+
if not distributor_value and "geography" in original_input_data:
|
| 190 |
+
dist_list = original_input_data["geography"].get("distributors", [])
|
| 191 |
+
if dist_list and isinstance(dist_list, list):
|
| 192 |
+
distributor_value = dist_list[0]
|
| 193 |
+
if not distributor_value:
|
| 194 |
+
distributor_value = model_eligibility.get("distributor")
|
| 195 |
+
if isinstance(distributor_value, list) and len(distributor_value) > 0:
|
| 196 |
+
distributor_value = distributor_value[0]
|
| 197 |
+
model_eligibility["distributor"] = distributor_value
|
| 198 |
+
|
| 199 |
+
plan_id = original_input_data.get("plan_id", "")
|
| 200 |
+
metadata_source = original_input_data.get("metadata", {}).get("source", "")
|
| 201 |
+
is_vic_plan = "VEC" in plan_id or metadata_source == "VEC" or model_eligibility.get("is_victorian", False)
|
| 202 |
+
model_eligibility["is_victorian"] = is_vic_plan
|
| 203 |
+
|
| 204 |
+
if not model_eligibility.get("tariff_types") and "pricingModel" in electricity_contract:
|
| 205 |
+
model_eligibility["tariff_types"] = [electricity_contract["pricingModel"]]
|
| 206 |
+
|
| 207 |
+
if "solarFeedInTariff" in electricity_contract and electricity_contract["solarFeedInTariff"]:
|
| 208 |
+
model_eligibility["has_feed_in_tariff"] = True
|
| 209 |
+
if original_input_data.get("ops_status") == "PENDING" and not model_eligibility.get("channel"):
|
| 210 |
+
model_eligibility["channel"] = "PENDING"
|
| 211 |
+
if metadata_source in ["VEC", "EME"] and not model_eligibility.get("comparator_name"):
|
| 212 |
+
model_eligibility["comparator_name"] = metadata_source
|
| 213 |
+
if "is_generally_available" not in model_eligibility:
|
| 214 |
+
model_eligibility["is_generally_available"] = True
|
| 215 |
+
|
| 216 |
+
# 2. Chuẩn hóa FEES
|
| 217 |
+
model_fees = parsed_json.get("fees", [])
|
| 218 |
+
if not isinstance(model_fees, list):
|
| 219 |
+
model_fees = []
|
| 220 |
+
|
| 221 |
+
final_fees = []
|
| 222 |
+
seen_fee_types = set()
|
| 223 |
+
|
| 224 |
+
for m_fee in model_fees:
|
| 225 |
+
if not isinstance(m_fee, dict): continue
|
| 226 |
+
f_type = m_fee.get("fee_type") or m_fee.get("type")
|
| 227 |
+
if not f_type: continue
|
| 228 |
+
|
| 229 |
+
t_context = m_fee.get("trigger_context") or m_fee.get("description")
|
| 230 |
+
if not t_context:
|
| 231 |
+
for orig_fee in electricity_contract.get("fees", []):
|
| 232 |
+
if orig_fee.get("type") == f_type:
|
| 233 |
+
t_context = orig_fee.get("description")
|
| 234 |
+
break
|
| 235 |
+
|
| 236 |
+
raw_val = m_fee.get("value") if m_fee.get("value") is not None else m_fee.get("amount")
|
| 237 |
+
try: fee_val = float(raw_val) if raw_val is not None else None
|
| 238 |
+
except: fee_val = None
|
| 239 |
+
|
| 240 |
+
cleaned_fee = {
|
| 241 |
+
"fee_type": f_type,
|
| 242 |
+
"amount_type": m_fee.get("amount_type") or "FIXED",
|
| 243 |
+
"value": fee_val,
|
| 244 |
+
"value_display": m_fee.get("value_display") or (f"${fee_val:.2f}" if fee_val else None),
|
| 245 |
+
"tax_inclusive": m_fee.get("tax_inclusive", True),
|
| 246 |
+
"payment_method": m_fee.get("payment_method"),
|
| 247 |
+
"is_waived": m_fee.get("is_waived", False),
|
| 248 |
+
"waived_for": m_fee.get("waived_for"),
|
| 249 |
+
"trigger_context": t_context,
|
| 250 |
+
"is_variable": m_fee.get("is_variable", False),
|
| 251 |
+
"is_pass_through": m_fee.get("is_pass_through", False)
|
| 252 |
+
}
|
| 253 |
+
final_fees.append(cleaned_fee)
|
| 254 |
+
seen_fee_types.add(f_type)
|
| 255 |
+
|
| 256 |
+
for orig_fee in electricity_contract.get("fees", []):
|
| 257 |
+
f_type = orig_fee.get("type")
|
| 258 |
+
if f_type and f_type not in seen_fee_types:
|
| 259 |
+
raw_amount = orig_fee.get("amount") if orig_fee.get("amount") is not None else orig_fee.get("value")
|
| 260 |
+
try: fee_val = float(raw_amount) if raw_amount else None
|
| 261 |
+
except: fee_val = None
|
| 262 |
+
|
| 263 |
+
fallback_fee = {
|
| 264 |
+
"fee_type": f_type,
|
| 265 |
+
"amount_type": orig_fee.get("term") or "FIXED",
|
| 266 |
+
"value": fee_val,
|
| 267 |
+
"value_display": f"${fee_val:.2f}" if fee_val else None,
|
| 268 |
+
"tax_inclusive": True,
|
| 269 |
+
"trigger_context": orig_fee.get("description"),
|
| 270 |
+
"is_waived": False,
|
| 271 |
+
"is_variable": False,
|
| 272 |
+
"is_pass_through": False
|
| 273 |
+
}
|
| 274 |
+
final_fees.append(fallback_fee)
|
| 275 |
+
seen_fee_types.add(f_type)
|
| 276 |
+
|
| 277 |
+
# 3. Chuẩn hóa DISCOUNTS
|
| 278 |
+
model_discounts = parsed_json.get("discounts", [])
|
| 279 |
+
if not isinstance(model_discounts, list):
|
| 280 |
+
model_discounts = []
|
| 281 |
+
|
| 282 |
+
final_discounts = []
|
| 283 |
+
for m_disc in model_discounts:
|
| 284 |
+
if not isinstance(m_disc, dict): continue
|
| 285 |
+
|
| 286 |
+
rate_val = m_disc.get("rate")
|
| 287 |
+
if rate_val is None or float(rate_val) == 0.0:
|
| 288 |
+
for orig_disc in electricity_contract.get("discounts", []):
|
| 289 |
+
for rate_key in ["percentOfBill", "percentOfUse", "percentOfDemand", "percentOfSolar"]:
|
| 290 |
+
if rate_key in orig_disc and "rate" in orig_disc[rate_key]:
|
| 291 |
+
try: rate_val = float(orig_disc[rate_key]["rate"])
|
| 292 |
+
except: pass
|
| 293 |
+
break
|
| 294 |
+
|
| 295 |
+
m_disc["rate"] = rate_val if rate_val is not None else 0.0
|
| 296 |
+
if not m_disc.get("discount_condition") and "description" in m_disc:
|
| 297 |
+
m_disc["discount_condition"] = [m_disc["description"]]
|
| 298 |
+
|
| 299 |
+
final_discounts.append(m_disc)
|
| 300 |
+
|
| 301 |
+
if not final_discounts:
|
| 302 |
+
for orig_disc in electricity_contract.get("discounts", []):
|
| 303 |
+
rate_val = None
|
| 304 |
+
amount_val = None
|
| 305 |
+
for rate_key in ["percentOfBill", "percentOfUse", "percentOfDemand", "percentOfSolar"]:
|
| 306 |
+
if rate_key in orig_disc and "rate" in orig_disc[rate_key]:
|
| 307 |
+
raw_rate = orig_disc[rate_key]["rate"]
|
| 308 |
+
rate_val = float(raw_rate)
|
| 309 |
+
break
|
| 310 |
+
|
| 311 |
+
description = orig_disc.get("description", "")
|
| 312 |
+
dollar_match = re.search(r'\$(\d+\.?\d*)', description)
|
| 313 |
+
if dollar_match and "%" not in description and rate_val and rate_val >= 1.0:
|
| 314 |
+
amount_val = float(dollar_match.group(1))
|
| 315 |
+
rate_val = None
|
| 316 |
+
|
| 317 |
+
fallback_disc = {
|
| 318 |
+
"discount_type": orig_disc.get("type") or "GUARANTEED",
|
| 319 |
+
"raw_category": orig_disc.get("category") or "percentOfUse",
|
| 320 |
+
"display_name": orig_disc.get("displayName") or orig_disc.get("description"),
|
| 321 |
+
"method": orig_disc.get("methodUType") or "percentOfUse",
|
| 322 |
+
"rate": float(rate_val) if rate_val else 0.15,
|
| 323 |
+
"discount_condition": [orig_disc.get("description")] if orig_disc.get("description") else []
|
| 324 |
+
}
|
| 325 |
+
final_discounts.append(fallback_disc)
|
| 326 |
+
|
| 327 |
+
# 4. Chuẩn hóa INCENTIVES
|
| 328 |
+
model_incentives = parsed_json.get("incentives", [])
|
| 329 |
+
if not isinstance(model_incentives, list):
|
| 330 |
+
model_incentives = [model_incentives] if isinstance(model_incentives, dict) else []
|
| 331 |
+
|
| 332 |
+
if not model_incentives and "solarFeedInTariff" in electricity_contract:
|
| 333 |
+
for s_fit in electricity_contract["solarFeedInTariff"]:
|
| 334 |
+
rates = s_fit.get("singleTariff", {}).get("rates", [])
|
| 335 |
+
unit_price = float(rates[0].get("unitPrice", 0.005)) if rates else 0.005
|
| 336 |
+
fallback_inc = {
|
| 337 |
+
"incentive_type": "SOLAR_REBATE",
|
| 338 |
+
"raw_category": "retailer_solar_fiT",
|
| 339 |
+
"display_name": s_fit.get("displayName") or "Current FIT policy",
|
| 340 |
+
"amount_aud": unit_price,
|
| 341 |
+
"tax_inclusive": True,
|
| 342 |
+
"value_display": f"${unit_price}/kWh",
|
| 343 |
+
"is_recurring": True,
|
| 344 |
+
"customer_scope": ["RESIDENTIAL"],
|
| 345 |
+
"trigger": "SOLAR_EXPORT",
|
| 346 |
+
"timing_months": 1,
|
| 347 |
+
"limit_per_account": "1"
|
| 348 |
+
}
|
| 349 |
+
model_incentives.append(fallback_inc)
|
| 350 |
+
|
| 351 |
+
parsed_json["eligibility"] = model_eligibility
|
| 352 |
+
parsed_json["fees"] = final_fees
|
| 353 |
+
parsed_json["discounts"] = final_discounts
|
| 354 |
+
parsed_json["incentives"] = model_incentives
|
| 355 |
+
|
| 356 |
+
try:
|
| 357 |
+
return EnergyTargetSchema(**parsed_json)
|
| 358 |
+
except ValidationError as e:
|
| 359 |
+
raise ValueError(f"Pydantic validation error: {e}")
|
| 360 |
+
|
| 361 |
+
# --- TẦNG ĐỊNH TUYẾN API ENDPOINTS ---
|
| 362 |
+
class PredictRequest(BaseModel):
|
| 363 |
+
instances: list
|
| 364 |
+
|
| 365 |
+
@app.post("/predict")
|
| 366 |
+
@app.post("/extract")
|
| 367 |
+
def predict(request: PredictRequest):
|
| 368 |
+
results = []
|
| 369 |
+
for instance in request.instances:
|
| 370 |
+
text = instance if isinstance(instance, str) else instance.get("raw_text", "")
|
| 371 |
+
try:
|
| 372 |
+
res = final_process_eme_technical_guided(text)
|
| 373 |
+
results.append(res.model_dump())
|
| 374 |
+
except Exception as e:
|
| 375 |
+
results.append({"error": str(e)})
|
| 376 |
+
return {"predictions": results}
|
| 377 |
+
|
| 378 |
+
@app.get("/health")
|
| 379 |
+
async def health():
|
| 380 |
+
return {"status": "healthy"}
|
| 381 |
+
|
| 382 |
+
if __name__ == "__main__":
|
| 383 |
+
import uvicorn
|
| 384 |
+
# Chạy uvicorn đọc trực tiếp cổng 8080 cho Cloud Run lắng nghe
|
| 385 |
+
uvicorn.run(app, host="0.0.0.0", port=8080)
|
requirements.txt
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio
|
| 2 |
+
fastapi
|
| 3 |
+
uvicorn
|
| 4 |
+
transformers
|
| 5 |
+
torch
|
| 6 |
+
accelerate
|
| 7 |
+
tiktoken
|
| 8 |
+
sentencepiece
|
| 9 |
+
json-repair
|
| 10 |
+
pydantic
|