File size: 4,983 Bytes
1051f3b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d99c5f6
 
 
 
 
 
 
 
 
1051f3b
 
 
 
 
 
d99c5f6
 
 
 
 
1051f3b
 
 
 
 
d99c5f6
 
1051f3b
 
 
 
 
 
 
 
 
d99c5f6
 
1051f3b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d94ba5e
1051f3b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
import gradio as gr
import pandas as pd
import requests
import webbrowser

# Define the backend API URL (modify this to your backend's URL)
BACKEND_API_URL = "https://do0rmamu-truck-loading-poc.hf.space/submit_data/"

# Function to process the file and send data to the API
def process_file(file, truck_type, auto_suggest):
    try:
        # Debugging: Print when file is being processed
        print(f"Processing file: {file.name}")

        # Read the uploaded file into a Pandas DataFrame
        if file.name.endswith('.csv'):
            df = pd.read_csv(file.name)
        elif file.name.endswith('.xls') or file.name.endswith('.xlsx'):
            df = pd.read_excel(file.name)
        else:
            return "Unsupported file format. Please upload a CSV or Excel file."
        
        print(f"File processed successfully, data:\n{df.head()}")  # Print first few rows of the data

        # Define a destination mapping
        destination_mapping = {
            "Destination A": 1,
            "Destination B": 2,
            "Destination C": 3,
            "Destination D": 4,
            "Destination E": 5
        }

        # Prepare consignments data from the DataFrame
        consignments_data = []
        grouped = df.groupby('ConsignmentNo')
        for consignment_no, group in grouped:
            consignment_boxes = [
                {
                    'PieceLength': float(row['PieceLength']),
                    'PieceBreadth': float(row['PieceBreadth']),
                    'PieceHeight': float(row['PieceHeight']),
                    'Priority': int(row.get('Priority', 0)),
                    'Destination': row.get('Destination', "Unknown")
                }
                for _, row in group.iterrows()
            ]
            consignments_data.append({
                'ConsignmentNo': str(consignment_no),  # Convert ConsignmentNo to string
                'Priority': int(group['Priority'].max()),  # Ensure Priority is int
                'Destination': group['Destination'].iloc[0],  # Taking the destination of the first box
                'boxes': consignment_boxes
            })

        print(f"Consignment data prepared:\n{consignments_data}")

        # Prepare the JSON payload to be sent
        json_data = {
            'truck_name': truck_type,
            'autoSuggest': auto_suggest,
            'consignments_data': consignments_data,
            'destination_mapping': destination_mapping  # Include destination mapping in payload
        }

        print(f"Sending the following data to backend:\n{json_data}")

        # Send the data as JSON to the backend
        response = requests.post(BACKEND_API_URL, json=json_data, allow_redirects=False)

        print(f"Received response from backend, status code: {response.status_code}")

        # Handle redirect (302 Found)
        if response.status_code == 302:
            redirect_url = response.headers.get('Location')
            if redirect_url:
                print(f"Redirecting to: {redirect_url}")
                webbrowser.open(redirect_url)
                return f"Redirecting to visualization: {redirect_url}"
        elif response.status_code != 200:
            return f"Failed to submit data. Status code: {response.status_code}\nError message: {response.text}"
        
        return "Data submitted successfully."

    except Exception as e:
        print(f"Exception occurred: {str(e)}")
        return f"An error occurred: {str(e)}"

# Gradio interface
def gradio_interface():
    # Define available truck types
    truck_types = [
        "TATA ACE", "ASHOK LEYLAND DOST", "MAHINDRA BOLERO PICK UP", 
        "ASHOK LEYLAND BADA DOST", "TATA 407", "EICHER 14 FEET",
        "EICHER 17 FEET", "EICHER 19 FEET", "TATA 22 FEET",
        "TATA TRUCK (6 TYRE)", "TAURUS 16 T (10 TYRE)", "TAURUS 21 T (12 TYRE)",
        "TAURUS 25 T (14 TYRE)", "CONTAINER 20 FT", "CONTAINER 32 FT SXL",
        "CONTAINER 32 FT MXL", "CONTAINER 32 FT SXL / MXL HQ",
        "20 FEET OPEN ALL SIDE (ODC)", "28-32 FEET OPEN-TRAILOR JCB ODC",
        "32 FEET OPEN-TRAILOR ODC", "40 FEET OPEN-TRAILOR ODC", "SCV", "LCV", 
        "ICV", "MCV"
    ]

    with gr.Blocks() as demo:
        # Title
        gr.Markdown("## Truck Loading Data Submission")
        
        # File Upload Input
        file_input = gr.File(label="Upload your consignments file (CSV or Excel)")

        # Truck Type Dropdown
        truck_type_input = gr.Dropdown(truck_types, label="Select Truck Type", value="TATA ACE")

        # Auto-Suggest Checkbox
        auto_suggest_input = gr.Checkbox(label="Auto-Suggest Truck", value=False)

        # Submit Button
        submit_button = gr.Button("Submit Data")

        # Output Textbox
        output_text = gr.Markdown()

        # Define interaction
        submit_button.click(process_file, [file_input, truck_type_input, auto_suggest_input], output_text)

    return demo

# Run the Gradio interface
gradio_interface().launch()