timfocus commited on
Commit
e508c3f
·
verified ·
1 Parent(s): 37f1d60

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +66 -82
app.py CHANGED
@@ -1,102 +1,86 @@
1
- import gradio as gr
2
- import pandas as pd
3
  import os
4
- import zipfile
5
- from reportlab.lib.pagesizes import inch
 
6
  from reportlab.pdfgen import canvas
7
- from reportlab.lib.utils import ImageReader
8
  import barcode
9
  from barcode.writer import ImageWriter
10
 
11
- # Ensure 'labels' directory exists
12
- os.makedirs("labels", exist_ok=True)
13
-
14
- def generate_label(data, index):
15
- """
16
- Generate a 4x6 inch shipping label as a PDF.
17
- """
18
- pdf_filename = f"labels/shipping_label_{index+1}.pdf"
19
- c = canvas.Canvas(pdf_filename, pagesize=(4 * inch, 6 * inch))
20
 
21
- # Draw sender details
22
- c.setFont("Helvetica-Bold", 12)
23
- c.drawString(30, 500, "From:")
24
- c.setFont("Helvetica", 10)
25
- c.drawString(30, 485, str(data.get('Sender Name', '')))
26
- c.drawString(30, 470, str(data.get('Sender Address', '')))
27
- c.drawString(30, 455, str(data.get('Sender City, State ZIP', '')))
28
-
29
- # Draw recipient details
30
- c.setFont("Helvetica-Bold", 12)
31
- c.drawString(30, 400, "To:")
32
- c.setFont("Helvetica", 10)
33
- c.drawString(30, 385, str(data.get('Recipient Name', '')))
34
- c.drawString(30, 370, str(data.get('Recipient Address', '')))
35
- c.drawString(30, 355, str(data.get('Recipient City, State ZIP', '')))
36
-
37
- # Draw shipping service
38
- c.setFont("Helvetica-Bold", 12)
39
- c.drawString(30, 320, f"Service: {str(data.get('Shipping Service', ''))}")
40
 
41
- # Draw tracking number
42
- c.setFont("Helvetica-Bold", 12)
43
- c.drawString(30, 280, "Tracking #:")
44
- c.setFont("Helvetica", 12)
45
- c.drawString(30, 260, str(data.get('Tracking Number', '')))
46
 
47
- # Generate barcode
48
- barcode_filename = f"labels/barcode_{index+1}.png"
49
- tracking_number = str(data.get('Tracking Number', '000000000'))
50
- ean = barcode.get_barcode_class('code128')
51
- ean_obj = ean(tracking_number, writer=ImageWriter())
52
- ean_obj.save(barcode_filename)
53
 
54
- # Add barcode to label
55
- barcode_img = ImageReader(barcode_filename)
56
- c.drawImage(barcode_img, 30, 120, width=300, height=100)
57
 
58
- # Save PDF
59
- c.showPage()
60
- c.save()
61
 
62
- def process_file(file_obj):
63
- """
64
- Read CSV or Excel file and generate shipping labels.
65
- """
66
  try:
67
- # Read file into Pandas (directly from file object)
68
- if file_obj.name.endswith('.csv'):
69
- df = pd.read_csv(file_obj) # Directly read from the file object
70
- elif file_obj.name.endswith(('.xls', '.xlsx')):
71
- df = pd.read_excel(file_obj) # Read Excel file directly
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72
  else:
73
- return "Invalid file format. Please upload a .csv, .xls, or .xlsx file."
74
 
75
- # Generate labels for each row
76
- for i, row in df.iterrows():
77
- generate_label(row, i)
78
-
79
- # Zip all PDFs into a single file for download
80
- zip_filename = "labels/shipping_labels.zip"
81
- with zipfile.ZipFile(zip_filename, "w") as zipf:
82
- for label_file in os.listdir("labels"):
83
- if label_file.endswith(".pdf"):
84
- zipf.write(f"labels/{label_file}", label_file)
85
-
86
- return zip_filename
87
 
 
88
  except Exception as e:
89
- return f"Error processing file: {str(e)}"
90
 
91
- # Gradio Interface
92
- interface = gr.Interface(
93
  fn=process_file,
94
- inputs=gr.File(label="Upload CSV or Excel File"),
95
- outputs=gr.File(label="Download Shipping Labels (ZIP)"),
96
- title="4x6 Shipping Label Generator",
97
- description="Upload a .csv or .xlsx file with shipping details, and this app will generate professional 4x6 shipping labels with barcodes.",
98
  )
99
 
100
- # Run the app
101
- if __name__ == "__main__":
102
- interface.launch()
 
 
 
1
  import os
2
+ import pandas as pd
3
+ import gradio as gr
4
+ from reportlab.lib.pagesizes import landscape, letter
5
  from reportlab.pdfgen import canvas
 
6
  import barcode
7
  from barcode.writer import ImageWriter
8
 
9
+ # Ensure output directories exist
10
+ LABELS_DIR = "labels"
11
+ BARCODES_DIR = "barcodes"
12
+ os.makedirs(LABELS_DIR, exist_ok=True)
13
+ os.makedirs(BARCODES_DIR, exist_ok=True)
 
 
 
 
14
 
15
+ # Function to process the uploaded file
16
+ def process_file(file):
17
+ try:
18
+ # Load data from file
19
+ if file.name.endswith('.csv'):
20
+ df = pd.read_csv(file.name)
21
+ elif file.name.endswith(('.xls', '.xlsx')):
22
+ df = pd.read_excel(file.name)
23
+ else:
24
+ return "Invalid file format. Please upload a .csv, .xls, or .xlsx file."
 
 
 
 
 
 
 
 
 
25
 
26
+ # Ensure required columns exist
27
+ required_cols = ["Sender Name", "Receiver Name", "Address", "City", "State", "Zip", "Tracking Number"]
28
+ for col in required_cols:
29
+ if col not in df.columns:
30
+ return f"Missing column: {col}"
31
 
32
+ # Process each row and generate labels
33
+ label_files = []
34
+ for i, row in df.iterrows():
35
+ label_path = create_shipping_label(row, i + 1)
36
+ label_files.append(label_path)
 
37
 
38
+ return label_files
 
 
39
 
40
+ except Exception as e:
41
+ return f"Error processing file: {str(e)}"
 
42
 
43
+ # Function to create a shipping label
44
+ def create_shipping_label(row, index):
 
 
45
  try:
46
+ tracking_number = str(row["Tracking Number"])
47
+ barcode_path = os.path.join(BARCODES_DIR, f"barcode_{index}.png")
48
+
49
+ # Generate barcode
50
+ ean = barcode.get_barcode_class('code128')
51
+ ean = ean(tracking_number, writer=ImageWriter())
52
+ ean.save(barcode_path)
53
+
54
+ # Create PDF label
55
+ label_path = os.path.join(LABELS_DIR, f"label_{index}.pdf")
56
+ c = canvas.Canvas(label_path, pagesize=(4 * 72, 6 * 72)) # 4x6 inches
57
+
58
+ # Add sender & receiver details
59
+ c.setFont("Helvetica", 10)
60
+ c.drawString(20, 380, f"From: {row['Sender Name']}")
61
+ c.drawString(20, 360, f"To: {row['Receiver Name']}")
62
+ c.drawString(20, 340, f"Address: {row['Address']}, {row['City']}, {row['State']} {row['Zip']}")
63
+
64
+ # Add barcode
65
+ if os.path.exists(barcode_path):
66
+ c.drawImage(barcode_path, 20, 200, width=200, height=50)
67
  else:
68
+ c.drawString(20, 200, "Barcode generation failed.")
69
 
70
+ c.showPage()
71
+ c.save()
 
 
 
 
 
 
 
 
 
 
72
 
73
+ return label_path
74
  except Exception as e:
75
+ return f"Error creating label: {str(e)}"
76
 
77
+ # Gradio interface
78
+ iface = gr.Interface(
79
  fn=process_file,
80
+ inputs=gr.File(type="file"),
81
+ outputs=gr.File(type="file", label="Download Labels"),
82
+ title="Shipping Label Generator",
83
+ description="Upload a .csv, .xls, or .xlsx file to generate shipping labels."
84
  )
85
 
86
+ iface.launch()