$ python hours.py image.jpg
{
"day_hours": [
{
"day": "Mon - Fri",
"hours": "7 AM - 5 PM"
},
{
"day": "Saturday",
"hours": "9 AM - 6 PM"
},
{
"day": "Sunday",
"hours": "Closed"
}
]
}
Last active
August 21, 2024 02:55
-
-
Save wiseman/71571f12e4961faab7425f32a6afe74e to your computer and use it in GitHub Desktop.
Get store hours from images
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import argparse | |
import base64 | |
import instructor | |
import openai | |
import pydantic | |
class DayHours(pydantic.BaseModel): | |
day: str | |
hours: str | |
class StoreHours(pydantic.BaseModel): | |
day_hours: list[DayHours] | |
def extract_store_hours(client, image_path: str) -> StoreHours: | |
with open(image_path, "rb") as f: | |
base64_image = base64.b64encode(f.read()).decode("utf-8") | |
return client.chat.completions.create( | |
model="gpt-4o", | |
response_model=StoreHours, | |
messages=[ | |
{ | |
"role": "user", | |
"content": [ | |
{ | |
"type": "text", | |
"text": ( | |
"Extract the store hours from the sign in the " | |
"image below. The store hours are typically displayed in " | |
"a table." | |
), | |
}, | |
{ | |
"type": "image_url", | |
"image_url": {"url": f"data:image/jpeg;base64,{base64_image}"}, | |
}, | |
], | |
} | |
], | |
) | |
def main(): | |
parser = argparse.ArgumentParser() | |
parser.add_argument("image_path", type=str) | |
args = parser.parse_args() | |
client = instructor.from_openai(openai.OpenAI(), mode=instructor.Mode.MD_JSON) | |
store_hours = extract_store_hours(client, args.image_path) | |
print(store_hours.model_dump_json(indent=2)) | |
if __name__ == "__main__": | |
main() |
Author
wiseman
commented
Aug 15, 2024
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment