from groq import Groq import base64 from PIL import Image import io from .config import Config class GroqAnalyzer: def __init__(self): Config.validate() self.client = Groq(api_key=Config.GROQ_API_KEY) self.model = "meta-llama/llama-4-maverick-17b-128e-instruct" def analyze_damage(self, image_path): try: with open(image_path, "rb") as image_file: base64_image = base64.b64encode(image_file.read()).decode() system_message = """You are a professional car damage assessment expert. Your task is to analyze car images and provide structured, consistent damage reports. Please follow these exact guidelines: 1. Use only these severity levels: High, Medium, Low 2. For status, use these terms: Damaged, Intact, Partially Visible, Potentially damaged 3. For actions, use these categories: Replacement/Repair, Inspection, Inspection/Repair 4. Always assess these components if visible: Front Bumper, Hood, Grille, Headlights, Fenders 5. Provide a consistent summary format focusing on: - Main visible damage - Recommended immediate actions - Secondary inspection points """ analysis_template = """Please analyze the car damage and provide the assessment in this exact format: [TABLE] Component | Status | Severity | Action Needed Follow with a structured table using | as separators. [SUMMARY] Start with "The image shows..." and describe: 1. Primary damage location and severity 2. Key components affected 3. Required immediate actions 4. Additional inspection recommendations Keep the format consistent and use only the predefined terms for severity, status, and actions.""" completion = self.client.chat.completions.create( model=self.model, messages=[ { "role": "system", "content": system_message }, { "role": "user", "content": [ { "type": "text", "text": analysis_template }, { "type": "image_url", "image_url": { "url": f"data:image/jpeg;base64,{base64_image}" } } ] } ], temperature=0.3, # Lower temperature for more consistent outputs max_completion_tokens=1024, top_p=0.9, # Slightly lower top_p for more focused outputs stream=True, stop=None ) # Handle streaming response full_response = "" for chunk in completion: if chunk.choices[0].delta.content: full_response += chunk.choices[0].delta.content return full_response except Exception as e: print(f"Error in Groq analysis: {e}") return f"Error analyzing image: {str(e)}"