from js import document, console, window, Uint8Array, File
from pyodide import create_proxy
import asyncio
import io
from PIL import Image
from pyodide.http import pyfetch, FetchResponse
import base64
async def browse_display(event):
console.log(event.target.value) # returns html element that triggers an event, “value” returns the value of the value attribute of text field
file_list = event.target.files # a list of files selected by the user
first_item = file_list.item(0)
old_image = document.getElementById("output_upload").querySelector("img")
if old_image:
old_image.remove()
new_image = document.createElement("img")
new_image.src = window.URL.createObjectURL(first_item)
new_image.width = 200
new_image.height = 100
document.getElementById("output_upload").appendChild(new_image)
array_buf = Uint8Array.new(await first_item.arrayBuffer()) # data arraybuffer (unsigned) from image
# convert to bytearray
bytes_list = bytearray(array_buf)
img_bytes = io.BytesIO(bytes_list)
my_img = Image.open(img_bytes)
async def image_to_text(image_data):
api_key = "XXXXXXXXXXXXXXX"
response = await pyfetch(
f"https://api.ocr.space/parse/image",
method = "POST",
headers={'apikey': api_key},
files={'image': ('image', image_data)}
)
data_dict = await response.json()
print(data_dict)
await image_to_text(my_img)
upload_img = create_proxy(browse_display)
print(upload_img)
document.getElementById(“image-upload”).addEventListener(“change”, upload_img)