Skip to content

Instantly share code, notes, and snippets.

@netoxico
Forked from wiseman/example.md
Created August 21, 2024 02:55
Show Gist options
  • Save netoxico/90e2d3d3bcf4b87b8e3c58938520b0ac to your computer and use it in GitHub Desktop.
Save netoxico/90e2d3d3bcf4b87b8e3c58938520b0ac to your computer and use it in GitHub Desktop.
Get store hours from images
$ 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"
    }
  ]
}
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()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment