Aya-Vision-8B 和 Qwen2VL-OCR-2B 之间的潦草手写体 OCR 比较

社区文章 发布于 2025 年 3 月 12 日

image/png

本次比较仅用于实验目的。尽管这是一项 8B 参数模型与基于 Qwen2VL 的 2B 参数 OCR 模型之间的不平衡比较,但目标是评估较低参数模型在 OCR 任务中的表现如何,与 Aya-Vision-8B 等中等消费级模型进行比较。

  • 您可以使用 Hugging Face Spaces 上的交互式演示测试这两个模型

本次比较中使用的模型

模型名称 描述 Hugging Face 链接
Aya Vision 8B 一个用于 OCR 和其他视觉任务的 8B 参数视觉模型。 Aya-Vision-8B
Qwen2VL-OCR-2B 一个为 OCR 任务优化的 2B 参数视觉-语言模型。 Qwen2-VL-OCR-2B
演示在此 Aya Vision 和 Qwen2VL 演示 在此尝试多模态 OCR

本研究探讨了较低参数模型与更复杂的中档视觉模型相比,如何处理潦草手写体识别

实验详情

该实验包括分析以下图片,每张图片都按潦草手写体识别的不同难度级别进行分类。这些图片作为测试用例,用于比较两种模型的 OCR 能力。

测试样本 1

提示: OCR 图片

image/jpeg

模型 提取文本
Aya-Vision-8B “雪人今天感觉很积极。雪人给自己做了一只大蓬松狗。那个穿着蹄子和围巾的雪人感到快乐,有点像女孩。你给他一个拥抱。他喜欢。他住在一个可爱的冰屋里。他很整洁。”
Qwen2VL-OCR-2B “雪人每天都感到积极,雪人给自己做了一只大蓬松狗。雪人戴着帽子和围巾很高兴。他感到快乐并给你一个拥抱。他住在一个孤独的冰屋里。他很暴躁。”

测试样本 2

提示: OCR 图片

image/png

模型 提取文本
Aya-Vision-8B “亲爱的爸爸,我真的把学分归于学校。它让我对所有东西都很难。我简直想不出我需要什么,所以如果你愿意,你可以给我寄一张卡片。我很想听到你的消息。爱你的,[你的名字]”
Qwen2VL-OCR-2B “亲爱的爸爸,学校真的很好。我交了很多朋友,学习也很努力。我所有的东西,我简直想不出我需要什么。所以如果你愿意,你可以给我寄一张卡片,我很想听到你的消息。爱你的,你的儿子”

测试样本 3

提示: OCR 图片

image/gif

模型 提取文本
Aya-Vision-8B “注 1 这里是文本。这是一张手写便条,带有涂鸦和草书。文本似乎是思想或提醒的混合,可能与个人成长或建议有关。由于手写风格和图像质量,阅读起来有点困难。可以辨认出的一些关键短语包括:- '这里是文本' - '这是一张手写便条' - '一些涂鸦和草书' - '思想或提醒的混合' - '与个人成长或建议有关' 总的来说,这张便条似乎是个人反思或手写记录的一系列想法。”
Qwen2VL-OCR-2B “注 1 请每天服用这些药片三次,您应该会感觉好很多。”

测试样本 4

提示: OCR 图片

image/jpeg

模型 提取文本
Aya-Vision-8B “记录。考古学记录了这些文化中类体育活动以及在这些文化中进行的体育运动。”
Qwen2VL-OCR-2B “记录。考古学有着悠久的体育活动历史,存在于这些文化中以及这些文化的生活中。”

测试样本 5

提示: OCR 图片

image/jpeg

模型 提取文本
Aya-Vision-8B “狮子嘲笑老鼠,放走了他。几天后,同一只狮子被猎人的网捕获。他尽力想挣脱网,但几乎成功。然而,他失败了。他愤怒地大声咆哮。听到狮子咆哮的人犹豫了,听到狮子咆哮的人犹豫了。”
Qwen2VL-OCR-2B “狮子嘲笑老鼠,放走了他。几天后,同一只狮子被猎人的网捕获。他几乎挣脱了网,但失败了。他愤怒地大声咆哮。老鼠听到了狮子的咆哮,并匆忙赶来。”

测试样本 6

提示: OCR 图片

image/jpeg

模型 提取文本
Aya-Vision-8B “今天是十月二十日,星期四。但感觉绝对像星期五。我正在煮第二杯咖啡,甚至已经写完了笔记。有时我会翻看旧笔记,我的笔迹简直认不出来。我试过全大写,但这看起来很刻意和不自然。我还是在笔记本电脑或纸上记笔记吧。我不确定我用的是什么笔。我试过不同类型的笔,但似乎没有一支是完美的。我对写出来的东西感到压力。人们就是这样写的!”
Qwen2VL-OCR-2B “今天是十月三十日,星期四——但感觉绝对像星期五。我已经在考虑再泡一杯咖啡了——而我第一杯还没喝完。我有问题吗?有时我会翻看我以前的笔记,我的字迹简直认不出来。也许这取决于我用的笔的类型?我试过全大写,但这看起来太刻意和不自然了。很多时候,我会在笔记本电脑上记笔记,但我似乎仍然更喜欢笔和纸。有什么改进建议吗?我看着我刚刚写的东西,已经感到压力很大了——它看起来像是三个人写的!!”

测试样本 7

提示: OCR 图像内容

image/jpeg

模型 提取文本
Aya-Vision-8B “A.M. Palmer 公司,纽约市。各位先生,我已完成 Palmer 商业书写法的课程,现呈上我的考试。我已努力严格遵循手册中的印刷说明,希望能获得最终证书。期待您的决定,山姆,此致。”
Qwen2VL-OCR-2B “你的城镇,1915 年 1 月 30 日。A. N. Palmer 公司,纽约市。各位先生:- 我已完成 Palmer 商业书写法的课程,现呈上我的考试。我已努力严格遵循手册中的印刷说明,希望能获得最终证书。期待您的决定,此致。”

测试样本 8

提示: OCR 图片

image/jpeg

模型 提取文本
Aya-Vision-8B “厌倦了这一切,为了安息而哭泣,就像看到一个更大的出生,贫困的虚无在快乐中被修剪,镀金的信仰不幸地被遗弃,少女的荣誉可耻地被玷污,视力和完美被痛苦地厌恶,力量被蹒跚的支配削弱,艺术变得强大,艺术像医生一样控制着孩子,被俘的好东西侍奉着坏船长,我宁愿离开,让我所爱的人独自一人。”
Qwen2VL-OCR-2B “厌倦了这一切,为求安息而哭泣,如同见弃于更生者,贫穷卑微却沉溺于狂欢,最纯洁的信仰不幸被遗弃,镀金的荣誉被可耻地错位,少女的美德被粗暴地践踏,完美的视力被无端地玷污,力量被跛行所削弱,艺术被权力钳制,愚蠢如医生般掌控着技能,被俘虏的善良侍奉着邪恶的船长。厌倦了这一切,我宁愿离去,为了死亡,我抛弃了我的爱。”

测试样本 9

提示: OCR 图片

image/png

模型 提取文本
Aya-Vision-8B “英国于 1947 年 8 月 15 日给予印度独立。印度人民怀着巨大的喜悦庆祝独立日。1 月 26 日是印度的共和国日。独立日和共和国日被视为国家节日,我们在这些日子里放假。”
Qwen2VL-OCR-2B “英国于 1947 年 8 月 15 日给予印度独立。印度人民怀着巨大的喜悦庆祝独立日。1 月 26 日是印度的共和国日。独立日和共和国日被视为国家节日,我们在这些日子里放假。”

测试样本 10

提示: OCR 图片

image/png

模型 提取文本
Aya-Vision-8B “对于像我这种字写得极差的人来说,这是一个很棒的工具。”
Qwen2VL-OCR-2B “对于像我这种字写得极差的人来说,这是一个很棒的工具。”

使用 transformers🤗 快速入门

!pip install -q gradio_client==1.3.0  
!pip install -q qwen-vl-utils==0.0.2  
!pip install -q transformers-stream-generator==0.0.4  
!pip install -q torch==2.4.0  
!pip install -q torchvision==0.19.0  
!pip install -q git+https://github.com/huggingface/transformers.git@v4.49.0-AyaVision  
!pip install -q accelerate  
!pip install -q av  
!pip install -q gradio  
import gradio as gr
from transformers import (
    Qwen2VLForConditionalGeneration,
    AutoProcessor,
    TextIteratorStreamer,
    AutoModelForImageTextToText,
)
from transformers.image_utils import load_image
from threading import Thread
import time
import torch
import spaces
from PIL import Image
import requests
from io import BytesIO

# Helper function to return a progress bar HTML snippet.
def progress_bar_html(label: str) -> str:
    return f'''
<div style="display: flex; align-items: center;">
    <span style="margin-right: 10px; font-size: 14px;">{label}</span>
    <div style="width: 110px; height: 5px; background-color: #FFB6C1; border-radius: 2px; overflow: hidden;">
        <div style="width: 100%; height: 100%; background-color: #FF69B4 ; animation: loading 1.5s linear infinite;"></div>
    </div>
</div>
<style>
@keyframes loading {{
    0% {{ transform: translateX(-100%); }}
    100% {{ transform: translateX(100%); }}
}}
</style>
    '''

QV_MODEL_ID = "prithivMLmods/Qwen2-VL-OCR-2B-Instruct" # or use  #prithivMLmods/Qwen2-VL-OCR2-2B-Instruct
qwen_processor = AutoProcessor.from_pretrained(QV_MODEL_ID, trust_remote_code=True)
qwen_model = Qwen2VLForConditionalGeneration.from_pretrained(
    QV_MODEL_ID,
    trust_remote_code=True,
    torch_dtype=torch.float16
).to("cuda").eval()

AYA_MODEL_ID = "CohereForAI/aya-vision-8b"
aya_processor = AutoProcessor.from_pretrained(AYA_MODEL_ID)
aya_model = AutoModelForImageTextToText.from_pretrained(
    AYA_MODEL_ID, device_map="auto", torch_dtype=torch.float16
)

@spaces.GPU
def model_inference(input_dict, history):
    text = input_dict["text"].strip()
    files = input_dict.get("files", [])
    
    if text.lower().startswith("@aya-vision"):
        # Remove the command prefix and trim the prompt.
        text_prompt = text[len("@aya-vision"):].strip()
        if not files:
            yield "Error: Please provide an image for the @aya-vision feature."
            return
        else:
            # For simplicity, use the first provided image.
            image = load_image(files[0])
            yield progress_bar_html("Processing with Aya-Vision-8b")
            messages = [{
                "role": "user",
                "content": [
                    {"type": "image", "image": image},
                    {"type": "text", "text": text_prompt},
                ],
            }]
            inputs = aya_processor.apply_chat_template(
                messages,
                padding=True,
                add_generation_prompt=True,
                tokenize=True,
                return_dict=True,
                return_tensors="pt"
            ).to(aya_model.device)
            # Set up a streamer for Aya-Vision output
            streamer = TextIteratorStreamer(aya_processor, skip_prompt=True, skip_special_tokens=True)
            generation_kwargs = dict(
                inputs, 
                streamer=streamer, 
                max_new_tokens=1024, 
                do_sample=True, 
                temperature=0.3
            )
            thread = Thread(target=aya_model.generate, kwargs=generation_kwargs)
            thread.start()
            buffer = ""
            for new_text in streamer:
                buffer += new_text
                buffer = buffer.replace("<|im_end|>", "")
                time.sleep(0.01)
                yield buffer
            return

    # Load images if provided.
    if len(files) > 1:
        images = [load_image(image) for image in files]
    elif len(files) == 1:
        images = [load_image(files[0])]
    else:
        images = []
    
    # Validate input: require both text and (optionally) image(s).
    if text == "" and not images:
        yield "Error: Please input a query and optionally image(s)."
        return
    if text == "" and images:
        yield "Error: Please input a text query along with the image(s)."
        return

    # Prepare messages for the Qwen2-VL model.
    messages = [{
        "role": "user",
        "content": [
            *[{"type": "image", "image": image} for image in images],
            {"type": "text", "text": text},
        ],
    }]
    
    prompt = qwen_processor.apply_chat_template(
        messages, tokenize=False, add_generation_prompt=True
    )
    inputs = qwen_processor(
        text=[prompt],
        images=images if images else None,
        return_tensors="pt",
        padding=True,
    ).to("cuda")
    
    # Set up a streamer for real-time output.
    streamer = TextIteratorStreamer(qwen_processor, skip_prompt=True, skip_special_tokens=True)
    generation_kwargs = dict(inputs, streamer=streamer, max_new_tokens=1024)
    
    # Start generation in a separate thread.
    thread = Thread(target=qwen_model.generate, kwargs=generation_kwargs)
    thread.start()
    
    buffer = ""
    yield progress_bar_html("Processing with Qwen2VL OCR")
    for new_text in streamer:
        buffer += new_text
        buffer = buffer.replace("<|im_end|>", "")
        time.sleep(0.01)
        yield buffer

examples = [
    [{"text": "@aya-vision Summarize the letter", "files": ["examples/1.png"]}],
    [{"text": "@aya-vision Extract JSON from the image", "files": ["example_images/document.jpg"]}],
    [{"text": "Extract as JSON table from the table", "files": ["examples/4.jpg"]}],
    [{"text": "@aya-vision Describe the photo", "files": ["examples/3.png"]}],
    [{"text": "@aya-vision Summarize the full image in detail", "files": ["examples/2.jpg"]}],
    [{"text": "@aya-vision Describe this image.", "files": ["example_images/campeones.jpg"]}],
    [{"text": "@aya-vision What is this UI about?", "files": ["example_images/s2w_example.png"]}],
    [{"text": "Can you describe this image?", "files": ["example_images/newyork.jpg"]}],
    [{"text": "Can you describe this image?", "files": ["example_images/dogs.jpg"]}],
    [{"text": "@aya-vision Where do the severe droughts happen according to this diagram?", "files": ["example_images/examples_weather_events.png"]}],
]

demo = gr.ChatInterface(
    fn=model_inference,
    description="# **Multimodal OCR `@aya-vision 'prompt..'`**",
    examples=examples,
    textbox=gr.MultimodalTextbox(
        label="Query Input", 
        file_types=["image"], 
        file_count="multiple", 
        placeholder="By default, it runs Qwen2VL OCR, Tag @aya-vision for Aya Vision 8B"
    ),
    stop_btn="Stop Generation",
    multimodal=True,
    cache_examples=False,
)

demo.launch(debug=True)

示例

https://huggingface.co/spaces/prithivMLmods/Multimodal-OCR/tree/main/examples

https://huggingface.co/spaces/prithivMLmods/Multimodal-OCR/tree/main/example_images

这是一项旨在提高 prithivMLmods/Qwen2-VL-OCR-2B-InstructprithivMLmods/Qwen2-VL-OCR2-2B-Instruct OCR 性能的实验性测试。Qwen2-VL-OCR-2B-Instruct 模型在某些情况下与 Aya-Vision 8B 旗鼓相当,甚至在某些 OCR 任务中表现更优。

分享您对这些样本案例的看法!

感谢阅读! 🤗

社区

注册登录 发表评论