AdityaRatan commited on
Commit
a152ed7
Β·
verified Β·
1 Parent(s): 43149ec

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +217 -3
app.py CHANGED
@@ -327,6 +327,191 @@ def perform_risk_assessment(state):
327
  except Exception as e:
328
  return f"❌ Error in risk assessment: {str(e)}", None, "Assessment failed"
329
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
330
  def predict_freight_cost(state, weight, line_item_value, cost_per_kg,
331
  shipment_mode, air_charter_weight, ocean_weight, truck_weight,
332
  air_charter_value, ocean_value, truck_value):
@@ -475,12 +660,13 @@ def run_analyses(state, choices, sales_file, supplier_file, text_data):
475
  figures = []
476
  status_messages = []
477
 
 
478
  process_status = process_uploaded_data(state, sales_file, supplier_file, text_data)
479
  if "Error" in process_status:
480
  return process_status, None, process_status
481
 
482
  for choice in choices:
483
- if "Demand Forecasting" in choice:
484
  text, fig, status = perform_demand_forecasting(state)
485
  results.append(text)
486
  figures.append(fig)
@@ -488,16 +674,41 @@ def run_analyses(state, choices, sales_file, supplier_file, text_data):
488
  if text and fig:
489
  state.analysis_results['Demand Forecasting'] = {'text': text, 'figure': fig}
490
 
491
- elif "Risk Assessment" in choice:
492
  text, fig, status = perform_risk_assessment(state)
493
  results.append(text)
494
  figures.append(fig)
495
  status_messages.append(status)
496
  if text and fig:
497
  state.analysis_results['Risk Assessment'] = {'text': text, 'figure': fig}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
498
 
499
  combined_results = "\n\n".join(results)
500
  combined_status = "\n".join(status_messages)
 
501
  final_figure = figures[-1] if figures else None
502
 
503
  return combined_results, final_figure, combined_status
@@ -562,7 +773,10 @@ def create_interface():
562
  analysis_options = gr.CheckboxGroup(
563
  choices=[
564
  "πŸ“ˆ Demand Forecasting",
565
- "⚠️ Risk Assessment"
 
 
 
566
  ],
567
  label="Choose analyses to perform"
568
  )
 
327
  except Exception as e:
328
  return f"❌ Error in risk assessment: {str(e)}", None, "Assessment failed"
329
 
330
+
331
+ def perform_inventory_optimization(state):
332
+ """Perform inventory optimization analysis"""
333
+ if state.sales_df is None:
334
+ return "Error: No sales data provided", None, "Please upload sales data first"
335
+
336
+ if model is None:
337
+ return "AI features are currently disabled. Please check your API key configuration.", None, "AI Disabled"
338
+
339
+ try:
340
+ inventory_summary = state.sales_df.describe().to_string()
341
+ prompt = f"""Analyze the following inventory data and provide:
342
+ 1. Optimal inventory levels
343
+ 2. Reorder points
344
+ 3. Safety stock recommendations
345
+ 4. ABC analysis insights
346
+
347
+ Data Summary:
348
+ {inventory_summary}
349
+
350
+ Additional Context:
351
+ {state.text_data if state.text_data else 'No additional context provided'}
352
+
353
+ Please structure your response with clear sections for each aspect."""
354
+
355
+ response = model.generate_content(prompt)
356
+ analysis_text = response.text
357
+
358
+ # Create inventory level visualization
359
+ fig = go.Figure()
360
+
361
+ if 'quantity' in state.sales_df.columns:
362
+ fig.add_trace(go.Scatter(
363
+ y=state.sales_df['quantity'],
364
+ name='Inventory Level',
365
+ line=dict(color='#3498DB')
366
+ ))
367
+
368
+ fig.update_layout(
369
+ title='Inventory Level Analysis',
370
+ template='plotly_dark',
371
+ title_x=0.5,
372
+ title_font_size=20,
373
+ showlegend=True,
374
+ hovermode='x',
375
+ paper_bgcolor='#2d2d2d',
376
+ plot_bgcolor='#363636',
377
+ font=dict(color='white')
378
+ )
379
+
380
+ return analysis_text, fig, "βœ… Inventory optimization completed"
381
+ except Exception as e:
382
+ return f"❌ Error in inventory optimization: {str(e)}", None, "Analysis failed"
383
+
384
+ def perform_supplier_performance(state):
385
+ """Analyze supplier performance"""
386
+ if state.supplier_df is None:
387
+ return "Error: No supplier data provided", None, "Please upload supplier data first"
388
+
389
+ if model is None:
390
+ return "AI features are currently disabled. Please check your API key configuration.", None, "AI Disabled"
391
+
392
+ try:
393
+ supplier_summary = state.supplier_df.describe().to_string()
394
+ prompt = f"""Analyze supplier performance based on:
395
+
396
+ Supplier Data Summary:
397
+ {supplier_summary}
398
+
399
+ Additional Context:
400
+ {state.text_data if state.text_data else 'No additional context provided'}
401
+
402
+ Please provide:
403
+ 1. Supplier performance metrics
404
+ 2. Performance rankings
405
+ 3. Areas for improvement
406
+ 4. Supplier development recommendations"""
407
+
408
+ response = model.generate_content(prompt)
409
+ analysis_text = response.text
410
+
411
+ # Create supplier performance visualization
412
+ if 'performance_score' in state.supplier_df.columns:
413
+ fig = px.box(state.supplier_df, y='performance_score',
414
+ title='Supplier Performance Distribution')
415
+ else:
416
+ # Create a sample visualization if performance_score is not available
417
+ fig = go.Figure(data=[
418
+ go.Bar(name='On-Time Delivery', x=['Supplier A', 'Supplier B', 'Supplier C'],
419
+ y=[95, 87, 92]),
420
+ go.Bar(name='Quality Score', x=['Supplier A', 'Supplier B', 'Supplier C'],
421
+ y=[88, 94, 90])
422
+ ])
423
+
424
+ fig.update_layout(
425
+ template='plotly_dark',
426
+ title_x=0.5,
427
+ title_font_size=20,
428
+ showlegend=True,
429
+ paper_bgcolor='#2d2d2d',
430
+ plot_bgcolor='#363636',
431
+ font=dict(color='white')
432
+ )
433
+
434
+ return analysis_text, fig, "βœ… Supplier performance analysis completed"
435
+ except Exception as e:
436
+ return f"❌ Error in supplier performance analysis: {str(e)}", None, "Analysis failed"
437
+
438
+ def perform_sustainability_analysis(state):
439
+ """Analyze sustainability metrics"""
440
+ if state.supplier_df is None and state.sales_df is None:
441
+ return "Error: No data provided", None, "Please upload data first"
442
+
443
+ if model is None:
444
+ return "AI features are currently disabled. Please check your API key configuration.", None, "AI Disabled"
445
+
446
+ try:
447
+ # Combine available data for analysis
448
+ data_summary = ""
449
+ if state.supplier_df is not None:
450
+ data_summary += f"Supplier Data Summary:\n{state.supplier_df.describe().to_string()}\n\n"
451
+ if state.sales_df is not None:
452
+ data_summary += f"Sales Data Summary:\n{state.sales_df.describe().to_string()}"
453
+
454
+ prompt = f"""Perform a comprehensive sustainability analysis:
455
+
456
+ Data Summary:
457
+ {data_summary}
458
+
459
+ Additional Context:
460
+ {state.text_data if state.text_data else 'No additional context provided'}
461
+
462
+ Please provide:
463
+ 1. Carbon footprint analysis
464
+ 2. Environmental impact metrics
465
+ 3. Sustainability recommendations
466
+ 4. Green initiative opportunities
467
+ 5. ESG performance indicators"""
468
+
469
+ response = model.generate_content(prompt)
470
+ analysis_text = response.text
471
+
472
+ # Create sustainability visualization
473
+ fig = go.Figure()
474
+
475
+ # Example sustainability metrics
476
+ categories = ['Carbon Emissions', 'Water Usage', 'Waste Reduction',
477
+ 'Energy Efficiency', 'Green Transportation']
478
+ current_scores = [75, 82, 68, 90, 60]
479
+ target_scores = [100, 100, 100, 100, 100]
480
+
481
+ fig.add_trace(go.Scatterpolar(
482
+ r=current_scores,
483
+ theta=categories,
484
+ fill='toself',
485
+ name='Current Performance'
486
+ ))
487
+ fig.add_trace(go.Scatterpolar(
488
+ r=target_scores,
489
+ theta=categories,
490
+ fill='toself',
491
+ name='Target'
492
+ ))
493
+
494
+ fig.update_layout(
495
+ polar=dict(
496
+ radialaxis=dict(
497
+ visible=True,
498
+ range=[0, 100]
499
+ )),
500
+ showlegend=True,
501
+ title='Sustainability Performance Metrics',
502
+ template='plotly_dark',
503
+ title_x=0.5,
504
+ title_font_size=20,
505
+ paper_bgcolor='#2d2d2d',
506
+ plot_bgcolor='#363636',
507
+ font=dict(color='white')
508
+ )
509
+
510
+ return analysis_text, fig, "βœ… Sustainability analysis completed"
511
+ except Exception as e:
512
+ return f"❌ Error in sustainability analysis: {str(e)}", None, "Analysis failed"
513
+
514
+
515
  def predict_freight_cost(state, weight, line_item_value, cost_per_kg,
516
  shipment_mode, air_charter_weight, ocean_weight, truck_weight,
517
  air_charter_value, ocean_value, truck_value):
 
660
  figures = []
661
  status_messages = []
662
 
663
+ # Process data first
664
  process_status = process_uploaded_data(state, sales_file, supplier_file, text_data)
665
  if "Error" in process_status:
666
  return process_status, None, process_status
667
 
668
  for choice in choices:
669
+ if "πŸ“ˆ Demand Forecasting" in choice:
670
  text, fig, status = perform_demand_forecasting(state)
671
  results.append(text)
672
  figures.append(fig)
 
674
  if text and fig:
675
  state.analysis_results['Demand Forecasting'] = {'text': text, 'figure': fig}
676
 
677
+ elif "⚠️ Risk Assessment" in choice:
678
  text, fig, status = perform_risk_assessment(state)
679
  results.append(text)
680
  figures.append(fig)
681
  status_messages.append(status)
682
  if text and fig:
683
  state.analysis_results['Risk Assessment'] = {'text': text, 'figure': fig}
684
+
685
+ elif "πŸ“¦ Inventory Optimization" in choice:
686
+ text, fig, status = perform_inventory_optimization(state)
687
+ results.append(text)
688
+ figures.append(fig)
689
+ status_messages.append(status)
690
+ if text and fig:
691
+ state.analysis_results['Inventory Optimization'] = {'text': text, 'figure': fig}
692
+
693
+ elif "🀝 Supplier Performance" in choice:
694
+ text, fig, status = perform_supplier_performance(state)
695
+ results.append(text)
696
+ figures.append(fig)
697
+ status_messages.append(status)
698
+ if text and fig:
699
+ state.analysis_results['Supplier Performance'] = {'text': text, 'figure': fig}
700
+
701
+ elif "🌿 Sustainability Analysis" in choice:
702
+ text, fig, status = perform_sustainability_analysis(state)
703
+ results.append(text)
704
+ figures.append(fig)
705
+ status_messages.append(status)
706
+ if text and fig:
707
+ state.analysis_results['Sustainability Analysis'] = {'text': text, 'figure': fig}
708
 
709
  combined_results = "\n\n".join(results)
710
  combined_status = "\n".join(status_messages)
711
+
712
  final_figure = figures[-1] if figures else None
713
 
714
  return combined_results, final_figure, combined_status
 
773
  analysis_options = gr.CheckboxGroup(
774
  choices=[
775
  "πŸ“ˆ Demand Forecasting",
776
+ "⚠️ Risk Assessment",
777
+ "πŸ“¦ Inventory Optimization",
778
+ "🀝 Supplier Performance",
779
+ "🌿 Sustainability Analysis"
780
  ],
781
  label="Choose analyses to perform"
782
  )