Spaces:
Sleeping
Sleeping
Update model.py
Browse files123456715 unmodified lines23242526272829303132333435363713 unmodified lines515253545556575859606162631 unmodified line65666768697071727374751 unmodified line77787980818270 unmodified lines153154155156157158from transformers import AutoModelForSeq2SeqLM, AutoTokenizerimport torchfrom typing import Dict, Listdef get_weather_condition(score: int) -> str:"""Map weather impact score (0-100) to descriptive weather condition."""if score <= 10:15 unmodified lines"""model_name = "sshleifer/distilbart-cnn-6-6"try:# Load tokenizer and model for CPUtokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=False)model = AutoModelForSeq2SeqLM.from_pretrained(model_name,torch_dtype=torch.float32, # Use float32 for CPUuse_safetensors=True, # Ensure safe loadingtrust_remote_code=False)# Prepare promptprompt = f"""You are an AI assistant analyzing project delay risks for a construction project.13 unmodified linesFormat the response as a list of strings, e.g., ["Insight 1", "Insight 2"]."""# Tokenize and generate with no_grad for memory efficiencywith torch.no_grad():inputs = tokenizer(prompt, return_tensors="pt", max_length=512, truncation=True).to("cpu")outputs = model.generate(**inputs,max_new_tokens=150, # Smaller output for CPU efficiencynum_beams=4, # Beam search for better qualitytemperature=0.7,do_sample=True)1 unmodified line# Parse response into a listinsights = [line.strip() for line in response.split("\n") if line.strip() and line.strip() not in [prompt]]return insights[:4] # Limit to 2-4 insightsexcept Exception as e:print(f"Error with model inference: {e}")return ["AI model unavailable; monitor progress and resource allocation."]def predict_delay(input_data: Dict) -> Dict:"""1 unmodified lineUses task duration, progress, workforce info, and weather impact.Insights are generated by DistilBART (CPU)."""phase = input_data.get("phase", "")task = input_data.get("task", "")expected_duration = input_data.get("task_expected_duration", 0)70 unmodified lines# Generate AI-driven insightsinsights = call_ai_model_for_insights(input_data, delay_risk)return {"project": input_data.get("project_name", "Unnamed Project"),"phase": phase,12345678910111215 unmodified lines28293031323334353637383940414243444513 unmodified lines596061626364656667686970711 unmodified line737475767778798081828384858687888990919293941 unmodified line9697989910010110270 unmodified lines173174175176177178179from transformers import AutoModelForSeq2SeqLM, AutoTokenizerimport torchimport loggingfrom typing import Dict, List# Configure logginglogging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')logger = logging.getLogger(__name__)def get_weather_condition(score: int) -> str:"""Map weather impact score (0-100) to descriptive weather condition."""if score <= 10:15 unmodified lines"""model_name = "sshleifer/distilbart-cnn-6-6"try:logger.info(f"Loading model: {model_name}")# Load tokenizer and model with minimal memory usagetokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=False, use_fast=True)model = AutoModelForSeq2SeqLM.from_pretrained(model_name,torch_dtype=torch.float32, # CPU-compatibleuse_safetensors=True, # Secure loadingtrust_remote_code=False,low_cpu_mem_usage=True # Optimize for low memory)logger.info("Model loaded successfully. Generating insights...")# Prepare promptprompt = f"""You are an AI assistant analyzing project delay risks for a construction project.13 unmodified linesFormat the response as a list of strings, e.g., ["Insight 1", "Insight 2"]."""# Tokenize and generate with memory-efficient settingswith torch.no_grad():inputs = tokenizer(prompt, return_tensors="pt", max_length=512, truncation=True).to("cpu")outputs = model.generate(**inputs,max_new_tokens=100, # Reduced for faster CPU inferencenum_beams=4,temperature=0.7,do_sample=True)1 unmodified line# Parse response into a listinsights = [line.strip() for line in response.split("\n") if line.strip() and line.strip() not in [prompt]]logger.info(f"Generated insights: {insights}")return insights[:4] or ["No insights generated; review input data."]except Exception as e:logger.error(f"Model inference failed: {str(e)}")# Fallback: Generate basic rule-based insightsfallback_insights = []if delay_risk > 75:fallback_insights.append("High risk detected; allocate additional resources urgently.")elif delay_risk > 50:fallback_insights.append("Moderate risk; consider extending shift hours or hiring staff.")if input_data.get('workforce_gap', 0) > 20:fallback_insights.append("Significant workforce gap; recruit additional workers.")if input_data.get('weather_impact_score', 0) > 50:fallback_insights.append("Adverse weather; prioritize indoor tasks.")return fallback_insights or ["AI model unavailable; monitor progress and resource allocation."]def predict_delay(input_data: Dict) -> Dict:"""1 unmodified lineUses task duration, progress, workforce info, and weather impact.Insights are generated by DistilBART (CPU)."""logger.info("Starting delay prediction")phase = input_data.get("phase", "")task = input_data.get("task", "")expected_duration = input_data.get("task_expected_duration", 0)70 unmodified lines# Generate AI-driven insightsinsights = call_ai_model_for_insights(input_data, delay_risk)logger.info(f"Prediction completed: Delay risk = {delay_risk:.1f}%")return {"project": input_data.get("project_name", "Unnamed Project"),"phase": phase,
model.py+32-11