File size: 1,433 Bytes
37b9a66
 
 
 
 
 
 
 
 
03c245b
 
 
 
 
 
37b9a66
03c245b
37b9a66
 
 
 
 
03c245b
37b9a66
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import base64
from openai import OpenAI
import os

# Function to encode the image
def encode_image(image_path):
    assert os.path.exists(image_path), "The image file does not exist."
    with open(image_path, "rb") as image_file:
        return base64.b64encode(image_file.read()).decode('utf-8')
    
def encode_image_from_uploaded_file(image):
    # Convert image to bytes
    assert image is not None, "No image uploaded."
    image_bytes = image.read()
    return base64.b64encode(image_bytes).decode('utf-8')

def transcribe_image(image_file):
    """Transcribe handwritten text from an image using OCR."""
    # Initialize the OpenAI client
    client = OpenAI()

    # Encoding the image
    base64_image = encode_image_from_uploaded_file(image_file)


    # Preparing the API call
    response = client.chat.completions.create(
        model="gpt-4o-mini",
        messages=[
            {
                "role": "user",
                "content": [
                    {"type": "text", "text": "Please transcribe the handwritten text in this image. Return only the text content."},
                    {
                        "type": "image_url",
                        "image_url": {"url": f"data:image/jpeg;base64,{base64_image}"}
                    }
                ]
            }
        ],
        max_tokens=300
    )
    
    transcribed_text = response.choices[0].message.content

    return transcribed_text