|
| 1 | +import base64 |
| 2 | +import json |
| 3 | +import os.path |
| 4 | +from mimetypes import guess_type |
| 5 | + |
| 6 | +from injector import inject |
| 7 | + |
| 8 | +from taskweaver.llm import LLMApi, format_chat_message |
| 9 | +from taskweaver.logging import TelemetryLogger |
| 10 | +from taskweaver.memory import Memory, Post |
| 11 | +from taskweaver.memory.attachment import AttachmentType |
| 12 | +from taskweaver.module.event_emitter import SessionEventEmitter |
| 13 | +from taskweaver.module.tracing import Tracing |
| 14 | +from taskweaver.role import Role |
| 15 | +from taskweaver.role.role import RoleConfig, RoleEntry |
| 16 | +from taskweaver.session import SessionMetadata |
| 17 | + |
| 18 | + |
| 19 | +# Function to encode a local image into data URL |
| 20 | +def local_image_to_data_url(image_path): |
| 21 | + # Guess the MIME type of the image based on the file extension |
| 22 | + mime_type, _ = guess_type(image_path) |
| 23 | + if mime_type is None: |
| 24 | + mime_type = "application/octet-stream" # Default MIME type if none is found |
| 25 | + |
| 26 | + try: |
| 27 | + # Read and encode the image file |
| 28 | + with open(image_path, "rb") as image_file: |
| 29 | + base64_encoded_data = base64.b64encode(image_file.read()).decode("utf-8") |
| 30 | + except FileNotFoundError: |
| 31 | + logger.error(f"Error: The file {image_path} does not exist.") |
| 32 | + return None |
| 33 | + except IOError: |
| 34 | + logger.error(f"Error: The file {image_path} could not be read.") |
| 35 | + return None |
| 36 | + # Construct the data URL |
| 37 | + return f"data:{mime_type};base64,{base64_encoded_data}" |
| 38 | + |
| 39 | + |
| 40 | +class ImageReaderConfig(RoleConfig): |
| 41 | + def _configure(self): |
| 42 | + pass |
| 43 | + |
| 44 | + |
| 45 | +class ImageReader(Role): |
| 46 | + @inject |
| 47 | + def __init__( |
| 48 | + self, |
| 49 | + config: ImageReaderConfig, |
| 50 | + logger: TelemetryLogger, |
| 51 | + tracing: Tracing, |
| 52 | + event_emitter: SessionEventEmitter, |
| 53 | + role_entry: RoleEntry, |
| 54 | + llm_api: LLMApi, |
| 55 | + session_metadata: SessionMetadata, |
| 56 | + ): |
| 57 | + super().__init__(config, logger, tracing, event_emitter, role_entry) |
| 58 | + |
| 59 | + self.llm_api = llm_api |
| 60 | + self.session_metadata = session_metadata |
| 61 | + |
| 62 | + def reply(self, memory: Memory, **kwargs: ...) -> Post: |
| 63 | + rounds = memory.get_role_rounds( |
| 64 | + role=self.alias, |
| 65 | + include_failure_rounds=False, |
| 66 | + ) |
| 67 | + |
| 68 | + # obtain the query from the last round |
| 69 | + last_post = rounds[-1].post_list[-1] |
| 70 | + |
| 71 | + post_proxy = self.event_emitter.create_post_proxy(self.alias) |
| 72 | + |
| 73 | + post_proxy.update_send_to(last_post.send_from) |
| 74 | + |
| 75 | + input_message = last_post.message |
| 76 | + prompt = ( |
| 77 | + f"Input message: {input_message}.\n" |
| 78 | + "\n" |
| 79 | + "Your response should be a JSON object with the key 'image_url' and the value as the image path. " |
| 80 | + "For example, {'image_url': 'c:/images/image.jpg'} or {'image_url': 'http://example.com/image.jpg'}. " |
| 81 | + "Do not add any additional information in the response or wrap the JSON with ```json and ```." |
| 82 | + ) |
| 83 | + |
| 84 | + response = self.llm_api.chat_completion( |
| 85 | + messages=[ |
| 86 | + format_chat_message( |
| 87 | + role="system", |
| 88 | + message="Your task is to read the image path from the message.", |
| 89 | + ), |
| 90 | + format_chat_message( |
| 91 | + role="user", |
| 92 | + message=prompt, |
| 93 | + ), |
| 94 | + ], |
| 95 | + ) |
| 96 | + |
| 97 | + image_url = json.loads(response["content"])["image_url"] |
| 98 | + if image_url.startswith("http"): |
| 99 | + image_content = image_url |
| 100 | + attachment_message = f"Image from {image_url}." |
| 101 | + else: |
| 102 | + if os.path.isabs(image_url): |
| 103 | + image_content = local_image_to_data_url(image_url) |
| 104 | + else: |
| 105 | + image_content = local_image_to_data_url(os.path.join(self.session_metadata.execution_cwd, image_url)) |
| 106 | + attachment_message = f"Image from {image_url} encoded as a Base64 data URL." |
| 107 | + |
| 108 | + post_proxy.update_attachment( |
| 109 | + message=attachment_message, |
| 110 | + type=AttachmentType.image_url, |
| 111 | + extra={"image_url": image_content}, |
| 112 | + is_end=True, |
| 113 | + ) |
| 114 | + |
| 115 | + post_proxy.update_message( |
| 116 | + "I have read the image path from the message. The image is attached below.", |
| 117 | + ) |
| 118 | + |
| 119 | + return post_proxy.end() |
0 commit comments