Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -9,19 +9,28 @@ import os
|
|
| 9 |
from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
|
| 10 |
from peft import PeftModel
|
| 11 |
|
| 12 |
-
# Configuration
|
| 13 |
MODEL_PATHS = [
|
| 14 |
"FrAnKu34t23/Construction_Risk_Prediction_Model_v3"
|
| 15 |
]
|
| 16 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
|
| 18 |
models = []
|
| 19 |
tokenizers = []
|
| 20 |
|
| 21 |
-
# Initialize
|
| 22 |
injury_classifier = pipeline("zero-shot-classification", model="facebook/bart-large-mnli")
|
| 23 |
-
|
| 24 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
|
| 26 |
def classify_injury_zero_shot(description):
|
| 27 |
candidate_labels = [
|
|
@@ -54,41 +63,6 @@ def load_models():
|
|
| 54 |
print(f"β Model loading failed: {e}")
|
| 55 |
return False
|
| 56 |
|
| 57 |
-
def parse_input(input_text):
|
| 58 |
-
"""Parse input - can be plain text or JSON"""
|
| 59 |
-
try:
|
| 60 |
-
# Try to parse as JSON first
|
| 61 |
-
data = json.loads(input_text)
|
| 62 |
-
if isinstance(data, dict):
|
| 63 |
-
# Extract relevant fields from JSON
|
| 64 |
-
scenario = ""
|
| 65 |
-
if "scenario" in data:
|
| 66 |
-
scenario = data["scenario"]
|
| 67 |
-
elif "description" in data:
|
| 68 |
-
scenario = data["description"]
|
| 69 |
-
elif "text" in data:
|
| 70 |
-
scenario = data["text"]
|
| 71 |
-
else:
|
| 72 |
-
# If no obvious field, concatenate all string values
|
| 73 |
-
scenario = " ".join([str(v) for v in data.values() if isinstance(v, str)])
|
| 74 |
-
|
| 75 |
-
# Add additional context if available
|
| 76 |
-
context_fields = ["location", "equipment", "workers", "conditions", "environment"]
|
| 77 |
-
context = []
|
| 78 |
-
for field in context_fields:
|
| 79 |
-
if field in data and data[field]:
|
| 80 |
-
context.append(f"{field}: {data[field]}")
|
| 81 |
-
|
| 82 |
-
if context:
|
| 83 |
-
scenario += " Additional context: " + ", ".join(context)
|
| 84 |
-
|
| 85 |
-
return scenario.strip(), data
|
| 86 |
-
else:
|
| 87 |
-
return str(data), {"raw_input": str(data)}
|
| 88 |
-
except json.JSONDecodeError:
|
| 89 |
-
# If not JSON, treat as plain text
|
| 90 |
-
return input_text.strip(), {"scenario": input_text.strip()}
|
| 91 |
-
|
| 92 |
def format_input(scenario_text):
|
| 93 |
scenario = scenario_text.strip()
|
| 94 |
if not scenario.startswith(", "):
|
|
@@ -123,74 +97,134 @@ def extract_scenario_from_prompt(prompt):
|
|
| 123 |
except:
|
| 124 |
return prompt
|
| 125 |
|
| 126 |
-
def
|
| 127 |
-
"""
|
| 128 |
try:
|
| 129 |
-
#
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 144 |
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
# Extract the generated part after the prompt
|
| 149 |
-
cause = cause_text.replace(cause_prompt, "").strip()
|
| 150 |
-
if not cause:
|
| 151 |
-
cause = "Unable to determine specific cause from the analysis"
|
| 152 |
-
except:
|
| 153 |
-
cause = "Analysis indicates multiple contributing factors to the workplace incident"
|
| 154 |
|
| 155 |
-
#
|
| 156 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 157 |
|
| 158 |
-
return
|
| 159 |
|
| 160 |
except Exception as e:
|
| 161 |
-
print("β HF model analysis failed:", e)
|
| 162 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 163 |
|
| 164 |
-
def generate_prediction_ensemble(
|
| 165 |
-
if not
|
| 166 |
return "β Please enter a scenario.", "", "", ""
|
| 167 |
|
| 168 |
try:
|
| 169 |
-
# Parse input (JSON or plain text)
|
| 170 |
-
scenario_text, parsed_data = parse_input(input_text)
|
| 171 |
-
|
| 172 |
-
if not scenario_text:
|
| 173 |
-
return "β No valid scenario found in input.", "", "", json.dumps(parsed_data, indent=2)
|
| 174 |
-
|
| 175 |
prompt = format_input(scenario_text)
|
| 176 |
raw_outputs = generate_all_model_outputs(prompt, max_length, temperature)
|
| 177 |
|
| 178 |
scenario_only = extract_scenario_from_prompt(prompt)
|
| 179 |
injury_guess = classify_injury_zero_shot(scenario_only)
|
| 180 |
|
| 181 |
-
#
|
| 182 |
-
|
|
|
|
|
|
|
|
|
|
| 183 |
|
| 184 |
-
|
| 185 |
-
|
|
|
|
| 186 |
|
| 187 |
cause = match_cause.group(1).strip() if match_cause else "Unable to determine cause"
|
| 188 |
injury = match_injury.group(1).strip().capitalize() if match_injury else injury_guess
|
| 189 |
|
| 190 |
combined_raw = "\n\n".join(raw_outputs)
|
| 191 |
-
parsed_json = json.dumps(parsed_data, indent=2)
|
| 192 |
|
| 193 |
-
|
|
|
|
|
|
|
|
|
|
| 194 |
|
| 195 |
except Exception as e:
|
| 196 |
return "β Prediction failed.", "", traceback.format_exc(), ""
|
|
@@ -198,25 +232,27 @@ def generate_prediction_ensemble(input_text, max_length=300, temperature=0.7):
|
|
| 198 |
def create_interface():
|
| 199 |
with gr.Blocks(title="Workplace Safety Risk Predictor") as interface:
|
| 200 |
gr.HTML("""
|
| 201 |
-
<h1>π§ Workplace Safety Risk Prediction Model (Ensemble)</h1>
|
| 202 |
-
<p>Enter a construction scenario to analyze possible risks.
|
| 203 |
-
<p><strong>
|
|
|
|
|
|
|
| 204 |
<ul>
|
| 205 |
<li>An employee was working with chemical solvents without proper ventilation. The employee inhaled toxic fumes and experienced respiratory problems.</li>
|
| 206 |
<li>A worker fell from scaffolding due to lack of fall protection measures in place.</li>
|
|
|
|
|
|
|
| 207 |
</ul>
|
| 208 |
-
<p><strong>JSON Example:</strong></p>
|
| 209 |
-
<pre>{"scenario": "Worker fell from height", "location": "Construction site", "equipment": "Scaffolding", "conditions": "No safety harness"}</pre>
|
| 210 |
""")
|
| 211 |
|
| 212 |
with gr.Row():
|
| 213 |
with gr.Column():
|
| 214 |
-
scenario_input = gr.Textbox(lines=
|
| 215 |
gr.Markdown("**Quick Examples:**")
|
| 216 |
with gr.Row():
|
| 217 |
ex1 = gr.Button("Solvent Exposure")
|
| 218 |
ex2 = gr.Button("Fall from Scaffolding")
|
| 219 |
-
ex3 = gr.Button("
|
| 220 |
ex4 = gr.Button("Welding Fire Hazard")
|
| 221 |
temperature = gr.Slider(0.1, 1.0, 0.7, 0.1, label="Creativity (Temperature)")
|
| 222 |
max_len = gr.Slider(100, 500, 300, 50, label="Max Response Length")
|
|
@@ -225,24 +261,23 @@ def create_interface():
|
|
| 225 |
with gr.Column():
|
| 226 |
cause_output = gr.Textbox(label="π Cause of Accident")
|
| 227 |
degree_output = gr.Textbox(label="π Degree of Injury")
|
| 228 |
-
with gr.Accordion("π
|
| 229 |
-
|
| 230 |
with gr.Accordion("π Raw Model Outputs", open=False):
|
| 231 |
raw_output = gr.Textbox(label="Raw Responses", lines=12)
|
| 232 |
|
| 233 |
predict_btn.click(
|
| 234 |
fn=generate_prediction_ensemble,
|
| 235 |
inputs=[scenario_input, max_len, temperature],
|
| 236 |
-
outputs=[cause_output, degree_output, raw_output,
|
| 237 |
)
|
| 238 |
|
| 239 |
-
# Example functions
|
| 240 |
ex1.click(fn=lambda: "An employee was working with chemical solvents without proper ventilation. The employee inhaled toxic fumes and experienced respiratory problems.", outputs=scenario_input)
|
| 241 |
ex2.click(fn=lambda: "A worker fell from scaffolding due to lack of fall protection measures in place.", outputs=scenario_input)
|
| 242 |
-
ex3.click(fn=lambda:
|
| 243 |
ex4.click(fn=lambda: "During welding, flammable vapors ignited due to poor fire safety practices.", outputs=scenario_input)
|
| 244 |
|
| 245 |
-
gr.HTML("<p style='text-align:center;'>Built with Transformers +
|
| 246 |
|
| 247 |
return interface
|
| 248 |
|
|
|
|
| 9 |
from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
|
| 10 |
from peft import PeftModel
|
| 11 |
|
| 12 |
+
# Configuration - Using better base models
|
| 13 |
MODEL_PATHS = [
|
| 14 |
"FrAnKu34t23/Construction_Risk_Prediction_Model_v3"
|
| 15 |
]
|
| 16 |
+
# Better base model options - choose one based on your needs
|
| 17 |
+
BASE_MODEL_ID = "microsoft/DialoGPT-medium" # Better conversational model
|
| 18 |
+
# Alternative options:
|
| 19 |
+
# BASE_MODEL_ID = "gpt2-medium" # Larger GPT-2
|
| 20 |
+
# BASE_MODEL_ID = "microsoft/DialoGPT-large" # Even better but slower
|
| 21 |
|
| 22 |
models = []
|
| 23 |
tokenizers = []
|
| 24 |
|
| 25 |
+
# Initialize better models for analysis
|
| 26 |
injury_classifier = pipeline("zero-shot-classification", model="facebook/bart-large-mnli")
|
| 27 |
+
|
| 28 |
+
# Use a more capable model for text analysis and reasoning
|
| 29 |
+
analysis_model = pipeline(
|
| 30 |
+
"text-generation",
|
| 31 |
+
model="microsoft/DialoGPT-large", # Better reasoning capabilities
|
| 32 |
+
device=0 if torch.cuda.is_available() else -1
|
| 33 |
+
)
|
| 34 |
|
| 35 |
def classify_injury_zero_shot(description):
|
| 36 |
candidate_labels = [
|
|
|
|
| 63 |
print(f"β Model loading failed: {e}")
|
| 64 |
return False
|
| 65 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
def format_input(scenario_text):
|
| 67 |
scenario = scenario_text.strip()
|
| 68 |
if not scenario.startswith(", "):
|
|
|
|
| 97 |
except:
|
| 98 |
return prompt
|
| 99 |
|
| 100 |
+
def parse_json_from_raw_output(raw_output):
|
| 101 |
+
"""Extract JSON from raw model output"""
|
| 102 |
try:
|
| 103 |
+
# Look for JSON pattern in the raw output
|
| 104 |
+
json_match = re.search(r'\{.*?\}', raw_output, re.DOTALL)
|
| 105 |
+
if json_match:
|
| 106 |
+
json_str = json_match.group(0)
|
| 107 |
+
return json.loads(json_str)
|
| 108 |
+
return None
|
| 109 |
+
except:
|
| 110 |
+
return None
|
| 111 |
+
|
| 112 |
+
def extract_structured_data_from_outputs(raw_outputs):
|
| 113 |
+
"""Extract and combine structured JSON data from all model outputs"""
|
| 114 |
+
all_json_data = []
|
| 115 |
+
|
| 116 |
+
for output in raw_outputs:
|
| 117 |
+
json_data = parse_json_from_raw_output(output)
|
| 118 |
+
if json_data:
|
| 119 |
+
all_json_data.append(json_data)
|
| 120 |
+
|
| 121 |
+
return all_json_data
|
| 122 |
+
|
| 123 |
+
def analyze_with_advanced_hf_model(raw_outputs, zero_shot_injury, structured_data):
|
| 124 |
+
"""Replace Gemini Pro functionality with advanced HF model analysis"""
|
| 125 |
+
|
| 126 |
+
# Prepare the analysis prompt similar to original Gemini prompt
|
| 127 |
+
structured_info = ""
|
| 128 |
+
if structured_data:
|
| 129 |
+
structured_info = "\n\nStructured data extracted from models:\n"
|
| 130 |
+
for i, data in enumerate(structured_data, 1):
|
| 131 |
+
structured_info += f"Model {i}: {json.dumps(data, indent=2)}\n"
|
| 132 |
+
|
| 133 |
+
prompt = f"""You are a workplace safety analyst. Below are raw text outputs from construction safety prediction models.
|
| 134 |
+
|
| 135 |
+
Your tasks:
|
| 136 |
+
- Compare and merge the model outputs
|
| 137 |
+
- Summarize the most plausible cause of accident in natural language
|
| 138 |
+
- Infer the degree of injury by considering all outputs and classifier suggestion
|
| 139 |
+
|
| 140 |
+
Classifier prediction for Degree of Injury: {zero_shot_injury}
|
| 141 |
+
|
| 142 |
+
Model Outputs:
|
| 143 |
+
{raw_outputs[0]}
|
| 144 |
+
|
| 145 |
+
{raw_outputs[1] if len(raw_outputs) > 1 else ""}
|
| 146 |
+
|
| 147 |
+
{raw_outputs[2] if len(raw_outputs) > 2 else ""}
|
| 148 |
+
|
| 149 |
+
{structured_info}
|
| 150 |
+
|
| 151 |
+
Based on this analysis, provide a concise response in this format:
|
| 152 |
+
Cause of Accident: [single clear sentence]
|
| 153 |
+
Degree of Injury: [Low/Medium/High]
|
| 154 |
+
|
| 155 |
+
Analysis:"""
|
| 156 |
+
|
| 157 |
+
try:
|
| 158 |
+
# Use the analysis model to generate response
|
| 159 |
+
response = analysis_model(
|
| 160 |
+
prompt,
|
| 161 |
+
max_length=len(prompt.split()) + 100,
|
| 162 |
+
temperature=0.3, # Lower temperature for more consistent analysis
|
| 163 |
+
do_sample=True,
|
| 164 |
+
pad_token_id=analysis_model.tokenizer.eos_token_id
|
| 165 |
+
)
|
| 166 |
|
| 167 |
+
generated_text = response[0]['generated_text']
|
| 168 |
+
# Extract only the generated part after the prompt
|
| 169 |
+
analysis_result = generated_text.replace(prompt, "").strip()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 170 |
|
| 171 |
+
# If the analysis doesn't contain the required format, create it
|
| 172 |
+
if "Cause of Accident:" not in analysis_result:
|
| 173 |
+
# Fallback analysis based on structured data
|
| 174 |
+
cause = "Multiple safety protocol violations identified"
|
| 175 |
+
if structured_data:
|
| 176 |
+
causes = []
|
| 177 |
+
for data in structured_data:
|
| 178 |
+
if isinstance(data, dict) and "Cause of Accident" in data:
|
| 179 |
+
causes.append(data["Cause of Accident"])
|
| 180 |
+
if causes:
|
| 181 |
+
cause = causes[0] # Take the first cause found
|
| 182 |
+
|
| 183 |
+
analysis_result = f"Cause of Accident: {cause}\nDegree of Injury: {zero_shot_injury}"
|
| 184 |
|
| 185 |
+
return analysis_result
|
| 186 |
|
| 187 |
except Exception as e:
|
| 188 |
+
print("β Advanced HF model analysis failed:", e)
|
| 189 |
+
# Fallback using structured data if available
|
| 190 |
+
if structured_data and len(structured_data) > 0:
|
| 191 |
+
first_data = structured_data[0]
|
| 192 |
+
cause = first_data.get("Cause of Accident", "Safety protocol violation")
|
| 193 |
+
injury = first_data.get("Degree of Injury", zero_shot_injury)
|
| 194 |
+
return f"Cause of Accident: {cause}\nDegree of Injury: {injury}"
|
| 195 |
+
|
| 196 |
+
return f"Cause of Accident: Unable to analyze due to technical error\nDegree of Injury: {zero_shot_injury}"
|
| 197 |
|
| 198 |
+
def generate_prediction_ensemble(scenario_text, max_length=300, temperature=0.7):
|
| 199 |
+
if not scenario_text.strip():
|
| 200 |
return "β Please enter a scenario.", "", "", ""
|
| 201 |
|
| 202 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 203 |
prompt = format_input(scenario_text)
|
| 204 |
raw_outputs = generate_all_model_outputs(prompt, max_length, temperature)
|
| 205 |
|
| 206 |
scenario_only = extract_scenario_from_prompt(prompt)
|
| 207 |
injury_guess = classify_injury_zero_shot(scenario_only)
|
| 208 |
|
| 209 |
+
# Extract structured JSON data from raw outputs
|
| 210 |
+
structured_data = extract_structured_data_from_outputs(raw_outputs)
|
| 211 |
+
|
| 212 |
+
# Use advanced HF model analysis (replacing Gemini)
|
| 213 |
+
hf_analysis = analyze_with_advanced_hf_model(raw_outputs, injury_guess, structured_data)
|
| 214 |
|
| 215 |
+
# Parse the analysis results
|
| 216 |
+
match_cause = re.search(r"Cause of Accident\s*:\s*(.+)", hf_analysis)
|
| 217 |
+
match_injury = re.search(r"Degree of Injury\s*:\s*(Low|Medium|High)", hf_analysis, re.IGNORECASE)
|
| 218 |
|
| 219 |
cause = match_cause.group(1).strip() if match_cause else "Unable to determine cause"
|
| 220 |
injury = match_injury.group(1).strip().capitalize() if match_injury else injury_guess
|
| 221 |
|
| 222 |
combined_raw = "\n\n".join(raw_outputs)
|
|
|
|
| 223 |
|
| 224 |
+
# Format structured data for display
|
| 225 |
+
structured_display = json.dumps(structured_data, indent=2) if structured_data else "No structured data found"
|
| 226 |
+
|
| 227 |
+
return cause, injury, combined_raw, structured_display
|
| 228 |
|
| 229 |
except Exception as e:
|
| 230 |
return "β Prediction failed.", "", traceback.format_exc(), ""
|
|
|
|
| 232 |
def create_interface():
|
| 233 |
with gr.Blocks(title="Workplace Safety Risk Predictor") as interface:
|
| 234 |
gr.HTML("""
|
| 235 |
+
<h1>π§ Workplace Safety Risk Prediction Model (Enhanced Ensemble)</h1>
|
| 236 |
+
<p>Enter a construction scenario to analyze possible risks. Uses advanced language models for better analysis.</p>
|
| 237 |
+
<p><strong>Expected JSON Output Format:</strong></p>
|
| 238 |
+
<pre>{"Cause of Accident": "...", "Degree of Injury": "High/Medium/Low", "Hazards": ["...", "..."]}</pre>
|
| 239 |
+
<p><strong>Examples:</strong></p>
|
| 240 |
<ul>
|
| 241 |
<li>An employee was working with chemical solvents without proper ventilation. The employee inhaled toxic fumes and experienced respiratory problems.</li>
|
| 242 |
<li>A worker fell from scaffolding due to lack of fall protection measures in place.</li>
|
| 243 |
+
<li>While operating a crane, the load became unstable and struck a nearby worker.</li>
|
| 244 |
+
<li>During welding, flammable vapors ignited due to poor fire safety practices.</li>
|
| 245 |
</ul>
|
|
|
|
|
|
|
| 246 |
""")
|
| 247 |
|
| 248 |
with gr.Row():
|
| 249 |
with gr.Column():
|
| 250 |
+
scenario_input = gr.Textbox(lines=5, label="Scenario Description")
|
| 251 |
gr.Markdown("**Quick Examples:**")
|
| 252 |
with gr.Row():
|
| 253 |
ex1 = gr.Button("Solvent Exposure")
|
| 254 |
ex2 = gr.Button("Fall from Scaffolding")
|
| 255 |
+
ex3 = gr.Button("Crane Load Accident")
|
| 256 |
ex4 = gr.Button("Welding Fire Hazard")
|
| 257 |
temperature = gr.Slider(0.1, 1.0, 0.7, 0.1, label="Creativity (Temperature)")
|
| 258 |
max_len = gr.Slider(100, 500, 300, 50, label="Max Response Length")
|
|
|
|
| 261 |
with gr.Column():
|
| 262 |
cause_output = gr.Textbox(label="π Cause of Accident")
|
| 263 |
degree_output = gr.Textbox(label="π Degree of Injury")
|
| 264 |
+
with gr.Accordion("π Extracted Structured Data", open=False):
|
| 265 |
+
structured_output = gr.Textbox(label="JSON Data from Models", lines=8)
|
| 266 |
with gr.Accordion("π Raw Model Outputs", open=False):
|
| 267 |
raw_output = gr.Textbox(label="Raw Responses", lines=12)
|
| 268 |
|
| 269 |
predict_btn.click(
|
| 270 |
fn=generate_prediction_ensemble,
|
| 271 |
inputs=[scenario_input, max_len, temperature],
|
| 272 |
+
outputs=[cause_output, degree_output, raw_output, structured_output]
|
| 273 |
)
|
| 274 |
|
|
|
|
| 275 |
ex1.click(fn=lambda: "An employee was working with chemical solvents without proper ventilation. The employee inhaled toxic fumes and experienced respiratory problems.", outputs=scenario_input)
|
| 276 |
ex2.click(fn=lambda: "A worker fell from scaffolding due to lack of fall protection measures in place.", outputs=scenario_input)
|
| 277 |
+
ex3.click(fn=lambda: "While operating a crane, the load became unstable and struck a nearby worker.", outputs=scenario_input)
|
| 278 |
ex4.click(fn=lambda: "During welding, flammable vapors ignited due to poor fire safety practices.", outputs=scenario_input)
|
| 279 |
|
| 280 |
+
gr.HTML("<p style='text-align:center;'>Built with Advanced Transformers + Enhanced Analysis + Gradio</p>")
|
| 281 |
|
| 282 |
return interface
|
| 283 |
|