forked from VikashBasfore/osha_ai_app
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenai_helper.py
More file actions
75 lines (55 loc) · 2.19 KB
/
Copy pathgenai_helper.py
File metadata and controls
75 lines (55 loc) · 2.19 KB
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
import google.generativeai as genai
import os
from dotenv import load_dotenv
import time
# Load API key
load_dotenv()
# Configure Gemini
genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
# Create model
model = genai.GenerativeModel("gemini-2.5-flash") # stable model
def explain_prediction(row_data, prediction, confidence):
try:
prompt = f"""
You are a professional workplace safety analyst.
Analyze the following workplace incident and provide a structured explanation.
Give answers in the following sections:
1. Root Cause (4–6 lines)
Explain why the incident happened in detail.
2. Risk Factors (4–6 lines)
Describe the key hazards and unsafe conditions involved.
3. Chances of Recurrence (4–6 lines)
Explain how likely this incident is to happen again and why.
4. Prevention & Solutions (4–6 lines)
Explain what actions the company should take to prevent this.
5. Worker Treatment (4–6 lines)
Explain what medical treatment the injured worker should receive.
6. Long-term Safety Measures (4–6 lines)
Explain what improvements should be made to avoid future incidents.
Incident details:
{row_data}
Prediction: {prediction}
Confidence: {confidence}
Instructions:
- Write each section clearly with its heading
- Each section must have 4–6 lines
- Use simple professional language
- Highlight key terms using **bold**
- Do NOT use HTML
- Keep it structured and readable
"""
# Retry logic
for attempt in range(5):
try:
response = model.generate_content(prompt)
return response.text.strip()
except Exception as e:
if "503" in str(e):
time.sleep(5)
elif "429" in str(e):
return "🚫 Daily AI limit reached. Please try again tomorrow."
else:
return f"AI Error: {str(e)}"
return "⚠ AI is busy. Please try again in a few seconds."
except Exception as e:
return f"AI Error: {str(e)}"