/ Модель

Характеристики

Контекст
32 768 токенов
Параметры
1,5 млрд
Лицензия
Apache 2.0
Архитектура
qwen2_vl · dense
Базовая модель
Qwen2-VL-2B-Instruct
Библиотека
transformers
Опубликована
16 янв 2025

ChemQwen-vL

Изображение и текст → текст3 профессии

Мультимодальная модель для распознавания химических структур на изображениях, генерации InChI и ответов на вопросы по химическим схемам.

35скачиваний за 30 дней5лайковвеса обновлены16 янв 2025

Бенчмарки

Как модель справилась с задачами пользователей ailist и что о ней публикуют открытые лидерборды

Тесты пользователейпока нет

Никто ещё не опубликовал тест этой модели. Соберите бенчмарк из своих задач — результат появится здесь.

  1. Добавьте модель в бенчмарк

    Вместе с другими моделями категории «Изображение → текст» — сравнение идёт внутри одной категории.

  2. Опишите свои задачи

    Напишите запросы, при необходимости приложите файлы и эталонные ответы.

  3. Запустите и опубликуйте

    Модели ответят на каждую задачу, судья оценит ответы. Опубликованный результат появится на этой странице.

Публичные оценки

Из открытых лидербордов. Сравнивайте результаты одного теста при одинаковых условиях — отсутствие оценки не значит, что модель хуже.

В подключённых источниках результатов для этой модели пока нет.

Что умеет модель

Описание составлено по карточке модели и метаданным Hugging Face

ChemQwen-vL — мультимодальная модель для химии, разработанная prithivMLmods путём дообучения Qwen2-VL-2B-Instruct. Она принимает изображения и текстовые запросы, распознаёт химические структуры на изображениях, генерирует для них идентификаторы InChI и текстовые описания, а также отвечает на вопросы о химических схемах. Модель построена на архитектуре Qwen2-VL, поддерживает изображения произвольного разрешения и контекст до 32 768 токенов; размер — 1,5 млрд параметров. В карточке заявлена поддержка химического текста на английском, китайском, немецком, французском, японском, корейском, арабском и других языках.

Модель предназначена для задач хемоинформатики, научного анализа и обучения, включая распознавание структур и обработку химических иллюстраций. Лицензия — Apache-2.0. Карточка предупреждает, что точность может снижаться на сложных или нестандартных схемах, изображениях низкого качества и редких обозначениях; результаты для важных лабораторных решений требуют проверки человеком.

Сценарии применения

  • генерация InChI по изображению химической структуры
  • описание молекулярной структуры по схеме
  • ответы на вопросы по химическим изображениям
  • анализ химических иллюстраций для исследований и обучения
  • извлечение химической информации из сканов

Ограничения

Модель может ошибаться на сложных или нестандартных структурах, изображениях низкого качества и редких химических обозначениях. Карточка рекомендует проверять результаты перед использованием для критически важных лабораторных решений.

Для каких профессий подходит3

Разделы каталога профессий, в задачах которых используется эта модель

Все профессии

Карточка модели

README от автора на Hugging Face, как он его опубликовал

Открыть на Hugging Face

ccccccccccccccccccccc.png

ChemQwen-vL [ Qwen for Chemistry Vision ]

ChemQwen-vL is a vision-language model fine-tuned based on the Qwen2VL-2B Instruct model. It has been trained using the International Chemical Identifier (InChI) format and is optimized for chemical component identification. The model excels at generating the InChI and providing descriptions of chemical compounds based on their images. Its architecture, derived from Qwen2-VL, can handle images of arbitrary resolutions by mapping them into a dynamic number of visual tokens. This offers a more human-like visual processing experience. The model operates in a multi-modal framework, combining image-text-text capabilities.

Key Enhancements

  • State-of-the-art understanding of chemical images: ChemQwen-vL delivers top-tier performance in analyzing chemical images of varying resolutions and ratios, ensuring precise InChI generation and structural descriptions.

  • Advanced processing of chemical sequences: Capable of handling complex molecular structures and long sequences, ChemQwen-vL is ideal for tasks requiring detailed chemical reasoning and compound analysis.

  • Integration with automated laboratory systems: With its powerful reasoning and decision-making capabilities, ChemQwen-vL can integrate with laboratory robotics, enabling autonomous chemical analysis and reporting based on image and text inputs.

  • Multilingual Chemical Text Support: To support global scientific communities, ChemQwen-vL understands chemical texts in multiple languages, including English, Chinese, German, French, Japanese, Korean, Arabic, and more, for enhanced accessibility and collaboration.

Demo Inference With Documentation

ChemQwen.png

📌 ChemQwen Demo :- https://huggingface.co/prithivMLmods/ChemQwen-vL/blob/main/Chemical%20Identifier%20Demo%20Documentation/Chemical%20Identifier%20Demo%20Documentation.ipynb

Datasets

Dataset NameDescriptionInChI Link
IUPAC ProjectsA collection of datasets related to IUPAC projects, including chemical identifiers and standards.InChI Link

Use it with Transformers

Before using, ensure that the required libraries are successfully installed in the environment.

!pip install gradio spaces transformers accelerate numpy requests torch torchvision qwen-vl-utils av ipython reportlab fpdf python-docx pillow huggingface_hub

ChemQwen With Inference Documentation, Before using, make sure that the hf_token is provided in the login field in the code below.


# Authenticate with Hugging Face
from huggingface_hub import login

# Log in to Hugging Face using the provided token
hf_token = '----xxxxx----'
login(hf_token)

# Demo
import gradio as gr
import spaces
from transformers import Qwen2VLForConditionalGeneration, AutoProcessor, TextIteratorStreamer
from qwen_vl_utils import process_vision_info
import torch
from PIL import Image
import os
import uuid
import io
from threading import Thread
from reportlab.lib.pagesizes import A4
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.lib import colors
from reportlab.platypus import SimpleDocTemplate, Image as RLImage, Paragraph, Spacer
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
import docx
from docx.enum.text import WD_ALIGN_PARAGRAPH

# Define model options
MODEL_OPTIONS = {
    "ChemQwen": "prithivMLmods/ChemQwen-vL",
}

# Preload models and processors into CUDA
models = {}
processors = {}
for name, model_id in MODEL_OPTIONS.items():
    print(f"Loading {name}...")
    models[name] = Qwen2VLForConditionalGeneration.from_pretrained(
        model_id,
        trust_remote_code=True,
        torch_dtype=torch.float16
    ).to("cuda").eval()
    processors[name] = AutoProcessor.from_pretrained(model_id, trust_remote_code=True)

image_extensions = Image.registered_extensions()

def identify_and_save_blob(blob_path):
    """Identifies if the blob is an image and saves it."""
    try:
        with open(blob_path, 'rb') as file:
            blob_content = file.read()
            try:
                Image.open(io.BytesIO(blob_content)).verify()  # Check if it's a valid image
                extension = ".png"  # Default to PNG for saving
                media_type = "image"
            except (IOError, SyntaxError):
                raise ValueError("Unsupported media type. Please upload a valid image.")

            filename = f"temp_{uuid.uuid4()}_media{extension}"
            with open(filename, "wb") as f:
                f.write(blob_content)

            return filename, media_type

    except FileNotFoundError:
        raise ValueError(f"The file {blob_path} was not found.")
    except Exception as e:
        raise ValueError(f"An error occurred while processing the file: {e}")

@spaces.GPU
def qwen_inference(model_name, media_input, text_input=None):
    """Handles inference for the selected model."""
    model = models[model_name]
    processor = processors[model_name]

    if isinstance(media_input, str):
        media_path = media_input
        if media_path.endswith(tuple([i for i in image_extensions.keys()])):
            media_type = "image"
        else:
            try:
                media_path, media_type = identify_and_save_blob(media_input)
            except Exception as e:
                raise ValueError("Unsupported media type. Please upload a valid image.")

    messages = [
        {
            "role": "user",
            "content": [
                {
                    "type": media_type,
                    media_type: media_path
                },
                {"type": "text", "text": text_input},
            ],
        }
    ]

    text = processor.apply_chat_template(
        messages, tokenize=False, add_generation_prompt=True
    )
    image_inputs, _ = process_vision_info(messages)
    inputs = processor(
        text=[text],
        images=image_inputs,
        padding=True,
        return_tensors="pt",
    ).to("cuda")

    streamer = TextIteratorStreamer(
        processor.tokenizer, skip_prompt=True, skip_special_tokens=True
    )
    generation_kwargs = dict(inputs, streamer=streamer, max_new_tokens=1024)

    thread = Thread(target=model.generate, kwargs=generation_kwargs)
    thread.start()

    buffer = ""
    for new_text in streamer:
        buffer += new_text
        # Remove <|im_end|> or similar tokens from the output
        buffer = buffer.replace("<|im_end|>", "")
        yield buffer

def format_plain_text(output_text):
    """Formats the output text as plain text without LaTeX delimiters."""
    # Remove LaTeX delimiters and convert to plain text
    plain_text = output_text.replace("\\(", "").replace("\\)", "").replace("\\[", "").replace("\\]", "")
    return plain_text

def generate_document(media_path, output_text, file_format, font_size, line_spacing, alignment, image_size):
    """Generates a document with the input image and plain text output."""
    plain_text = format_plain_text(output_text)
    if file_format == "pdf":
        return generate_pdf(media_path, plain_text, font_size, line_spacing, alignment, image_size)
    elif file_format == "docx":
        return generate_docx(media_path, plain_text, font_size, line_spacing, alignment, image_size)

def generate_pdf(media_path, plain_text, font_size, line_spacing, alignment, image_size):
    """Generates a PDF document."""
    filename = f"output_{uuid.uuid4()}.pdf"
    doc = SimpleDocTemplate(
        filename,
        pagesize=A4,
        rightMargin=inch,
        leftMargin=inch,
        topMargin=inch,
        bottomMargin=inch
    )
    styles = getSampleStyleSheet()
    styles["Normal"].fontSize = int(font_size)
    styles["Normal"].leading = int(font_size) * line_spacing
    styles["Normal"].alignment = {
        "Left": 0,
        "Center": 1,
        "Right": 2,
        "Justified": 4
    }[alignment]

    story = []

    # Add image with size adjustment
    image_sizes = {
        "Small": (200, 200),
        "Medium": (400, 400),
        "Large": (600, 600)
    }
    img = RLImage(media_path, width=image_sizes[image_size][0], height=image_sizes[image_size][1])
    story.append(img)
    story.append(Spacer(1, 12))

    # Add plain text output
    text = Paragraph(plain_text, styles["Normal"])
    story.append(text)

    doc.build(story)
    return filename

def generate_docx(media_path, plain_text, font_size, line_spacing, alignment, image_size):
    """Generates a DOCX document."""
    filename = f"output_{uuid.uuid4()}.docx"
    doc = docx.Document()

    # Add image with size adjustment
    image_sizes = {
        "Small": docx.shared.Inches(2),
        "Medium": docx.shared.Inches(4),
        "Large": docx.shared.Inches(6)
    }
    doc.add_picture(media_path, width=image_sizes[image_size])
    doc.add_paragraph()

    # Add plain text output
    paragraph = doc.add_paragraph()
    paragraph.paragraph_format.line_spacing = line_spacing
    paragraph.paragraph_format.alignment = {
        "Left": WD_ALIGN_PARAGRAPH.LEFT,
        "Center": WD_ALIGN_PARAGRAPH.CENTER,
        "Right": WD_ALIGN_PARAGRAPH.RIGHT,
        "Justified": WD_ALIGN_PARAGRAPH.JUSTIFY
    }[alignment]
    run = paragraph.add_run(plain_text)
    run.font.size = docx.shared.Pt(int(font_size))

    doc.save(filename)
    return filename

# CSS for output styling
css = """
  #output {
    height: 500px;
    overflow: auto;
    border: 1px solid #ccc;
  }
.submit-btn {
    background-color: #cf3434  !important;
    color: white !important;
}
.submit-btn:hover {
    background-color: #ff2323 !important;
}
.download-btn {
    background-color: #35a6d6 !important;
    color: white !important;
}
.download-btn:hover {
    background-color: #22bcff !important;
}
"""

# Gradio app setup
with gr.Blocks(css=css) as demo:
    gr.Markdown("# ChemQwen Chemical Identifier")

    with gr.Tab(label="Image Input"):

        with gr.Row():
            with gr.Column():
                model_choice = gr.Dropdown(
                    label="Model Selection",
                    choices=list(MODEL_OPTIONS.keys()),
                    value="ChemQwen"
                )
                input_media = gr.File(
                    label="Upload Image", type="filepath"
                )
                text_input = gr.Textbox(label="Question", placeholder="Ask a question about the image...")
                submit_btn = gr.Button(value="Submit", elem_classes="submit-btn")

            with gr.Column():
                output_text = gr.Textbox(label="Output Text", lines=10)
                plain_text_output = gr.Textbox(label="Standardized Plain Text", lines=10)

        submit_btn.click(
            qwen_inference, [model_choice, input_media, text_input], [output_text]
        ).then(
            lambda output_text: format_plain_text(output_text), [output_text], [plain_text_output]
        )

        # Add examples directly usable by clicking
        with gr.Row():
            with gr.Column():
                line_spacing = gr.Dropdown(
                    choices=[0.5, 1.0, 1.15, 1.5, 2.0, 2.5, 3.0],
                    value=1.5,
                    label="Line Spacing"
                )
                font_size = gr.Dropdown(
                    choices=["8", "10", "12", "14", "16", "18", "20", "22", "24"],
                    value="18",
                    label="Font Size"
                )
                alignment = gr.Dropdown(
                    choices=["Left", "Center", "Right", "Justified"],
                    value="Justified",
                    label="Text Alignment"
                )
                image_size = gr.Dropdown(
                    choices=["Small", "Medium", "Large"],
                    value="Small",
                    label="Image Size"
                )
                file_format = gr.Radio(["pdf", "docx"], label="File Format", value="pdf")
                get_document_btn = gr.Button(value="Get Document", elem_classes="download-btn")

        get_document_btn.click(
            generate_document, [input_media, output_text, file_format, font_size, line_spacing, alignment, image_size], gr.File(label="Download Document")
        )

demo.launch(debug=True)

Intended Use

ChemQwen-vL is designed for applications in the field of cheminformatics and chemical research:

  1. Chemical Structure Recognition:

    • Generating precise International Chemical Identifiers (InChI) from chemical images.
    • Providing detailed descriptions of molecular structures based on visual inputs.
  2. Scientific Research and Education:

    • Supporting researchers and students by offering automated analysis of chemical diagrams and visual materials.
  3. Integration with Laboratory Systems:

    • Assisting in automation by integrating with robotic systems for chemical analysis, reporting, and data generation.
  4. Multilingual Chemical Data Analysis:

    • Supporting international collaborations with multilingual recognition of chemical texts and images.
  5. Advanced Question Answering:

    • Enabling chemistry-related visual question answering and reasoning for educational tools, publications, and research platforms.

Limitations

  1. Accuracy for Uncommon or Complex Structures:

    • May struggle with highly complex or unconventional chemical diagrams not adhering to standard formats.
  2. Dependency on Input Quality:

    • Performance can degrade with low-resolution, poorly scanned, or incomplete images.
  3. Limited Domain Knowledge:

    • While proficient in chemical component identification, the model might lack domain-specific context in specialized subfields of chemistry.
  4. Processing Speed for Large Data Sets:

    • Performance may slow down when processing very large datasets or videos of extended duration.
  5. Hardware Requirements:

    • Requires high computational resources, including GPUs, for optimal performance during inference.
  6. Language and Symbol Constraints:

    • Though multilingual, rare or specialized symbols and annotations may not always be recognized accurately.
  7. No Real-Time Laboratory Decisions:

    • While it integrates with automated systems, real-time critical decisions still require human validation.

Как запустить

На своей GPU в ailist. Цена — по текущим предложениям провайдеров

GPU в ailist

Универсальный рантайм · transformers

Можно запустить

Подбираем GPU…

Класс архитектуры
Qwen2VLForConditionalGeneration
Ревизия весов
b5e1217

0 моделей