Spaces:
Sleeping
Sleeping
File size: 27,641 Bytes
e66683b 912fb34 505b3b7 e66683b d14a34d 505b3b7 8359aa8 d14a34d 912fb34 8359aa8 d14a34d 8359aa8 d14a34d 8359aa8 d14a34d 8359aa8 d14a34d ed63163 505b3b7 16c9b8c 505b3b7 d0693a3 505b3b7 d0693a3 505b3b7 d0693a3 ed63163 16c9b8c 505b3b7 d14a34d e66683b 912fb34 505b3b7 d14a34d 505b3b7 912fb34 505b3b7 912fb34 505b3b7 912fb34 505b3b7 912fb34 505b3b7 d14a34d 912fb34 505b3b7 d14a34d 505b3b7 d14a34d 505b3b7 912fb34 505b3b7 912fb34 505b3b7 912fb34 505b3b7 d14a34d 912fb34 505b3b7 d14a34d 505b3b7 d14a34d 505b3b7 912fb34 505b3b7 912fb34 505b3b7 912fb34 505b3b7 912fb34 d14a34d 912fb34 505b3b7 912fb34 505b3b7 912fb34 505b3b7 d14a34d 912fb34 d14a34d 505b3b7 d14a34d 505b3b7 912fb34 d14a34d 912fb34 505b3b7 912fb34 505b3b7 912fb34 505b3b7 912fb34 d14a34d 912fb34 505b3b7 912fb34 505b3b7 d14a34d d0693a3 505b3b7 d0693a3 505b3b7 912fb34 505b3b7 d0693a3 d14a34d 505b3b7 d14a34d 505b3b7 912fb34 505b3b7 912fb34 d14a34d 505b3b7 912fb34 505b3b7 d14a34d 505b3b7 d14a34d 505b3b7 d14a34d 505b3b7 d14a34d 505b3b7 d14a34d 505b3b7 d14a34d 505b3b7 d14a34d 505b3b7 912fb34 505b3b7 912fb34 505b3b7 d14a34d 505b3b7 912fb34 505b3b7 912fb34 505b3b7 912fb34 d14a34d 912fb34 505b3b7 912fb34 505b3b7 912fb34 505b3b7 912fb34 e66683b 912fb34 0cb8324 d14a34d |
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 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 |
import gradio as gr
import pandas as pd
import google.generativeai as genai
import joblib
from reportlab.lib import colors
from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle, Image
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
import plotly.express as px
import plotly.graph_objects as go
import tempfile
import os
from datetime import datetime
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
# Configure Gemini API
GEMINI_API_KEY = os.getenv("gemini_api")
if not GEMINI_API_KEY:
raise ValueError("GEMINI_API_KEY environment variable not found")
genai.configure(api_key=GEMINI_API_KEY)
generation_config = {
"temperature": 1,
"top_p": 0.95,
"top_k": 64,
"max_output_tokens": 8192,
}
model = genai.GenerativeModel(
model_name="gemini-pro",
generation_config=generation_config,
)
chat_model = genai.GenerativeModel("gemini-pro")
# Enhanced CSS for better styling
CUSTOM_CSS = '''
.gradio-container {
max-width: 1200px !important;
margin: auto !important;
padding: 20px !important;
background-color: #1a1a1a !important;
color: #ffffff !important;
}
.main-header {
background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%) !important;
color: white !important;
padding: 30px !important;
border-radius: 15px !important;
margin-bottom: 30px !important;
text-align: center !important;
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2) !important;
}
.app-title {
font-size: 2.5em !important;
font-weight: bold !important;
margin-bottom: 10px !important;
background: linear-gradient(90deg, #ffffff, #3498DB) !important;
-webkit-background-clip: text !important;
-webkit-text-fill-color: transparent !important;
text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3) !important;
}
.app-subtitle {
font-size: 1.3em !important;
color: #89CFF0 !important;
margin-bottom: 15px !important;
font-weight: 500 !important;
}
.app-description {
font-size: 1.1em !important;
color: #B0C4DE !important;
margin-bottom: 20px !important;
line-height: 1.5 !important;
}
.creator-info {
font-size: 1.2em !important;
color: #3498DB !important;
margin-top: 15px !important;
padding: 10px !important;
border-top: 2px solid rgba(52, 152, 219, 0.3) !important;
font-style: italic !important;
}
.status-box {
background: #363636 !important;
border-left: 4px solid #3498DB !important;
padding: 15px !important;
margin: 10px 0 !important;
border-radius: 0 5px 5px 0 !important;
color: #ffffff !important;
}
.chart-container {
background: #2d2d2d !important;
padding: 20px !important;
border-radius: 10px !important;
box-shadow: 0 2px 4px rgba(0,0,0,0.2) !important;
color: #ffffff !important;
}
.chat-container {
height: 400px !important;
overflow-y: auto !important;
border: 1px solid #404040 !important;
border-radius: 10px !important;
padding: 15px !important;
background: #2d2d2d !important;
color: #ffffff !important;
}
.file-upload {
border: 2px dashed #404040 !important;
border-radius: 10px !important;
padding: 20px !important;
text-align: center !important;
background: #2d2d2d !important;
color: #ffffff !important;
}
.result-box {
background: #363636 !important;
border: 1px solid #404040 !important;
border-radius: 10px !important;
padding: 20px !important;
margin-top: 15px !important;
color: #ffffff !important;
}
.tab-content {
background: #2d2d2d !important;
padding: 20px !important;
border-radius: 10px !important;
box-shadow: 0 2px 4px rgba(0,0,0,0.2) !important;
color: #ffffff !important;
}
input, select, textarea {
background: #363636 !important;
color: #ffffff !important;
border: 1px solid #404040 !important;
}
input:focus, select:focus, textarea:focus {
border-color: #3498DB !important;
box-shadow: 0 0 0 2px rgba(52, 152, 219, 0.2) !important;
}
.action-button {
background: #3498DB !important;
color: white !important;
border: none !important;
padding: 10px 20px !important;
border-radius: 5px !important;
cursor: pointer !important;
transition: all 0.3s ease !important;
}
.action-button:hover {
background: #2980B9 !important;
transform: translateY(-2px) !important;
box-shadow: 0 4px 8px rgba(0,0,0,0.2) !important;
}
.footer {
text-align: center !important;
padding: 20px !important;
margin-top: 40px !important;
border-top: 1px solid #404040 !important;
color: #888888 !important;
}
.tabs {
background: #2d2d2d !important;
border-radius: 10px !important;
padding: 10px !important;
}
.tab-selected {
background: #3498DB !important;
color: white !important;
}
.gr-box {
background: #2d2d2d !important;
border: 1px solid #404040 !important;
}
.gr-text-input {
background: #363636 !important;
color: #ffffff !important;
}
.gr-checkbox {
border-color: #404040 !important;
}
.gr-checkbox:checked {
background-color: #3498DB !important;
}
.gr-button-primary {
background: #3498DB !important;
color: white !important;
}
.gr-button-secondary {
background: #404040 !important;
color: white !important;
}
'''
class SupplyChainState:
def __init__(self):
self.sales_df = None
self.supplier_df = None
self.text_data = None
self.chat_history = []
self.analysis_results = {}
self.freight_predictions = []
# Load the XGBoost model
self.model_path = "optimized_xgboost_model.pkl"
try:
self.freight_model = joblib.load(self.model_path)
except Exception as e:
print(f"Warning: Could not load freight prediction model from {self.model_path}: {e}")
self.freight_model = None
def process_uploaded_data(state, sales_file, supplier_file, text_data):
"""Process uploaded files and store in state"""
try:
if sales_file is not None:
state.sales_df = pd.read_csv(sales_file.name)
if supplier_file is not None:
state.supplier_df = pd.read_excel(supplier_file.name)
state.text_data = text_data
return "β
Data processed successfully"
except Exception as e:
return f'β Error processing data: {str(e)}'
def perform_demand_forecasting(state):
"""Perform demand forecasting using Gemini"""
if state.sales_df is None:
return "Error: No sales data provided", None, "Please upload sales data first"
try:
sales_summary = state.sales_df.describe().to_string()
prompt = f"""Analyze the following sales data summary and provide:
1. A detailed demand forecast for the next quarter
2. Key trends and seasonality patterns
3. Actionable recommendations
Data Summary:
{sales_summary}
Please structure your response with clear sections for Forecast, Trends, and Recommendations."""
response = model.generate_content(prompt)
analysis_text = response.text
# Create visualization
fig = px.line(state.sales_df, title='Historical Sales Data and Forecast')
fig.update_layout(
template='plotly_dark',
title_x=0.5,
title_font_size=20,
showlegend=True,
hovermode='x',
paper_bgcolor='#2d2d2d',
plot_bgcolor='#363636',
font=dict(color='white')
)
return analysis_text, fig, "β
Analysis completed successfully"
except Exception as e:
return f"β Error in demand forecasting: {str(e)}", None, "Analysis failed"
def perform_risk_assessment(state):
"""Perform risk assessment using Gemini"""
if state.supplier_df is None:
return "Error: No supplier data provided", None, "Please upload supplier data first"
try:
supplier_summary = state.supplier_df.describe().to_string()
prompt = f"""Perform a comprehensive risk assessment based on:
Supplier Data Summary:
{supplier_summary}
Additional Context:
{state.text_data if state.text_data else 'No additional context provided'}
Please provide:
1. Risk scoring for each supplier
2. Identified risk factors
3. Mitigation recommendations"""
response = model.generate_content(prompt)
analysis_text = response.text
# Create risk visualization
fig = px.scatter(state.supplier_df, title='Supplier Risk Assessment')
fig.update_layout(
template='plotly_dark',
title_x=0.5,
title_font_size=20,
showlegend=True,
hovermode='closest',
paper_bgcolor='#2d2d2d',
plot_bgcolor='#363636',
font=dict(color='white')
)
return analysis_text, fig, "β
Risk assessment completed"
except Exception as e:
return f"β Error in risk assessment: {str(e)}", None, "Assessment failed"
def chat_with_navigator(state, message):
"""Handle chat interactions with the SupplyChainAI Navigator"""
try:
# Prepare context from available data
context = "Available data and analysis:\n"
if state.sales_df is not None:
context += f"- Sales data with {len(state.sales_df)} records\n"
if state.supplier_df is not None:
context += f"- Supplier data with {len(state.supplier_df)} records\n"
if state.text_data:
context += "- Additional context from text data\n"
if state.freight_predictions:
context += f"- Recent freight predictions: {state.freight_predictions[-5:]}\n"
# Add analysis results
if state.analysis_results:
context += "\nRecent analysis results:\n"
for analysis_type, results in state.analysis_results.items():
context += f"- {analysis_type} completed\n"
prompt = f"""You are SupplyChainAI Navigator's assistant. Help the user with supply chain analysis,
including demand forecasting, risk assessment, and freight cost predictions.
Available Context:
{context}
Chat History:
{str(state.chat_history[-3:]) if state.chat_history else 'No previous messages'}
User message: {message}
Provide a helpful response based on the available data and analysis results."""
response = chat_model.generate_content(prompt)
state.chat_history.append(("user", message))
state.chat_history.append(("assistant", response.text))
return state.chat_history
except Exception as e:
return [(msg_type, msg) for msg_type, msg in state.chat_history] + [("assistant", f"Error: {str(e)}")]
def predict_freight_cost(state, weight, line_item_value, cost_per_kg,
shipment_mode, air_charter_weight, ocean_weight, truck_weight,
air_charter_value, ocean_value, truck_value):
"""Predict freight cost using the loaded model"""
if state.freight_model is None:
return "Error: Freight prediction model not loaded"
try:
features = {
'weight (kilograms)': weight,
'line item value': line_item_value,
'cost per kilogram': cost_per_kg,
'shipment mode_Air Charter_weight': air_charter_weight if "Air" in shipment_mode else 0,
'shipment mode_Ocean_weight': ocean_weight if "Ocean" in shipment_mode else 0,
'shipment mode_Truck_weight': truck_weight if "Truck" in shipment_mode else 0,
'shipment mode_Air Charter_line_item_value': air_charter_value if "Air" in shipment_mode else 0,
'shipment mode_Ocean_line_item_value': ocean_value if "Ocean" in shipment_mode else 0,
'shipment mode_Truck_line_item_value': truck_value if "Truck" in shipment_mode else 0
}
input_data = pd.DataFrame([features])
prediction = state.freight_model.predict(input_data)
return round(float(prediction[0]), 2)
except Exception as e:
return f"Error making prediction: {str(e)}"
def generate_pdf_report(state, analysis_options):
"""Generate PDF report with analysis results"""
try:
temp_dir = tempfile.mkdtemp()
pdf_path = os.path.join(temp_dir, "supply_chain_report.pdf")
doc = SimpleDocTemplate(pdf_path, pagesize=letter)
styles = getSampleStyleSheet()
story = []
# Enhanced title style
title_style = ParagraphStyle(
'CustomTitle',
parent=styles['Heading1'],
fontSize=24,
spaceAfter=30,
textColor=colors.HexColor('#2C3E50')
)
# Add title
story.append(Paragraph("SupplyChainAI Navigator Report", title_style))
story.append(Spacer(1, 12))
# Add timestamp
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
story.append(Paragraph(f"Generated on: {timestamp}", styles['Normal']))
story.append(Spacer(1, 20))
# Add executive summary
story.append(Paragraph("Executive Summary", styles['Heading2']))
summary_text = "This report provides a comprehensive analysis of supply chain data, including demand forecasting, risk assessment, and optimization recommendations."
story.append(Paragraph(summary_text, styles['Normal']))
story.append(Spacer(1, 20))
# Add analysis results
if state.analysis_results:
for analysis_type, results in state.analysis_results.items():
if analysis_type in analysis_options:
story.append(Paragraph(analysis_type, styles['Heading2']))
story.append(Spacer(1, 12))
story.append(Paragraph(results['text'], styles['Normal']))
story.append(Spacer(1, 12))
if 'figure' in results:
img_path = os.path.join(temp_dir, f"{analysis_type.lower()}_plot.png")
results['figure'].write_image(img_path)
story.append(Image(img_path, width=400, height=300))
story.append(Spacer(1, 20))
# Add freight predictions if available
if state.freight_predictions:
story.append(Paragraph("Recent Freight Cost Predictions", styles['Heading2']))
story.append(Spacer(1, 12))
pred_data = [["Prediction #", "Cost (USD)"]]
for i, pred in enumerate(state.freight_predictions[-5:], 1):
pred_data.append([f"Prediction {i}", f"${pred:,.2f}"])
table = Table(pred_data)
table.setStyle(TableStyle([
('BACKGROUND', (0, 0), (-1, 0), colors.HexColor('#3498DB')),
('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke),
('ALIGN', (0, 0), (-1, -1), 'CENTER'),
('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),
('FONTSIZE', (0, 0), (-1, 0), 14),
('BOTTOMPADDING', (0, 0), (-1, 0), 12),
('BACKGROUND', (0, 1), (-1, -1), colors.whitesmoke),
('TEXTCOLOR', (0, 1), (-1, -1), colors.black),
('FONTNAME', (0, 1), (-1, -1), 'Helvetica'),
('FONTSIZE', (0, 1), (-1, -1), 12),
('GRID', (0, 0), (-1, -1), 1, colors.black)
]))
story.append(table)
story.append(Spacer(1, 20))
# Build PDF
doc.build(story)
return pdf_path
except Exception as e:
print(f"Error generating PDF: {str(e)}")
return None
def run_analyses(state, choices, sales_file, supplier_file, text_data):
"""Run selected analyses"""
results = []
figures = []
status_messages = []
# Process data first
process_status = process_uploaded_data(state, sales_file, supplier_file, text_data)
if "Error" in process_status:
return process_status, None, process_status
for choice in choices:
if "Demand Forecasting" in choice:
text, fig, status = perform_demand_forecasting(state)
results.append(text)
figures.append(fig)
status_messages.append(status)
if text and fig:
state.analysis_results['Demand Forecasting'] = {'text': text, 'figure': fig}
elif "Risk Assessment" in choice:
text, fig, status = perform_risk_assessment(state)
results.append(text)
figures.append(fig)
status_messages.append(status)
if text and fig:
state.analysis_results['Risk Assessment'] = {'text': text, 'figure': fig}
combined_results = "\n\n".join(results)
combined_status = "\n".join(status_messages)
final_figure = figures[-1] if figures else None
return combined_results, final_figure, combined_status
def predict_and_store_freight(state, *args):
"""Predict freight cost and store the result"""
result = predict_freight_cost(state, *args)
if isinstance(result, (int, float)):
state.freight_predictions.append(result)
return result
def create_interface():
"""Create Gradio interface with enhanced UI"""
state = SupplyChainState()
with gr.Blocks(css=CUSTOM_CSS, title="SupplyChainAI Navigator") as demo:
# Header
with gr.Row(elem_classes="main-header"):
with gr.Column():
gr.Markdown("# π’ SupplyChainAI Navigator", elem_classes="app-title")
gr.Markdown("### Intelligent Supply Chain Analysis & Optimization", elem_classes="app-subtitle")
gr.Markdown("An AI-powered platform for comprehensive supply chain analytics", elem_classes="app-description")
gr.Markdown("Created by Aditya Ratan", elem_classes="creator-info")
# Main Content Tabs
with gr.Tabs() as tabs:
# Data Upload Tab
with gr.Tab("π Data Upload", elem_classes="tab-content"):
with gr.Row():
with gr.Column(scale=1):
sales_data_upload = gr.File(
file_types=[".csv"],
label="π Sales Data (CSV)",
elem_classes="file-upload"
)
with gr.Column(scale=1):
supplier_data_upload = gr.File(
file_types=[".xlsx", ".xls"],
label="π Supplier Data (Excel)",
elem_classes="file-upload"
)
text_input_area = gr.Textbox(
label="π Additional Context",
placeholder="Add market updates, news, or other relevant information...",
lines=5
)
with gr.Row():
upload_status = gr.Textbox(
label="Status",
elem_classes="status-box"
)
upload_button = gr.Button(
"π Process Data",
variant="primary",
elem_classes="action-button"
)
# Analysis Tab
with gr.Tab("π Analysis", elem_classes="tab-content"):
analysis_options = gr.CheckboxGroup(
choices=[
"π Demand Forecasting",
"β οΈ Risk Assessment"
],
label="Choose analyses to perform"
)
analyze_button = gr.Button(
"π Run Analysis",
variant="primary",
elem_classes="action-button"
)
with gr.Row():
with gr.Column(scale=2):
analysis_output = gr.Textbox(
label="Analysis Results",
elem_classes="result-box"
)
with gr.Column(scale=3):
plot_output = gr.Plot(
label="Visualization",
elem_classes="chart-container"
)
raw_output = gr.Textbox(
label="Processing Status",
elem_classes="status-box"
)
# Freight Cost Prediction Tab
with gr.Tab("π° Cost Prediction", elem_classes="tab-content"):
with gr.Row():
shipment_mode = gr.Dropdown(
choices=["βοΈ Air", "π’ Ocean", "π Truck"],
label="Transport Mode",
value="βοΈ Air"
)
with gr.Row():
with gr.Column():
weight = gr.Slider(
label="π¦ Weight (kg)",
minimum=1,
maximum=10000,
step=1,
value=1000
)
with gr.Column():
line_item_value = gr.Slider(
label="π΅ Item Value (USD)",
minimum=1,
maximum=1000000,
step=1,
value=10000
)
with gr.Column():
cost_per_kg = gr.Slider(
label="π° Cost per kg (USD)",
minimum=0,
maximum=500,
step=0.1,
value=50
)
# Mode-specific inputs
with gr.Row(visible=False) as air_inputs:
air_charter_weight = gr.Slider(
label="Air Charter Weight",
minimum=0,
maximum=10000
)
air_charter_value = gr.Slider(
label="Air Charter Value",
minimum=0,
maximum=1000000
)
with gr.Row(visible=False) as ocean_inputs:
ocean_weight = gr.Slider(
label="Ocean Weight",
minimum=0,
maximum=10000
)
ocean_value = gr.Slider(
label="Ocean Value",
minimum=0,
maximum=1000000
)
with gr.Row(visible=False) as truck_inputs:
truck_weight = gr.Slider(
label="Truck Weight",
minimum=0,
maximum=10000
)
truck_value = gr.Slider(
label="Truck Value",
minimum=0,
maximum=1000000
)
with gr.Row():
predict_button = gr.Button(
"π Calculate Cost",
variant="primary",
elem_classes="action-button"
)
freight_result = gr.Number(
label="Predicted Cost (USD)",
elem_classes="result-box"
)
# Chat Tab
with gr.Tab("π¬ Chat", elem_classes="tab-content"):
chatbot = gr.Chatbot(
label="Chat History",
elem_classes="chat-container",
height=400
)
with gr.Row():
msg = gr.Textbox(
label="Message",
placeholder="Ask about your supply chain data...",
scale=4
)
chat_button = gr.Button(
"π€ Send",
variant="primary",
scale=1,
elem_classes="action-button"
)
# Report Tab
with gr.Tab("π Report", elem_classes="tab-content"):
report_button = gr.Button(
"π Generate Report",
variant="primary",
elem_classes="action-button"
)
report_download = gr.File(
label="Download Report"
)
# Footer
with gr.Row(elem_classes="footer"):
gr.Markdown("Β© 2025 SupplyChainAI Navigator")
# Event Handlers
def update_mode_inputs(mode):
return {
air_inputs: gr.update(visible=mode=="βοΈ Air"),
ocean_inputs: gr.update(visible=mode=="π’ Ocean"),
truck_inputs: gr.update(visible=mode=="π Truck")
}
# Connect all components
upload_button.click(
fn=lambda *args: process_uploaded_data(state, *args),
inputs=[sales_data_upload, supplier_data_upload, text_input_area],
outputs=[upload_status]
)
analyze_button.click(
fn=lambda *args: run_analyses(state, *args),
inputs=[analysis_options, sales_data_upload, supplier_data_upload, text_input_area],
outputs=[analysis_output, plot_output, raw_output]
)
shipment_mode.change(
fn=update_mode_inputs,
inputs=[shipment_mode],
outputs=[air_inputs, ocean_inputs, truck_inputs]
)
predict_button.click(
fn=lambda *args: predict_and_store_freight(state, *args),
inputs=[
weight, line_item_value, cost_per_kg,
shipment_mode, air_charter_weight, ocean_weight, truck_weight,
air_charter_value, ocean_value, truck_value
],
outputs=[freight_result]
)
chat_button.click(
fn=lambda message: chat_with_navigator(state, message),
inputs=[msg],
outputs=[chatbot]
).then(
fn=lambda: "",
outputs=[msg]
)
report_button.click(
fn=lambda options: generate_pdf_report(state, options),
inputs=[analysis_options],
outputs=[report_download]
)
return demo
if __name__ == "__main__":
demo = create_interface()
demo.launch(
share=True,
debug=True
)
# Enhanced title |