RiwajTailors2 / app.py
engrharis's picture
Update app.py
865c054 verified
import streamlit as st
import pandas as pd
import os
import re
from datetime import datetime
from PIL import Image
from fpdf import FPDF
# Load data
def load_data():
if os.path.exists("data.csv"):
df = pd.read_csv("data.csv")
if 'SerialNo' not in df.columns:
df['SerialNo'] = range(1, len(df)+1)
return df
return pd.DataFrame(columns=["SerialNo", "Name", "Phone", "SizingText", "ImagePath", "StitchingHistory"])
# Save data
def save_data(df):
df['SerialNo'] = range(1, len(df)+1)
df.to_csv("data.csv", index=False)
# Export customer record as PDF
def export_as_pdf(customer):
pdf = FPDF()
pdf.add_page()
pdf.set_font("Arial", size=12)
pdf.cell(200, 10, txt="Tailor Record", ln=True, align="C")
pdf.ln(10)
pdf.cell(0, 10, f"Serial No: {customer['SerialNo']}", ln=True)
pdf.cell(0, 10, f"Name: {customer['Name']}", ln=True)
pdf.cell(0, 10, f"Phone: {customer['Phone']}", ln=True)
pdf.multi_cell(0, 10, f"Sizing Details: {customer['SizingText']}")
if customer["StitchingHistory"]:
pdf.cell(0, 10, "Stitching History:", ln=True)
for entry in str(customer["StitchingHistory"]).split(" || "):
pdf.multi_cell(0, 10, f"- {entry}")
filename = f"Tailor_Record_{customer['SerialNo']}_{customer['Name']}.pdf"
pdf.output(filename)
return filename
# UI Starts
st.set_page_config("Tailor Record App", layout="wide")
st.title("πŸ‘” Tailor Record Management System")
df = load_data()
# Add Record
st.subheader("βž• Add New Customer Record")
with st.form("new_customer"):
col1, col2 = st.columns(2)
with col1:
name = st.text_input("Customer Name*", max_chars=100)
phone = st.text_input("Phone Number*", max_chars=15, key="phone_input")
with col2:
sizing_text = st.text_area("Sizing Details*", height=200)
image = st.file_uploader("Optional: Upload sizing photo", type=["png", "jpg", "jpeg"])
st.markdown("**Stitching History (Optional):**")
history_entries = []
with st.expander("βž• Add Stitching History Entries (Optional)"):
num_entries = st.number_input("Number of entries", min_value=0, max_value=10, step=1)
for i in range(num_entries):
date = st.date_input(f"Stitch Date {i+1}", key=f"date_{i}")
desc = st.text_input(f"Description (optional) for Stitch {i+1}", key=f"desc_{i}")
history_entries.append(f"{date} - {desc}")
submitted = st.form_submit_button("πŸ’Ύ Save Record")
if submitted:
if not name or not phone or not phone.isdigit():
st.error("Customer Name and valid Phone Number are required!")
elif not sizing_text:
st.error("Sizing details are required!")
else:
image_path = ""
if image is not None:
os.makedirs("images", exist_ok=True)
timestamp = datetime.now().strftime('%Y%m%d%H%M%S')
image_path = os.path.join("images", f"{timestamp}_{image.name}")
try:
with open(image_path, "wb") as f:
f.write(image.getbuffer())
except Exception as e:
st.error(f"Error saving image: {e}")
image_path = ""
new_record = {
"SerialNo": len(df) + 1,
"Name": name.strip(),
"Phone": phone.strip(),
"SizingText": sizing_text.strip(),
"ImagePath": image_path,
"StitchingHistory": " || ".join(history_entries) if history_entries else ""
}
df = pd.concat([df, pd.DataFrame([new_record])], ignore_index=True)
df = df.sort_values(by="Name").reset_index(drop=True)
save_data(df)
st.success("Customer record saved successfully.")
st.rerun()