File size: 5,342 Bytes
1eaee2c ed54481 1eaee2c 3cf1d45 5c3e455 a803465 3cf1d45 5c3e455 3cf1d45 5c3e455 1eaee2c a803465 1eaee2c a803465 3cf1d45 a803465 3cf1d45 a803465 3cf1d45 a803465 3cf1d45 a803465 3cf1d45 a803465 3cf1d45 a803465 3cf1d45 a803465 3cf1d45 1eaee2c 3cf1d45 a803465 3cf1d45 a803465 3cf1d45 a803465 3cf1d45 a803465 3cf1d45 a803465 3cf1d45 a803465 3cf1d45 a803465 3cf1d45 | 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 | import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent))
import chainlit as cl
from src.components.model_nlp_intent import predict_intent
from src.components.model_nlp_ner import extract_entities_pipeline
from src.components.model_risk_predictor import predict_risk
from src.components.recommendation_engine import generate_recommendation
@cl.on_chat_start
async def welcome():
welcome_msg = cl.Message(
content=(
"# π Welcome to AI-Powered Supply Chain Risk Advisor\n\n"
"I provide **real-time risk analysis** and **mitigation strategies** "
"based on:\n"
"- π **Regional factors** (port congestion, infrastructure)\n"
"- β οΈ **Active events** (strikes, typhoons, disruptions)\n"
"- π’ **Route analysis** (origin to destination)\n"
"- π€ **ML-powered predictions** (trained on historical data)\n\n"
"### π¬ Example Questions:\n\n"
"- \"Is there any delay in vessels from USA to UAE?\"\n"
"- \"What should I do about the port strike in Shanghai?\"\n"
"- \"Are there weather problems affecting shipments to Germany?\"\n"
"- \"Risk level for Mumbai to Singapore route?\"\n\n"
"**Ask me anything about your supply chain risks!** π"
)
)
await welcome_msg.send()
@cl.on_message
async def handle_message(msg: cl.Message):
query = msg.content
loading_msg = cl.Message(content="π Analyzing your query...")
await loading_msg.send()
try:
intent_result = predict_intent(query)
intent = intent_result["intent"]
confidence = intent_result["confidence"]
entities = extract_entities_pipeline(query)
region = None
origin = None
destination = None
if entities.get("location"):
locations = entities["location"]
if isinstance(locations, list) and len(locations) > 0:
region = locations[0]
if len(locations) > 1:
origin = locations[0]
destination = locations[1]
else:
region = locations
if not region:
region = "Mumbai"
incidents = []
event_type = None
if entities.get("event"):
events = entities["event"]
if isinstance(events, list):
incidents = events
event_type = events[0] if events else None
else:
incidents = [events]
event_type = events
risk_score = predict_risk(
region=region,
days=5,
origin=origin,
destination=destination,
event_type=event_type,
incidents=incidents
)
recent_incidents = incidents if incidents else ["port strike", "supplier outage"]
weather_alert = "Typhoon warning" if region.lower() == "shanghai" else None
advice = generate_recommendation(
risk_score=risk_score,
region=region,
recent_incidents=recent_incidents,
weather_alert=weather_alert,
intent=intent
)
if risk_score >= 0.7:
risk_emoji = "π΄"
risk_level = "High"
elif risk_score >= 0.4:
risk_emoji = "π‘"
risk_level = "Medium"
else:
risk_emoji = "π’"
risk_level = "Low"
response = (
f"### π Supply Chain Risk Analysis\n\n"
f"**Region:** {region}\n"
f"**Intent:** {intent} (Confidence: {confidence:.2%})\n"
f"**Entities:** {entities}\n"
)
if origin and destination:
response += f"**Route:** {origin} β {destination}\n"
if incidents:
response += f"**β οΈ Detected Events:** {', '.join(incidents)}\n"
response += f"**Risk Score:** {risk_emoji} **{risk_level}** ({risk_score:.2f})\n\n"
response += f"**π‘ Recommendation:**\n{advice['message']}\n"
await loading_msg.remove()
await cl.Message(content=response).send()
alert_emoji = "π¨" if risk_score >= 0.7 else "β οΈ" if risk_score >= 0.4 else "β
"
await cl.Message(
content=f"{alert_emoji} **Alert Level:** {advice['action'].upper()}"
).send()
except Exception as e:
print(f"Error processing query: {str(e)}")
import traceback
traceback.print_exc()
try:
await loading_msg.remove()
except:
pass
await cl.Message(
content=(
f"β **Error:** An error occurred while processing your request.\n\n"
f"**Details:** {str(e)}\n\n"
f"Please try:\n"
f"- Rephrasing your question\n"
f"- Being more specific about locations\n"
f"- Asking a different question\n\n"
f"Example: \"What is the risk level for shipments from Mumbai to Singapore?\""
)
).send() |