Toan2004-ai commited on
Commit
922f211
·
1 Parent(s): 213de92

add readme config

Browse files
Files changed (5) hide show
  1. .dockerignore +4 -0
  2. engine.py +235 -0
  3. main.py +16 -350
  4. model_manager.py +28 -0
  5. schema.py +92 -0
.dockerignore ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ __pycache__
2
+ .git
3
+ .env
4
+ .DS_Store
engine.py ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import re
3
+ from pydantic.v1 import ValidationError
4
+ import torch
5
+ from json_repair import repair_json
6
+ from schema import EnergyTargetSchema
7
+ from main import get_model_and_tokenizer
8
+
9
+ def final_process_eme_technical_guided(input_text):
10
+ curr_model, curr_tokenizer = get_model_and_tokenizer()
11
+
12
+ prompt = f"""<|im_start|>system
13
+ 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|>
14
+ <|im_start|>user
15
+ {input_text}<|im_end|>
16
+ <|im_start|>assistant
17
+ """
18
+ inputs = curr_tokenizer([prompt], return_tensors="pt").to("cpu")
19
+ eos_token_id = curr_tokenizer.convert_tokens_to_ids("<|im_end|>")
20
+
21
+ with torch.no_grad():
22
+ outputs = curr_model.generate(
23
+ **inputs,
24
+ max_new_tokens=768,
25
+ temperature=0.1,
26
+ top_p=0.9,
27
+ use_cache=True,
28
+ do_sample=False,
29
+ eos_token_id=eos_token_id,
30
+ pad_token_id=curr_tokenizer.eos_token_id
31
+ )
32
+
33
+ full_response = curr_tokenizer.decode(outputs[0], skip_special_tokens=False)
34
+ json_part = full_response.split("<|im_start|>assistant")[-1].split("<|im_end|>")[0].strip()
35
+
36
+ try:
37
+ parsed_json = json.loads(json_part)
38
+ except json.JSONDecodeError:
39
+ print("Cảnh báo: JSON không hợp lệ, đang cố gắng sửa chữa...")
40
+ repaired_json_str = repair_json(json_part)
41
+ parsed_json = json.loads(repaired_json_str)
42
+
43
+ if isinstance(parsed_json, list):
44
+ parsed_json = parsed_json[0] if len(parsed_json) > 0 else {}
45
+ if not isinstance(parsed_json, dict):
46
+ parsed_json = {}
47
+
48
+ # 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ệ
49
+ try:
50
+ original_input_data = json.loads(input_text)
51
+ except json.JSONDecodeError:
52
+ original_input_data = {}
53
+
54
+ electricity_contract = original_input_data.get("electricity_contract", {})
55
+
56
+ # 1. Chuẩn hóa ELIGIBILITY
57
+ model_eligibility = parsed_json.get("eligibility", {})
58
+ if not isinstance(model_eligibility, dict):
59
+ model_eligibility = {}
60
+
61
+ if not model_eligibility.get("customer_type"):
62
+ model_eligibility["customer_type"] = original_input_data.get("customer_type") or "RESIDENTIAL"
63
+
64
+ distributor_value = original_input_data.get("distributor")
65
+ if not distributor_value and "geography" in original_input_data:
66
+ dist_list = original_input_data["geography"].get("distributors", [])
67
+ if dist_list and isinstance(dist_list, list):
68
+ distributor_value = dist_list[0]
69
+ if not distributor_value:
70
+ distributor_value = model_eligibility.get("distributor")
71
+ if isinstance(distributor_value, list) and len(distributor_value) > 0:
72
+ distributor_value = distributor_value[0]
73
+ model_eligibility["distributor"] = distributor_value
74
+
75
+ plan_id = original_input_data.get("plan_id", "")
76
+ metadata_source = original_input_data.get("metadata", {}).get("source", "")
77
+ is_vic_plan = "VEC" in plan_id or metadata_source == "VEC" or model_eligibility.get("is_victorian", False)
78
+ model_eligibility["is_victorian"] = is_vic_plan
79
+
80
+ if not model_eligibility.get("tariff_types") and "pricingModel" in electricity_contract:
81
+ model_eligibility["tariff_types"] = [electricity_contract["pricingModel"]]
82
+
83
+ if "solarFeedInTariff" in electricity_contract and electricity_contract["solarFeedInTariff"]:
84
+ model_eligibility["has_feed_in_tariff"] = True
85
+ if original_input_data.get("ops_status") == "PENDING" and not model_eligibility.get("channel"):
86
+ model_eligibility["channel"] = "PENDING"
87
+ if metadata_source in ["VEC", "EME"] and not model_eligibility.get("comparator_name"):
88
+ model_eligibility["comparator_name"] = metadata_source
89
+ if "is_generally_available" not in model_eligibility:
90
+ model_eligibility["is_generally_available"] = True
91
+
92
+ # 2. Chuẩn hóa FEES
93
+ model_fees = parsed_json.get("fees", [])
94
+ if not isinstance(model_fees, list):
95
+ model_fees = []
96
+
97
+ final_fees = []
98
+ seen_fee_types = set()
99
+
100
+ for m_fee in model_fees:
101
+ if not isinstance(m_fee, dict): continue
102
+ f_type = m_fee.get("fee_type") or m_fee.get("type")
103
+ if not f_type: continue
104
+
105
+ t_context = m_fee.get("trigger_context") or m_fee.get("description")
106
+ if not t_context:
107
+ for orig_fee in electricity_contract.get("fees", []):
108
+ if orig_fee.get("type") == f_type:
109
+ t_context = orig_fee.get("description")
110
+ break
111
+
112
+ raw_val = m_fee.get("value") if m_fee.get("value") is not None else m_fee.get("amount")
113
+ try: fee_val = float(raw_val) if raw_val is not None else None
114
+ except: fee_val = None
115
+
116
+ cleaned_fee = {
117
+ "fee_type": f_type,
118
+ "amount_type": m_fee.get("amount_type") or "FIXED",
119
+ "value": fee_val,
120
+ "value_display": m_fee.get("value_display") or (f"${fee_val:.2f}" if fee_val else None),
121
+ "tax_inclusive": m_fee.get("tax_inclusive", True),
122
+ "payment_method": m_fee.get("payment_method"),
123
+ "is_waived": m_fee.get("is_waived", False),
124
+ "waived_for": m_fee.get("waived_for"),
125
+ "trigger_context": t_context,
126
+ "is_variable": m_fee.get("is_variable", False),
127
+ "is_pass_through": m_fee.get("is_pass_through", False)
128
+ }
129
+ final_fees.append(cleaned_fee)
130
+ seen_fee_types.add(f_type)
131
+
132
+ for orig_fee in electricity_contract.get("fees", []):
133
+ f_type = orig_fee.get("type")
134
+ if f_type and f_type not in seen_fee_types:
135
+ raw_amount = orig_fee.get("amount") if orig_fee.get("amount") is not None else orig_fee.get("value")
136
+ try: fee_val = float(raw_amount) if raw_amount else None
137
+ except: fee_val = None
138
+
139
+ fallback_fee = {
140
+ "fee_type": f_type,
141
+ "amount_type": orig_fee.get("term") or "FIXED",
142
+ "value": fee_val,
143
+ "value_display": f"${fee_val:.2f}" if fee_val else None,
144
+ "tax_inclusive": True,
145
+ "trigger_context": orig_fee.get("description"),
146
+ "is_waived": False,
147
+ "is_variable": False,
148
+ "is_pass_through": False
149
+ }
150
+ final_fees.append(fallback_fee)
151
+ seen_fee_types.add(f_type)
152
+
153
+ # 3. Chuẩn hóa DISCOUNTS
154
+ model_discounts = parsed_json.get("discounts", [])
155
+ if not isinstance(model_discounts, list):
156
+ model_discounts = []
157
+
158
+ final_discounts = []
159
+ for m_disc in model_discounts:
160
+ if not isinstance(m_disc, dict): continue
161
+
162
+ rate_val = m_disc.get("rate")
163
+ if rate_val is None or float(rate_val) == 0.0:
164
+ for orig_disc in electricity_contract.get("discounts", []):
165
+ for rate_key in ["percentOfBill", "percentOfUse", "percentOfDemand", "percentOfSolar"]:
166
+ if rate_key in orig_disc and "rate" in orig_disc[rate_key]:
167
+ try: rate_val = float(orig_disc[rate_key]["rate"])
168
+ except: pass
169
+ break
170
+
171
+ m_disc["rate"] = rate_val if rate_val is not None else 0.0
172
+ if not m_disc.get("discount_condition") and "description" in m_disc:
173
+ m_disc["discount_condition"] = [m_disc["description"]]
174
+
175
+ final_discounts.append(m_disc)
176
+
177
+ if not final_discounts:
178
+ for orig_disc in electricity_contract.get("discounts", []):
179
+ rate_val = None
180
+ amount_val = None
181
+ for rate_key in ["percentOfBill", "percentOfUse", "percentOfDemand", "percentOfSolar"]:
182
+ if rate_key in orig_disc and "rate" in orig_disc[rate_key]:
183
+ raw_rate = orig_disc[rate_key]["rate"]
184
+ rate_val = float(raw_rate)
185
+ break
186
+
187
+ description = orig_disc.get("description", "")
188
+ dollar_match = re.search(r'\$(\d+\.?\d*)', description)
189
+ if dollar_match and "%" not in description and rate_val and rate_val >= 1.0:
190
+ amount_val = float(dollar_match.group(1))
191
+ rate_val = None
192
+
193
+ fallback_disc = {
194
+ "discount_type": orig_disc.get("type") or "GUARANTEED",
195
+ "raw_category": orig_disc.get("category") or "percentOfUse",
196
+ "display_name": orig_disc.get("displayName") or orig_disc.get("description"),
197
+ "method": orig_disc.get("methodUType") or "percentOfUse",
198
+ "rate": float(rate_val) if rate_val else 0.15,
199
+ "discount_condition": [orig_disc.get("description")] if orig_disc.get("description") else []
200
+ }
201
+ final_discounts.append(fallback_disc)
202
+
203
+ # 4. Chuẩn hóa INCENTIVES
204
+ model_incentives = parsed_json.get("incentives", [])
205
+ if not isinstance(model_incentives, list):
206
+ model_incentives = [model_incentives] if isinstance(model_incentives, dict) else []
207
+
208
+ if not model_incentives and "solarFeedInTariff" in electricity_contract:
209
+ for s_fit in electricity_contract["solarFeedInTariff"]:
210
+ rates = s_fit.get("singleTariff", {}).get("rates", [])
211
+ unit_price = float(rates[0].get("unitPrice", 0.005)) if rates else 0.005
212
+ fallback_inc = {
213
+ "incentive_type": "SOLAR_REBATE",
214
+ "raw_category": "retailer_solar_fiT",
215
+ "display_name": s_fit.get("displayName") or "Current FIT policy",
216
+ "amount_aud": unit_price,
217
+ "tax_inclusive": True,
218
+ "value_display": f"${unit_price}/kWh",
219
+ "is_recurring": True,
220
+ "customer_scope": ["RESIDENTIAL"],
221
+ "trigger": "SOLAR_EXPORT",
222
+ "timing_months": 1,
223
+ "limit_per_account": "1"
224
+ }
225
+ model_incentives.append(fallback_inc)
226
+
227
+ parsed_json["eligibility"] = model_eligibility
228
+ parsed_json["fees"] = final_fees
229
+ parsed_json["discounts"] = final_discounts
230
+ parsed_json["incentives"] = model_incentives
231
+
232
+ try:
233
+ return EnergyTargetSchema(**parsed_json)
234
+ except ValidationError as e:
235
+ raise ValueError(f"Pydantic validation error: {e}")
main.py CHANGED
@@ -3,362 +3,29 @@ 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
 
@@ -381,5 +48,4 @@ async def health():
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)
 
3
  from typing import List, Optional
4
  from transformers import AutoTokenizer, AutoModelForCausalLM
5
  from json_repair import repair_json
6
+ from schema import EnergyTargetSchema
7
+ from engine import final_process_eme_technical_guided
8
+ from contextlib import asynccontextmanager
9
+ from model_manager import get_model_and_tokenizer
10
+ import torch, json, re, os, logging
11
 
12
  # Tối ưu hóa số luồng xử lý trên CPU của Cloud Run
13
  torch.set_num_threads(4)
14
 
15
+ @asynccontextmanager
16
+ async def lifespan(app: FastAPI):
17
+ logging.basicConfig(level=logging.INFO)
18
+ logger = logging.getLogger(__name__)
19
+ logger.info("--- [LIFESPAN] Bắt đầu nạp mô hình vào RAM... ---")
20
+ get_model_and_tokenizer()
21
+ yield
22
+ # Cleanup khi tắt server (nếu cần)
23
+ logger.info("--- [LIFESPAN] Server dừng. ---")
24
 
25
+ # Cập nhật khi khai báo app
26
+ app = FastAPI(title="Volta Energy Plan Parser API", lifespan=lifespan)
 
27
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
  class PredictRequest(BaseModel):
30
  instances: list
31
 
 
48
 
49
  if __name__ == "__main__":
50
  import uvicorn
 
51
  uvicorn.run(app, host="0.0.0.0", port=8080)
model_manager.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import torch
3
+ from transformers import AutoTokenizer, AutoModelForCausalLM
4
+
5
+ MODEL_PATH = "NLP-Volta-Energy-AI/volta-energy-parser"
6
+ HF_TOKEN = os.environ.get("HF_TOKEN")
7
+
8
+ # Khởi tạo biến toàn cục
9
+ model = None
10
+ tokenizer = None
11
+
12
+ def get_model_and_tokenizer():
13
+ global model, tokenizer
14
+ if model is None or tokenizer is None:
15
+ print("--- [MODEL MANAGER] Đang tải mô hình từ Hugging Face... ---")
16
+ tokenizer = AutoTokenizer.from_pretrained(
17
+ MODEL_PATH, trust_remote_code=True, token=HF_TOKEN
18
+ )
19
+ model = AutoModelForCausalLM.from_pretrained(
20
+ MODEL_PATH,
21
+ torch_dtype=torch.float32,
22
+ low_cpu_mem_usage=True,
23
+ device_map="cpu",
24
+ trust_remote_code=True,
25
+ token=HF_TOKEN
26
+ )
27
+ print("--- [MODEL MANAGER] Mô hình đã nạp thành công! ---")
28
+ return model, tokenizer
schema.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pydantic import BaseModel
2
+ from typing import List, Optional
3
+
4
+ class EligibilitySchema(BaseModel):
5
+ customer_type: Optional[str] = None
6
+ is_victorian: bool = False
7
+ is_new_customer: bool = False
8
+ is_moving_customer: bool = False
9
+ is_existing_customer: bool = False
10
+ distributor: Optional[str] = None
11
+ requires_solar: bool = False
12
+ requires_net_metered_solar: bool = False
13
+ requires_ev: bool = False
14
+ requires_smart_meter: bool = False
15
+ requires_interval_meter: bool = False
16
+ tariff_types: List[str] = []
17
+ consumption_tier: Optional[str] = None
18
+ loyalty_program: Optional[str] = None
19
+ requires_abn: bool = False
20
+ requires_seniors_card: bool = False
21
+ requires_concession_card: bool = False
22
+ channel: Optional[str] = None
23
+ comparator_name: Optional[str] = None
24
+ requires_direct_debit: bool = False
25
+ requires_ebilling: bool = False
26
+ has_feed_in_tariff: bool = False
27
+ is_generally_available: bool = False
28
+
29
+ class FeeSchema(BaseModel):
30
+ fee_type: Optional[str] = None
31
+ amount_type: Optional[str] = None
32
+ value: Optional[float] = None
33
+ value_display: Optional[str] = None
34
+ tax_inclusive: bool = True
35
+ payment_method: Optional[str] = None
36
+ is_waived: bool = False
37
+ waived_for: Optional[str] = None
38
+ trigger_context: Optional[str] = None
39
+ is_variable: bool = False
40
+ is_pass_through: bool = False
41
+
42
+ class IncentiveSchema(BaseModel):
43
+ incentive_type: Optional[str] = None
44
+ raw_category: Optional[str] = None
45
+ display_name: Optional[str] = None
46
+ amount_aud: Optional[float] = None
47
+ points_value: Optional[float] = None
48
+ percent_value: Optional[float] = None
49
+ recurring_amount_aud: Optional[float] = None
50
+ tax_inclusive: bool = True
51
+ value_display: Optional[str] = None
52
+ loyalty_program: Optional[str] = None
53
+ reward_card_network: Optional[str] = None
54
+ is_recurring: bool = False
55
+ customer_scope: List[str] = []
56
+ channel_required: Optional[str] = None
57
+ membership_required: Optional[str] = None
58
+ trigger: Optional[str] = None
59
+ timing_days: Optional[int] = None
60
+ timing_months: Optional[int] = None
61
+ min_stay_days: Optional[int] = None
62
+ limit_per_account: Optional[str] = None
63
+ is_transferable: bool = False
64
+
65
+ class DiscountSchema(BaseModel):
66
+ discount_type: Optional[str] = None
67
+ raw_category: Optional[str] = None
68
+ display_name: Optional[str] = None
69
+ method: Optional[str] = None
70
+ rate: Optional[float] = None
71
+ amount_aud: Optional[float] = None
72
+ applies_to: Optional[str] = None
73
+ discount_condition: List[str] = []
74
+ requires_direct_debit: bool = False
75
+ requires_ebilling: bool = False
76
+ requires_pay_on_time: bool = False
77
+ requires_online_signup: bool = False
78
+ excludes_greenpower: bool = False
79
+ excludes_demand_charges: bool = False
80
+ excludes_fees: bool = False
81
+ is_estimated: bool = False
82
+ is_ongoing: bool = False
83
+ duration_months: Optional[int] = None
84
+ min_supply_months: Optional[int] = None
85
+ time_window: Optional[str] = None
86
+ installment_schedule: Optional[str] = None
87
+
88
+ class EnergyTargetSchema(BaseModel):
89
+ eligibility: EligibilitySchema
90
+ fees: List[FeeSchema] = []
91
+ incentives: List[IncentiveSchema] = []
92
+ discounts: List[DiscountSchema] = []