File size: 4,879 Bytes
e73ce34
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
from __future__ import annotations

import os

import cv2
from DECIMER import predict_SMILES
from decimer_segmentation import segment_chemical_structures_from_file
from PIL import Image


def convert_image(path: str) -> str:
    """Convert a GIF image to PNG format, resize, and place on a white.

    background.

    Args:
        path (str): The path to the GIF image file.

    Returns:
        str: The path of the converted and processed PNG image file.
    """
    # Open the image and convert to RGBA
    img = Image.open(path).convert("RGBA")

    # Calculate new dimensions for resizing
    new_size = (int(float(img.width) * 2), int(float(img.height) * 2))

    # Resize the image using Lanczos resampling
    resized_image = img.resize(new_size, resample=Image.LANCZOS)

    # Calculate background size
    background_size = (
        int(float(resized_image.width) * 2),
        int(float(resized_image.height) * 2),
    )

    # Create a new image with white background
    new_im = Image.new(resized_image.mode, background_size, "white")

    # Calculate position to paste the resized image in the center
    paste_pos = (
        int((new_im.size[0] - resized_image.size[0]) / 2),
        int((new_im.size[1] - resized_image.size[1]) / 2),
    )

    # Paste the resized image onto the new background
    new_im.paste(resized_image, paste_pos)

    # Save the processed image in PNG format
    new_path = path.replace("gif", "png")
    new_im.save(new_path, optimize=True, quality=100)

    return new_path


def get_segments(path: str) -> tuple:
    """Takes an image file path and returns a set of paths and image names of.

    segmented images.

    Args:
        input_path (str): the path of an image.

    Returns:
        image_name (str): image file name.
        segments (list): a set of segmented images.
    """

    image_name = os.path.split(path)[1]
    if image_name[-3:].lower() == "gif":
        new_path = convert_image(path)
        segments = segment_chemical_structures_from_file(new_path)
        return image_name, segments
    else:
        segments = segment_chemical_structures_from_file(path)
        return image_name, segments


def get_predicted_segments(path: str, hand_drawn: bool = False) -> str:
    """Get predicted SMILES representations for segments within an image.

    This function takes an image path, extracts segments, predicts SMILES representations
    for each segment, and returns a concatenated string of predicted SMILES.

    Args:
        path (str): Path to the input image file.
        hand_drawn (bool): Whether to use hand-drawn model for prediction. Defaults to False.

    Returns:
        str: Predicted SMILES representations joined by '.' if segments are detected,
             otherwise returns a single predicted SMILES for the whole image.
    """
    smiles_predicted = []
    image_name, segments = get_segments(path)

    if len(segments) == 0:
        smiles = predict_SMILES(path, confidence=False, hand_drawn=hand_drawn)
        return smiles
    else:
        for segment_index in range(len(segments)):
            segmentname = f"{image_name[:-5]}_{segment_index}.png"
            segment_path = os.path.join(segmentname)
            cv2.imwrite(segment_path, segments[segment_index])
            smiles = predict_SMILES(
                segment_path, confidence=False, hand_drawn=hand_drawn
            )
            smiles_predicted.append(smiles)
            os.remove(segment_path)
        return ".".join(smiles_predicted)


def get_predicted_segments_from_file(
    content: any, filename: str, hand_drawn: bool = False
) -> str:
    """Takes an image file content and filename, saves it temporarily, and returns SMILES prediction.

    If the image dimensions are below 500 pixels, uses predict_SMILES directly.
    Otherwise, uses segmentation approach.

    Args:
        content (any): The image file content.
        filename (str): The filename to save the content to.
        hand_drawn (bool): Whether to use hand-drawn model for prediction. Defaults to False.

    Returns:
        str: Predicted SMILES string.
    """

    # Write the content to file and ensure it's closed
    with open(filename, "wb") as f:
        f.write(content)

    try:
        # Check image dimensions
        img = Image.open(filename)
        width, height = img.size
        img.close()  # Close the image to free resources

        # If image is small (below 500 pixels in either dimension), use direct prediction
        if width < 500 or height < 500:
            smiles = predict_SMILES(filename, confidence=False, hand_drawn=hand_drawn)
        else:
            smiles = get_predicted_segments(filename, hand_drawn=hand_drawn)

        return smiles
    finally:
        # Ensure the temporary file is always removed
        if os.path.exists(filename):
            os.remove(filename)