lyg
2 天以前 22f370322412074174cde20ecfd14ec03657ab63
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
# -*- coding: utf-8 -*-
# @author: lyg
# @date: 2025-5-8
# @version: 1
# @description: 利用LLM将图片转为文本。
 
from langchain_core.prompts import HumanMessagePromptTemplate, ChatPromptTemplate
from langchain_core.messages import HumanMessage, SystemMessage
from langchain_core.output_parsers import JsonOutputParser
import json
import base64
 
from knowledgebase.llm import vision_llm
 
 
class ImageToText:
    def __init__(self):
        self.llm = vision_llm
        self.prompt = ChatPromptTemplate.from_messages([
            ("system", "你是一个资深软件工程师,请分析图片中的内容。"),
            (
                "user",
                [
                    {"type": "text", "text": "{msg}"},
                    {
                        "type": "image_url",
                        "image_url": {"url": "data:image/jpeg;base64,{image}"},
                    }
                ],
            )
        ])
 
    def gen_text_from_img(self, image: bytes) -> str:
        """
        从图片生成文本。
 
        :param image:  图片数据
        :return: 文本
        """
        image = base64.b64encode(image).decode()
        chain = self.prompt | self.llm
        resp = chain.invoke({"msg": "使用自然语言输出图片中的内容,不要做过多的解释。输出格式为纯文本。", "image": image})
        return resp.content