Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -55,50 +55,36 @@ class Customer(BaseModel):
|
|
| 55 |
def load_customers_from_dataset() -> List[Customer]:
|
| 56 |
"""Load customers from HF Dataset"""
|
| 57 |
try:
|
| 58 |
-
print(f"π
|
| 59 |
|
| 60 |
-
# Load with
|
| 61 |
dataset = load_dataset(
|
| 62 |
DATASET_NAME,
|
| 63 |
split="train",
|
| 64 |
-
token=HF_TOKEN
|
| 65 |
-
download_mode="force_redownload", # Always get latest data
|
| 66 |
-
verification_mode="no_checks" # Skip verification for faster loading
|
| 67 |
)
|
| 68 |
|
| 69 |
-
print(f"β
|
| 70 |
customers = []
|
| 71 |
|
| 72 |
-
if len(dataset) == 0:
|
| 73 |
-
print("π Dataset is empty")
|
| 74 |
-
return []
|
| 75 |
-
|
| 76 |
for row in dataset:
|
| 77 |
try:
|
| 78 |
-
# Handle both string and integer IDs
|
| 79 |
-
customer_id = int(row['id']) if isinstance(row['id'], str) else row['id']
|
| 80 |
-
|
| 81 |
-
# Clean and validate data
|
| 82 |
-
phone_val = row.get('phone', '')
|
| 83 |
-
address_val = row.get('address', '')
|
| 84 |
-
|
| 85 |
customers.append(Customer(
|
| 86 |
-
id=
|
| 87 |
name=str(row['name']),
|
| 88 |
email=str(row['email']),
|
| 89 |
-
phone=str(
|
| 90 |
-
address=str(
|
| 91 |
))
|
| 92 |
except Exception as row_error:
|
| 93 |
-
print(f"β οΈ
|
| 94 |
continue
|
| 95 |
|
| 96 |
-
print(f"π
|
| 97 |
return customers
|
| 98 |
|
| 99 |
except Exception as e:
|
| 100 |
-
print(f"
|
| 101 |
-
print("β οΈ Returning empty customer list. Check dataset exists and HF_TOKEN is set.")
|
| 102 |
return []
|
| 103 |
|
| 104 |
def save_customers_to_dataset(customers: List[Customer]):
|
|
@@ -118,95 +104,62 @@ def save_customers_to_dataset(customers: List[Customer]):
|
|
| 118 |
df = pd.DataFrame(data)
|
| 119 |
print(f"πΎ Saving {len(customers)} customers to dataset...")
|
| 120 |
|
| 121 |
-
#
|
| 122 |
df.to_csv("customers.csv", index=False)
|
| 123 |
-
print("π Local backup saved
|
| 124 |
|
| 125 |
-
# Upload to HF Dataset
|
| 126 |
if HF_TOKEN:
|
| 127 |
try:
|
| 128 |
-
# Method 1: Direct file upload (most reliable)
|
| 129 |
upload_file(
|
| 130 |
path_or_fileobj="customers.csv",
|
| 131 |
path_in_repo="customers.csv",
|
| 132 |
repo_id=DATASET_NAME,
|
| 133 |
repo_type="dataset",
|
| 134 |
-
token=HF_TOKEN
|
| 135 |
-
commit_message=f"Update dataset with {len(customers)} customers"
|
| 136 |
)
|
| 137 |
-
print(f"β
Successfully
|
| 138 |
|
| 139 |
-
# Small delay
|
| 140 |
import time
|
| 141 |
-
time.sleep(
|
| 142 |
|
| 143 |
except Exception as e:
|
| 144 |
-
print(f"
|
| 145 |
-
|
| 146 |
-
# Method 2: Fallback with Dataset.push_to_hub
|
| 147 |
-
try:
|
| 148 |
-
print("π Trying alternative method...")
|
| 149 |
-
from datasets import Dataset
|
| 150 |
-
hf_dataset = Dataset.from_pandas(df)
|
| 151 |
-
|
| 152 |
-
hf_dataset.push_to_hub(
|
| 153 |
-
DATASET_NAME,
|
| 154 |
-
token=HF_TOKEN,
|
| 155 |
-
split="train",
|
| 156 |
-
commit_message=f"Update with {len(customers)} customers"
|
| 157 |
-
)
|
| 158 |
-
print("β
Alternative upload method successful")
|
| 159 |
-
|
| 160 |
-
except Exception as e2:
|
| 161 |
-
print(f"β Both upload methods failed: {e2}")
|
| 162 |
-
raise HTTPException(
|
| 163 |
-
status_code=500,
|
| 164 |
-
detail="Failed to save data to HuggingFace dataset. Please try again."
|
| 165 |
-
)
|
| 166 |
else:
|
| 167 |
-
print("β οΈ
|
| 168 |
-
|
| 169 |
-
status_code=500,
|
| 170 |
-
detail="HF_TOKEN not configured. Cannot save to dataset."
|
| 171 |
-
)
|
| 172 |
-
|
| 173 |
-
except HTTPException:
|
| 174 |
-
raise # Re-raise HTTP exceptions
|
| 175 |
except Exception as e:
|
| 176 |
-
print(f"β
|
| 177 |
-
raise
|
| 178 |
-
status_code=500,
|
| 179 |
-
detail=f"Internal error while saving data: {str(e)}"
|
| 180 |
-
)
|
| 181 |
# Create
|
| 182 |
@app.post("/Customer", response_model=Customer)
|
| 183 |
def create_customer(customer: Customer):
|
| 184 |
-
print(f"β Creating
|
| 185 |
customers = load_customers_from_dataset()
|
| 186 |
-
print(f"π Current customers
|
| 187 |
|
| 188 |
# Check for unique ID
|
| 189 |
-
existing_ids = [
|
| 190 |
if customer.id in existing_ids:
|
| 191 |
-
print(f"β
|
| 192 |
raise HTTPException(
|
| 193 |
status_code=400,
|
| 194 |
-
detail=f"Customer
|
| 195 |
)
|
| 196 |
|
| 197 |
customers.append(customer)
|
| 198 |
-
print(f"π Total customers after adding: {len(customers)}")
|
| 199 |
-
|
| 200 |
save_customers_to_dataset(customers)
|
| 201 |
-
print(f"β
|
| 202 |
return customer
|
| 203 |
|
| 204 |
# Read
|
| 205 |
@app.get("/Customer", response_model=List[Customer])
|
| 206 |
def get_customer():
|
| 207 |
-
print("π
|
| 208 |
customers = load_customers_from_dataset()
|
| 209 |
-
print(f"π
|
| 210 |
return customers
|
| 211 |
|
| 212 |
# Update
|
|
|
|
| 55 |
def load_customers_from_dataset() -> List[Customer]:
|
| 56 |
"""Load customers from HF Dataset"""
|
| 57 |
try:
|
| 58 |
+
print(f"π Loading dataset: {DATASET_NAME}")
|
| 59 |
|
| 60 |
+
# Load dataset with minimal options
|
| 61 |
dataset = load_dataset(
|
| 62 |
DATASET_NAME,
|
| 63 |
split="train",
|
| 64 |
+
token=HF_TOKEN
|
|
|
|
|
|
|
| 65 |
)
|
| 66 |
|
| 67 |
+
print(f"β
Dataset loaded: {len(dataset)} rows")
|
| 68 |
customers = []
|
| 69 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 70 |
for row in dataset:
|
| 71 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
customers.append(Customer(
|
| 73 |
+
id=int(row['id']),
|
| 74 |
name=str(row['name']),
|
| 75 |
email=str(row['email']),
|
| 76 |
+
phone=str(row.get('phone', '')) if row.get('phone') and row.get('phone') != '' else None,
|
| 77 |
+
address=str(row.get('address', '')) if row.get('address') and row.get('address') != '' else None
|
| 78 |
))
|
| 79 |
except Exception as row_error:
|
| 80 |
+
print(f"β οΈ Skipping invalid row: {row_error}")
|
| 81 |
continue
|
| 82 |
|
| 83 |
+
print(f"π Loaded {len(customers)} customers")
|
| 84 |
return customers
|
| 85 |
|
| 86 |
except Exception as e:
|
| 87 |
+
print(f"β οΈ Load error: {e}")
|
|
|
|
| 88 |
return []
|
| 89 |
|
| 90 |
def save_customers_to_dataset(customers: List[Customer]):
|
|
|
|
| 104 |
df = pd.DataFrame(data)
|
| 105 |
print(f"πΎ Saving {len(customers)} customers to dataset...")
|
| 106 |
|
| 107 |
+
# Save locally first as backup
|
| 108 |
df.to_csv("customers.csv", index=False)
|
| 109 |
+
print("π Local backup saved")
|
| 110 |
|
| 111 |
+
# Upload to HF Dataset if token is available
|
| 112 |
if HF_TOKEN:
|
| 113 |
try:
|
|
|
|
| 114 |
upload_file(
|
| 115 |
path_or_fileobj="customers.csv",
|
| 116 |
path_in_repo="customers.csv",
|
| 117 |
repo_id=DATASET_NAME,
|
| 118 |
repo_type="dataset",
|
| 119 |
+
token=HF_TOKEN
|
|
|
|
| 120 |
)
|
| 121 |
+
print(f"β
Successfully saved {len(customers)} customers to dataset")
|
| 122 |
|
| 123 |
+
# Small delay for sync
|
| 124 |
import time
|
| 125 |
+
time.sleep(1)
|
| 126 |
|
| 127 |
except Exception as e:
|
| 128 |
+
print(f"β οΈ Upload error: {e}")
|
| 129 |
+
# Don't fail the operation, just log the error
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 130 |
else:
|
| 131 |
+
print("β οΈ HF_TOKEN not set - data saved locally only")
|
| 132 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 133 |
except Exception as e:
|
| 134 |
+
print(f"β Error in save_customers_to_dataset: {e}")
|
| 135 |
+
# Don't raise exception to avoid breaking the API
|
|
|
|
|
|
|
|
|
|
| 136 |
# Create
|
| 137 |
@app.post("/Customer", response_model=Customer)
|
| 138 |
def create_customer(customer: Customer):
|
| 139 |
+
print(f"β Creating customer ID: {customer.id}")
|
| 140 |
customers = load_customers_from_dataset()
|
| 141 |
+
print(f"π Current customers: {len(customers)}")
|
| 142 |
|
| 143 |
# Check for unique ID
|
| 144 |
+
existing_ids = [c.id for c in customers]
|
| 145 |
if customer.id in existing_ids:
|
| 146 |
+
print(f"β ID {customer.id} already exists")
|
| 147 |
raise HTTPException(
|
| 148 |
status_code=400,
|
| 149 |
+
detail=f"Customer ID {customer.id} already exists"
|
| 150 |
)
|
| 151 |
|
| 152 |
customers.append(customer)
|
|
|
|
|
|
|
| 153 |
save_customers_to_dataset(customers)
|
| 154 |
+
print(f"β
Created customer {customer.id}")
|
| 155 |
return customer
|
| 156 |
|
| 157 |
# Read
|
| 158 |
@app.get("/Customer", response_model=List[Customer])
|
| 159 |
def get_customer():
|
| 160 |
+
print("π Getting all customers")
|
| 161 |
customers = load_customers_from_dataset()
|
| 162 |
+
print(f"π Found {len(customers)} customers")
|
| 163 |
return customers
|
| 164 |
|
| 165 |
# Update
|