VNPT / master /ui_pack /input_customer_info.py
VuvanAn's picture
Upload folder using huggingface_hub
2186e9b verified
import json
from typing import List, Optional
from pydantic import BaseModel, Field, EmailStr, ValidationError
# --- Simplified Class Definition using Pydantic ---
class Relation(BaseModel):
"""A Pydantic model for a single relation."""
citizen_id: str = Field(..., min_length=1)
relation_type: str = Field(..., min_length=1)
class Customer(BaseModel):
"""
A simplified and robust class to represent a customer using Pydantic.
Validation is handled automatically based on type hints.
"""
# Attributes with validation rules
name: str = Field(..., min_length=1, description="Customer's full name.")
birth: int = Field(..., gt=0, description="Customer's birth must be a positive number.")
current_position: str = Field(..., min_length=1)
# citizen_id: str = Field(..., min_length=12, max_length=12)
email: EmailStr # Automatic email format validation
# phone: str = Field(..., pattern=r'^\+?[0-9]{9,15}$', description="Phone number with country code.")
# Optional list of relations
relations: List[Relation] = []
def save(self, filepath: str = "customers.jsonl"):
"""
Saves the customer data to a JSONL file.
Each customer is appended as a new line.
"""
try:
with open(filepath, 'a', encoding='utf-8') as f:
# Pydantic has a built-in method to dump the model to a JSON string
f.write(self.model_dump_json() + '\n')
print(f"✅ Successfully saved customer '{self.name}' to {filepath}")
except IOError as e:
print(f"❌ Error saving file: {e}")
def as_string(self) -> str:
"""Returns the customer data as a formatted string."""
return f"""
Customer Information:
Name: {self.name}
Birth: {self.birth}
Position: {self.current_position}
Email: {self.email}
Phone: {self.phone}
Relations:
{self.relations}
"""
# --- Example Usage ---
# 1. Creating a valid customer
print("--- Attempting to create a valid customer ---")
try:
valid_customer = Customer(
name="Đảng Cộng sản Việt Nam",
birth=1930,
current_position="Đảng cầm quyền và là chính đảng duy nhất được phép hoạt động tại Việt Nam",
email="ngjabach@example.com",
)
print("Customer created successfully:")
print(valid_customer)
# Save the customer to a file
valid_customer.save()
except ValidationError as e:
print("Validation Error:", e)
print("\n" + "="*50 + "\n")
# 2. Creating an invalid customer (bad email and age)
# print("--- Attempting to create an invalid customer ---")
# try:
# invalid_customer = Customer(
# name="Trần Thị Bình",
# age=-5, # Invalid: age must be > 0
# current_position="Project Manager",
# citizen_id="098765432109",
# email="tran.binh@", # Invalid: not a valid email format
# phone="123", # Invalid: does not match pattern
# relations=[]
# )
# except ValidationError as e:
# print("❌ Caught expected validation errors:")
# print(e)