File size: 5,141 Bytes
1284dde
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
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)}")