import os from together import Together import base64 from io import BytesIO from PIL import Image import imghdr import tempfile # Set your API key os.environ["TOGETHER_API_KEY"] class ImageProcessor: def __init__(self): self.client = Together() self.prompt = """Convert the provided image into Markdown format. Ensure that all content from the page is included, such as headers, footers, subtexts, images (with alt text if possible), tables, and any other elements. Requirements: - Output Only Markdown: Return solely the Markdown content without any additional explanations or comments. - No Delimiters: Do not use code fences or delimiters like \`\`\`markdown. - Complete Content: Do not omit any part of the page, including headers, footers, and subtext. """ self.model = "meta-llama/Llama-3.2-11B-Vision-Instruct-Turbo" def get_mime_type(self, image_path): """Determine MIME type based on actual image format using imghdr""" img_type = imghdr.what(image_path) if img_type: return f'image/{img_type}' # Fallback to extension-based detection extension = os.path.splitext(image_path)[1].lower() mime_types = { '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.gif': 'image/gif', '.webp': 'image/webp' } return mime_types.get(extension, 'image/jpeg') def encode_image(self, image_path=None, image_data=None): """Encode image to base64 with error handling. Accepts either image_path or image_data (PIL Image or numpy array).""" if image_data is not None: try: buffered = BytesIO() # Convert numpy array to PIL Image if needed if hasattr(image_data, "shape"): image_data = PILImage.fromarray(image_data) image_data.save(buffered, format="PNG") return base64.b64encode(buffered.getvalue()).decode('utf-8'), 'image/png' except Exception as e: raise Exception(f"Error encoding image data: {str(e)}") elif image_path is not None: if not os.path.exists(image_path): raise FileNotFoundError(f"Image file not found: {image_path}") try: with open(image_path, "rb") as image_file: return base64.b64encode(image_file.read()).decode('utf-8'), self.get_mime_type(image_path) except Exception as e: raise Exception(f"Error encoding image: {str(e)}") else: raise ValueError("Either image_path or image_data must be provided") def analyze_image(self, image_path=None, image_data=None): """Analyze image using Together API with proper error handling. Accepts image_path or image_data (PIL Image).""" try: # Encode image and get MIME type base64_image, mime_type = self.encode_image(image_path=image_path, image_data=image_data) # Create API request stream = self.client.chat.completions.create( model=self.model, messages=[{ "role": "user", "content": [ {"type": "text", "text": self.prompt}, { "type": "image_url", "image_url": { "url": f"data:{mime_type};base64,{base64_image}" }, }, ], }], stream=True, ) # Process streaming response response_text = "" for chunk in stream: if hasattr(chunk, 'choices') and chunk.choices: if hasattr(chunk.choices[0], 'delta'): if hasattr(chunk.choices[0].delta, 'content'): content = chunk.choices[0].delta.content if content is not None: print(content, end="", flush=True) response_text += content return response_text except FileNotFoundError as e: print(f"File Error: {str(e)}") raise except Exception as e: print(f"Error during image analysis: {str(e)}") raise # # Remove example usage to avoid running on import # processor = ImageProcessor() # try: # # Example with different image types # image_paths = ["./data/2.jpg" # ] # for image_path in image_paths: # print(f"\nAnalyzing {image_path}...") # result=processor.analyze_image( # image_path # ) # print(f"\nResult for {image_path}:\n{result}") # except Exception as e: # print(f"An error occurred: {str(e)}")