Spaces:
Sleeping
Sleeping
File size: 13,617 Bytes
922f211 aa6b9c9 922f211 14f8340 93c111a 922f211 8c4d658 922f211 603498a 1104599 9f196cd 1104599 9f196cd 922f211 1104599 922f211 bef295d 93c111a 922f211 93c111a 4f473e5 93c111a 922f211 603498a 922f211 603498a 922f211 603498a 1104599 6921918 1104599 6921918 1104599 603498a d9a8842 cb1e19b 682ae26 1104599 d9a8842 d77520c 603498a 782a1fe cb1e19b 04332cd 8be9928 b2439c7 cb1e19b b2439c7 cb1e19b b2439c7 8be9928 cb1e19b b2439c7 782a1fe b2439c7 1104599 8be9928 7fb4fa4 b2439c7 8be9928 cb1e19b b2439c7 782a1fe 8be9928 1104599 8be9928 ab8f91a b2439c7 8be9928 603498a d77520c 922f211 cb1e19b 603498a d77520c cb1e19b b2439c7 cb1e19b d77520c 922f211 1104599 922f211 7fb4fa4 922f211 b2439c7 603498a 922f211 d77520c 922f211 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 | 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}") |