volta-parser / engine.py
Toan2004-ai
add readme config
4f473e5
Raw History Blame Contribute Delete
13.6 kB
import json
import re
from pydantic import ValidationError
import torch
from json_repair import repair_json
from schema import EnergyTargetSchema
# from model_manager import get_model_and_tokenizer
def final_process_eme_technical_guided(input_text):
# 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ệ
try:
original_input_data = json.loads(input_text)
except json.JSONDecodeError:
original_input_data = {}
parsed_json = original_input_data.copy()
electricity_contract = original_input_data.get("electricity_contract", {})
# ELIGIBILITY
contract_eligibility = electricity_contract.get("eligibility", [])
is_new_customer = False
for el in contract_eligibility:
if el.get("type") == "NEW_CUSTOMER":
is_new_customer = True
desc = el.get("description", "")
model_eligibility = parsed_json.get("eligibility", {})
if not isinstance(model_eligibility, dict):
model_eligibility = {}
model_eligibility["is_new_customer"] = is_new_customer
if not model_eligibility.get("customer_type"):
model_eligibility["customer_type"] = original_input_data.get("customer_type") or "RESIDENTIAL"
distributor_value = original_input_data.get("distributor")
if not distributor_value and "geography" in original_input_data:
dist_list = original_input_data["geography"].get("distributors", [])
if dist_list and isinstance(dist_list, list):
distributor_value = dist_list
if not distributor_value:
distributor_value = model_eligibility.get("distributor")
if distributor_value:
if isinstance(distributor_value, str):
model_eligibility["distributor"] = [distributor_value]
elif isinstance(distributor_value, list):
model_eligibility["distributor"] = ", ".join(distributor_value)
else:
model_eligibility["distributor"] = str(distributor_value)
else:
model_eligibility["distributor"] = []
plan_id = original_input_data.get("plan_id", "")
metadata_source = original_input_data.get("metadata", {}).get("source", "")
is_vic_plan = "VEC" in plan_id or metadata_source == "VEC" or model_eligibility.get("is_victorian", False)
model_eligibility["is_victorian"] = is_vic_plan
if not model_eligibility.get("tariff_types") and "pricingModel" in electricity_contract:
model_eligibility["tariff_types"] = [electricity_contract["pricingModel"]]
if "solarFeedInTariff" in electricity_contract and electricity_contract["solarFeedInTariff"]:
model_eligibility["has_feed_in_tariff"] = True
if original_input_data.get("ops_status") == "PENDING" and not model_eligibility.get("channel"):
model_eligibility["channel"] = "PENDING"
if metadata_source in ["VEC", "EME"] and not model_eligibility.get("comparator_name"):
model_eligibility["comparator_name"] = metadata_source
if "is_generally_available" not in model_eligibility:
model_eligibility["is_generally_available"] = True
# FEES
model_fees = parsed_json.get("fees", [])
if not isinstance(model_fees, list):
model_fees = []
final_fees = []
seen_fee_types = set()
for m_fee in model_fees:
if not isinstance(m_fee, dict): continue
f_type = m_fee.get("fee_type") or m_fee.get("type")
if not f_type: continue
t_context = m_fee.get("trigger_context") or m_fee.get("description")
if not t_context:
for orig_fee in electricity_contract.get("fees", []):
if orig_fee.get("type") == f_type:
t_context = orig_fee.get("description")
break
raw_val = m_fee.get("value") if m_fee.get("value") is not None else m_fee.get("amount")
try: fee_val = float(raw_val) if raw_val is not None else None
except: fee_val = None
cleaned_fee = {
"fee_type": f_type,
"amount_type": m_fee.get("amount_type") or "FIXED",
"value": fee_val,
"value_display": m_fee.get("value_display") or (f"${fee_val:.2f}" if fee_val else None),
"tax_inclusive": m_fee.get("tax_inclusive", True),
"payment_method": m_fee.get("payment_method"),
"is_waived": m_fee.get("is_waived", False),
"waived_for": m_fee.get("waived_for"),
"trigger_context": t_context,
"is_variable": m_fee.get("is_variable", False),
"is_pass_through": m_fee.get("is_pass_through", False)
}
final_fees.append(cleaned_fee)
seen_fee_types.add(f_type)
for orig_fee in electricity_contract.get("fees", []):
f_type = orig_fee.get("type")
if f_type and f_type not in seen_fee_types:
raw_amount = orig_fee.get("amount") if orig_fee.get("amount") is not None else orig_fee.get("value")
try: fee_val = float(raw_amount) if raw_amount else None
except: fee_val = None
fallback_fee = {
"fee_type": f_type,
"amount_type": orig_fee.get("term") or "FIXED",
"value": fee_val,
"value_display": f"${fee_val:.2f}" if fee_val else None,
"tax_inclusive": True,
"trigger_context": orig_fee.get("description"),
"is_waived": False,
"is_variable": False,
"is_pass_through": False
}
final_fees.append(fallback_fee)
seen_fee_types.add(f_type)
# DISCOUNTS
model_discounts = parsed_json.get("discounts", [])
if not isinstance(model_discounts, list):
model_discounts = []
final_discounts = []
for m_disc in model_discounts:
if not isinstance(m_disc, dict): continue
rate_val = m_disc.get("rate")
if rate_val is None or float(rate_val) == 0.0:
for orig_disc in electricity_contract.get("discounts", []):
for rate_key in ["percentOfBill", "percentOfUse", "percentOfDemand", "percentOfSolar"]:
if rate_key in orig_disc and "rate" in orig_disc[rate_key]:
try: rate_val = float(orig_disc[rate_key]["rate"])
except: pass
break
m_disc["rate"] = rate_val if rate_val is not None else 0.0
if not m_disc.get("discount_condition") and "description" in m_disc:
m_disc["discount_condition"] = [m_disc["description"]]
final_discounts.append(m_disc)
if not final_discounts:
for orig_disc in electricity_contract.get("discounts", []):
rate_val = None
amount_val = None
for rate_key in ["percentOfBill", "percentOfUse", "percentOfDemand", "percentOfSolar"]:
if rate_key in orig_disc and "rate" in orig_disc[rate_key]:
raw_rate = orig_disc[rate_key]["rate"]
rate_val = float(raw_rate)
break
description = orig_disc.get("description", "")
dollar_match = re.search(r'\$(\d+\.?\d*)', description)
if dollar_match and "%" not in description and rate_val and rate_val >= 1.0:
amount_val = float(dollar_match.group(1))
rate_val = None
fallback_disc = {
"discount_type": orig_disc.get("type") or "GUARANTEED",
"raw_category": orig_disc.get("category") or "percentOfUse",
"display_name": orig_disc.get("displayName") or orig_disc.get("description"),
"method": orig_disc.get("methodUType") or "percentOfUse",
"rate": float(rate_val) if rate_val else 0.15,
"discount_condition": [orig_disc.get("description")] if orig_disc.get("description") else []
}
final_discounts.append(fallback_disc)
# INCENTIVES
detected_loyalty_program = None
reward_network = None
for el in contract_eligibility:
if el.get("type") == "LOYALTY_MEMBER":
desc_el = el.get("description", "")
# Logic: Nếu có từ khóa Qantas thì gán tên cụ thể
if "Qantas" in desc_el:
detected_loyalty_program = "Qantas Business Rewards"
else:
detected_loyalty_program = "Loyalty Program"
break
final_incentives = []
model_incentives = parsed_json.get("incentives", [])
if isinstance(model_incentives, list):
for item in model_incentives:
if isinstance(item, dict):
final_incentives.append(item)
contract_incentives = electricity_contract.get("incentives", [])
incentive_type = "SOLAR_REBATE"
raw_category = "solar_fiT"
display_name = ""
default_payer_type = original_input_data.get("payerType", "RETAILER")
current_payer_type = default_payer_type
for item in contract_incentives:
if not isinstance(item, dict): continue
display_name = item.get("displayName", "")
desc = item.get("description")
current_payer_type = item.get("payerType") or default_payer_type
reward_network = None
desc_lower = desc.lower()
if "visa" in desc_lower: reward_network = "Visa"
elif "mastercard" in desc_lower: reward_network = "Mastercard"
elif "amex" in desc_lower: reward_network = "American Express"
if "Points" in desc or "Qantas" in desc:
points_match = re.search(r'(\d{1,3}(?:,\d{3})*)', desc)
points = int(points_match.group(1).replace(',', '')) if points_match else None
if current_payer_type == "RETAILER":
incentive_type = "SOLAR_REBATE"
raw_category = "retailer_solar_fiT"
elif current_payer_type == "GOVERNMENT":
incentive_type = "GOVERNMENT_REBATE"
raw_category = "government_solar_fiT"
else:
incentive_type = "SOLAR_REBATE"
raw_category = "solar_fiT"
final_incentives.append({
"incentive_type": current_payer_type,
"raw_category": raw_category,
"display_name": display_name,
"points_value": points,
"amount_aud": None,
"value_display": None,
"loyalty_program": detected_loyalty_program,
"reward_card_network": reward_network,
"is_recurring": "every" in desc.lower() or "per" in desc.lower(),
"tax_inclusive": True,
"customer_scope": [model_eligibility["customer_type"]] if isinstance(model_eligibility.get("customer_type"), str) else model_eligibility.get("customer_type", []),
"limit_per_account": None,
"trigger": "FIRST_BILL" if "first" in desc.lower() else None
})
else:
amount_match = re.search(r'\$(\d+(?:\.\d+)?)', desc)
amount = float(amount_match.group(1)) if amount_match else None
# Thêm vào nếu chưa tồn tại (tránh trùng lặp)
final_incentives.append({
"incentive_type": current_payer_type,
"raw_category": raw_category,
"display_name": display_name,
"amount_aud": amount,
"value_display": f"${amount}" if amount else None,
"loyalty_program": detected_loyalty_program,
"reward_card_network": reward_network,
"is_recurring": False if "Once Off" in desc else True,
"tax_inclusive": True,
"customer_scope": [model_eligibility["customer_type"]] if isinstance(model_eligibility.get("customer_type"), str) else model_eligibility.get("customer_type", []),
"limit_per_account": None,
"trigger": "FIRST_BILL" if "Once Off" in desc else None
})
if "solarFeedInTariff" in electricity_contract:
for s_fit in electricity_contract["solarFeedInTariff"]:
rates = s_fit.get("singleTariff", {}).get("rates", [])
unit_price = float(rates[0].get("unitPrice", 0.005)) if rates else 0.005
fit_display_name = s_fit.get("displayName", "Solar feed-in tariff (FIT)")
final_incentives.append({
"incentive_type": current_payer_type,
"raw_category": raw_category,
"display_name": fit_display_name,
"amount_aud": unit_price,
"tax_inclusive": True,
"value_display": f"${unit_price}/kWh",
"loyalty_program": detected_loyalty_program,
"reward_card_network": reward_network,
"is_recurring": True,
"customer_scope": [model_eligibility["customer_type"]] if isinstance(model_eligibility.get("customer_type"), str) else model_eligibility.get("customer_type", []),
"trigger": "SOLAR_EXPORT",
"timing_months": 1,
"limit_per_account": None
})
parsed_json["eligibility"] = model_eligibility
parsed_json["fees"] = final_fees
parsed_json["discounts"] = final_discounts
parsed_json["incentives"] = final_incentives
try:
return EnergyTargetSchema(**parsed_json)
except ValidationError as e:
raise ValueError(f"Pydantic validation error: {e}")