Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828339 unmodified lines12312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416512 unmodified lines178179180181import streamlit as stst.set_page_config(page_title="Packaging Box Cost Calculator", layout="wide")import requestsimport osimport jsonimport gspreadfrom google.oauth2.service_account import Credentialsfrom datetime import datetime# Google Sheets API setupdef setup_google_sheets():"""Sets up the Google Sheets API connection."""try:# Check if credentials file exists in the environment variable or local filecreds_info = os.getenv("GOOGLE_CREDENTIALS")if creds_info:# If the credentials are stored as an environment variable (JSON string)creds_dict = json.loads(creds_info)creds = Credentials.from_service_account_info(creds_dict,scopes=["https://www.googleapis.com/auth/spreadsheets","https://www.googleapis.com/auth/drive"])else:# Fallback to looking for a local credentials filecreds = Credentials.from_service_account_file("credentials.json",scopes=["https://www.googleapis.com/auth/spreadsheets","https://www.googleapis.com/auth/drive"])return gspread.authorize(creds)except Exception as e:st.warning(f"Google Sheets integration is not configured: {str(e)}")return Nonedef save_to_google_sheet(data):"""Saves the calculated box cost data to a Google Sheet."""try:client = setup_google_sheets()if not client:return False, "Google Sheets integration is not configured."# Try to open existing spreadsheet or create a new oneSPREADSHEET_ID = os.getenv("SPREADSHEET_ID", "Packaging Box Cost Calculations")try:sheet = client.open(SPREADSHEET_ID)except gspread.exceptions.SpreadsheetNotFound:# Create new spreadsheet if it doesn't existsheet = client.create(SPREADSHEET_ID)# Share with service account emailif os.getenv("SHARE_EMAIL"):sheet.share(os.getenv("SHARE_EMAIL"), perm_type='user', role='writer')# Setup headers for the worksheetworksheet = sheet.sheet1worksheet.update("A1:H1", [["Timestamp", "Company Name", "Box Length (in)", "Box Width (in)","Box Height (in)", "Material Type", "Blank Area (sq ft)", "Estimated Cost ($)"]])worksheet.format("A1:H1", {"textFormat": {"bold": True}})# Get the first worksheetworksheet = sheet.sheet1# Append data to the worksheettimestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")row = [timestamp] + list(data.values())worksheet.append_row(row)return True, f"Data saved to Google Sheet '{SPREADSHEET_ID}'."except Exception as e:return False, f"Error saving to Google Sheet: {str(e)}"def calculate_box_cost(length, width, height, material_type):"""Calculates the box cost based on dimensions and material type."""# Calculate blank area in square feet39 unmodified lines# Calculate the box costblank_area, cost = calculate_box_cost(box_length, box_width, box_height, material_type)# Format data for Google Sheetsform_data = {"Company Name": company_name if company_name else "Not specified","Box Length (in)": str(box_length),"Box Width (in)": str(box_width),"Box Height (in)": str(box_height),"Material Type": material_type,"Blank Area (sq ft)": f"{blank_area:.4f}","Estimated Cost ($)": f"{cost:.4f}"}# Save to Google Sheetssave_success, save_message = save_to_google_sheet(form_data)if save_success:st.success(save_message)else:st.warning(save_message)# Display resultsst.subheader("Cost Calculation Results")results_col1, results_col2 = st.columns(2)with results_col1:st.metric("Blank Area", f"{blank_area:.4f} sq ft")with results_col2:st.metric("Estimated Cost", f"${cost:.4f}")# Display calculation detailsst.markdown("### Calculation Details")st.markdown(f"""**Blank Area Formula:**```((2 × Length + 2 × Width + 1.5) × Height) ÷ 144```**Your Values:**```((2 × {box_length} + 2 × {box_width} + 1.5) × {box_height}) ÷ 144 = {blank_area:.4f} sq ft12 unmodified lines```{blank_area:.4f} sq ft × ${material_cost_factor} = ${cost:.4f}```""".replace("material_cost_factor", "0.10" if material_type == "32 ECT C-Flute" else "0.15" if material_type == "44 ECT C-Flute" else "0.08"))12345639 unmodified lines4647484950515253545556575812 unmodified lines71727374757677787980818283848586878889909192939495969798import streamlit as stst.set_page_config(page_title="Packaging Box Cost Calculator", layout="wide")def calculate_box_cost(length, width, height, material_type):"""Calculates the box cost based on dimensions and material type."""# Calculate blank area in square feet39 unmodified lines# Calculate the box costblank_area, cost = calculate_box_cost(box_length, box_width, box_height, material_type)# Display results - only showing cost, not area as requestedst.subheader("Cost Calculation Results")st.metric("Estimated Cost", f"${cost:.4f}")# Display calculation detailsst.markdown("### Calculation Details")st.markdown(f"""**Your Values:**```((2 × {box_length} + 2 × {box_width} + 1.5) × {box_height}) ÷ 144 = {blank_area:.4f} sq ft12 unmodified lines```{blank_area:.4f} sq ft × ${material_cost_factor} = ${cost:.4f}```""".replace("material_cost_factor", "0.10" if material_type == "32 ECT C-Flute" else "0.15" if material_type == "44 ECT C-Flute" else "0.08"))# Information about factors affecting box costst.markdown("### Factors Affecting Box Cost")st.markdown("""**Key Factors That Impact Packaging Box Costs:**1. **Material Type and Quality**: Higher ECT (Edge Crush Test) ratings indicate stronger boxes that can bear more weight, but increase cost. Premium materials with better moisture resistance or sustainability features also affect pricing.2. **Box Dimensions**: Larger boxes require more material and cost more. Non-standard sizes may require custom manufacturing, increasing costs further.3. **Order Volume**: Larger orders typically reduce per-unit costs due to economies of scale in production and shipping.4. **Printing and Finishing**: Custom printing, specialized coatings, or premium finishes add to the base cost of boxes.5. **Market Conditions**: Paper prices fluctuate based on supply chain issues, pulp availability, and energy costs. Recent global disruptions have caused significant price volatility.6. **Regulatory Compliance**: Meeting specific industry regulations (food safety, hazardous materials, etc.) may require specialized materials or treatments.7. **Shipping Distance**: Transportation costs are affected by fuel prices, distance, and logistics efficiency.8. **Sustainability Features**: Eco-friendly materials or manufacturing processes may add premium costs but can reduce environmental impact.9. **Supply Chain Efficiency**: Optimized supply chains with reduced waste and efficient distribution networks can lower overall packaging costs.""")
app.py+27-110