''' This module provides functions to process an image and answer questions about it using OpenAI's vision-capable models (e.g., GPT-4o). ''' import os import base64 from PIL import Image from langchain_openai import ChatOpenAI from langchain_core.messages import SystemMessage, HumanMessage # --- Global variables for models (loaded once) --- LLM_MODEL = None def _get_mime_type(image_path: str) -> str: try: extension = os.path.splitext(image_path)[1].lower() if extension == ".png": return "image/png" elif extension in [".jpg", ".jpeg"]: return "image/jpeg" elif extension == ".gif": return "image/gif" elif extension == ".webp": return "image/webp" else: # Fallback for unknown types, try to let PIL infer and default to jpeg try: img = Image.open(image_path) format = img.format if format == "PNG": return "image/png" if format == "JPEG": return "image/jpeg" if format == "GIF": return "image/gif" if format == "WEBP": return "image/webp" except Exception: pass # Ignore PIL error if it occurs, use default print(f"Warning: Unknown image type for {image_path}, defaulting to image/jpeg. May affect processing.") return "image/jpeg" # Default if extension is not recognized except Exception as e: print(f"Error getting mime type for {image_path}: {e}. Defaulting to image/jpeg.") return "image/jpeg" def _encode_image_to_base64(image_path: str) -> str | None: '''Encodes an image file to a base64 string.''' try: with open(image_path, "rb") as image_file: return base64.b64encode(image_file.read()).decode('utf-8') except FileNotFoundError: print(f"Error: Image file not found at {image_path}") return None except Exception as e: print(f"Error encoding image {image_path}: {e}") return None def _initialize_models(): global LLM_MODEL if LLM_MODEL is None: try: print("Initializing LLM (ChatOpenAI gpt-4o for Vision)...") LLM_MODEL = ChatOpenAI(model="gpt-4o", temperature=0.0, api_key=os.getenv("OPENAI_API_KEY"), max_tokens=1024) # GPT-4o is vision-capable print("Vision LLM initialized successfully.") except Exception as e: print(f"Error initializing Vision LLM: {e}. Image Q&A will not work.") LLM_MODEL = None # Ensure it's None if failed _initialize_models() # Initialize models when the module is loaded def process_image_and_answer(image_path: str, question: str, task_id: str | None = None) -> dict: ''' Processes an image to answer a question about it using OpenAI's GPT-4o (Vision). Args: image_path: Path to the image file. question: The question to answer about the image. task_id: An optional task ID for tracking. Returns: A dictionary containing the input parameters, a status message, and the answer. ''' print(f"Processing image '{image_path}' for question '{question}' (Task ID: {task_id}) using GPT-4o Vision.") if LLM_MODEL is None: return { "image_path": image_path, "question": question, "task_id": task_id, "description": "N/A - Vision LLM not initialized", "answer": "Error: Vision LLM is not initialized.", "status": "Error: LLM not initialized" } base64_image = _encode_image_to_base64(image_path) if base64_image is None: return { "image_path": image_path, "question": question, "task_id": task_id, "description": "N/A - Image encoding failed", "answer": f"Error: Could not encode image at {image_path}. Check logs.", "status": "Error: Image encoding failed" } mime_type = _get_mime_type(image_path) # System prompt can guide the LLM on how to behave, even for vision tasks. # For chess, asking for algebraic notation is a good idea. system_prompt_content = ( "You are an expert AI assistant analyzing an image. Answer the user's question based on the visual content of the image. " "If the question is about a chess position, and you can identify it, provide the answer in algebraic notation (e.g., Qb7, Nxf3). " "Be precise and focus only on what is visible in the image and relevant to the question." ) messages = [ SystemMessage(content=system_prompt_content), HumanMessage( content=[ {"type": "text", "text": question}, { "type": "image_url", "image_url": { "url": f"data:{mime_type};base64,{base64_image}" } } ] ) ] try: print(f"Sending image and question to GPT-4o Vision...") response = LLM_MODEL.invoke(messages) answer = response.content print(f"Successfully received answer from GPT-4o Vision: {answer[:200]}...") status = "Success" description = "Image processed directly by Vision LLM." except Exception as e: print(f"Error calling OpenAI Vision API: {e}") answer = f"Error: Could not get answer from Vision LLM. Details: {str(e)}" status = "Error: Vision API call failed" description = "N/A - Vision API call error" return { "image_path": image_path, "question": question, "task_id": task_id, "description": description, "answer": answer, "status": status } if __name__ == '__main__': if not os.getenv("OPENAI_API_KEY"): print("WARNING: OPENAI_API_KEY not set. GPT-4o Vision calls will fail.") dummy_image_path = "dummy_test_image.png" is_dummy_created = False try: img = Image.new('RGB', (60, 30), color = 'red') # Create a simple red image img.save(dummy_image_path, "PNG") print(f"Created dummy PNG file for testing: {dummy_image_path}") is_dummy_created = True except Exception as e: print(f"Could not create dummy PNG for testing: {e}. Ensure current directory is writable or provide a valid image path for testing.") if is_dummy_created or os.path.exists(dummy_image_path): print(f"\n--- Testing with image: {dummy_image_path} ---") test_question_color = "What is the dominant color of this image?" test_task_id_color = "test-vision-color-001" print(f"\nRunning color question: '{test_question_color}'") result_color = process_image_and_answer(dummy_image_path, test_question_color, test_task_id_color) print("\n--- Color Question Test Run Output ---") for key, value in result_color.items(): print(f"{key.capitalize()}: {value}") print("------------------------------------") # This will still be a tough test for the dummy image, but tests the flow test_question_chess = "If this were a chess board with a queen on a1, what color is the queen?" test_task_id_chess = "test-vision-chess-001" print(f"\nRunning hypothetical chess question: '{test_question_chess}'") result_chess = process_image_and_answer(dummy_image_path, test_question_chess, test_task_id_chess) print("\n--- Hypothetical Chess Question Test Run Output ---") for key, value in result_chess.items(): print(f"{key.capitalize()}: {value}") print("-----------------------------------------------") if is_dummy_created: try: os.remove(dummy_image_path) print(f"Removed dummy file: {dummy_image_path}") except Exception as e: print(f"Could not remove dummy file {dummy_image_path}: {e}") else: print("Skipping example run as dummy image could not be prepared.")