SkalskiP commited on
Commit
8274479
β€’
1 Parent(s): 73b6ea6

:tada: initial commit

Browse files
Files changed (4) hide show
  1. .gitignore +2 -0
  2. README.md +2 -2
  3. app.py +117 -0
  4. requirements.txt +4 -0
.gitignore ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ .idea/
2
+ venv/
README.md CHANGED
@@ -1,10 +1,10 @@
1
  ---
2
  title: HotDogGPT
3
- emoji: πŸ“‰
4
  colorFrom: blue
5
  colorTo: yellow
6
  sdk: gradio
7
- sdk_version: 4.1.1
8
  app_file: app.py
9
  pinned: false
10
  ---
 
1
  ---
2
  title: HotDogGPT
3
+ emoji: 🌭
4
  colorFrom: blue
5
  colorTo: yellow
6
  sdk: gradio
7
+ sdk_version: 3.50.2
8
  app_file: app.py
9
  pinned: false
10
  ---
app.py ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import base64
2
+
3
+ import cv2
4
+ import gradio as gr
5
+ import numpy as np
6
+ import requests
7
+
8
+ MARKDOWN = """
9
+ # HotDogGPT πŸ’¬ + 🌭
10
+
11
+ HotDogGPT is OpenAI Vision API experiment reproducing the famous
12
+ [Hot Dog, Not Hot Dog](https://www.youtube.com/watch?v=ACmydtFDTGs) app from Silicon
13
+ Valley.
14
+
15
+ <p align="center">
16
+ <img width="600" src="https://miro.medium.com/v2/resize:fit:650/1*VrpXE1hE4rO1roK0laOd7g.png" alt="hotdog">
17
+ </p>
18
+
19
+ Visit [awesome-openai-vision-api-experiments](https://github.com/roboflow/awesome-openai-vision-api-experiments)
20
+ repository to find more OpenAI Vision API experiments or contribute your own.
21
+ """
22
+ API_URL = "https://api.openai.com/v1/chat/completions"
23
+ CLASSES = ["🌭 Hot Dog", "❌ Not Hot Dog"]
24
+
25
+
26
+ def preprocess_image(image: np.ndarray) -> np.ndarray:
27
+ image = np.fliplr(image)
28
+ return cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
29
+
30
+
31
+ def encode_image_to_base64(image: np.ndarray) -> str:
32
+ success, buffer = cv2.imencode('.jpg', image)
33
+ if not success:
34
+ raise ValueError("Could not encode image to JPEG format.")
35
+
36
+ encoded_image = base64.b64encode(buffer).decode('utf-8')
37
+ return encoded_image
38
+
39
+
40
+ def compose_payload(image: np.ndarray, prompt: str) -> dict:
41
+ base64_image = encode_image_to_base64(image)
42
+ return {
43
+ "model": "gpt-4-vision-preview",
44
+ "messages": [
45
+ {
46
+ "role": "user",
47
+ "content": [
48
+ {
49
+ "type": "text",
50
+ "text": prompt
51
+ },
52
+ {
53
+ "type": "image_url",
54
+ "image_url": {
55
+ "url": f"data:image/jpeg;base64,{base64_image}"
56
+ }
57
+ }
58
+ ]
59
+ }
60
+ ],
61
+ "max_tokens": 300
62
+ }
63
+
64
+
65
+ def compose_classification_prompt(classes: list) -> str:
66
+ return (f"What is in the image? Return the class of the object in the image. Here "
67
+ f"are the classes: {', '.join(classes)}. You can only return one class "
68
+ f"from that list.")
69
+
70
+
71
+ def compose_headers(api_key: str) -> dict:
72
+ return {
73
+ "Content-Type": "application/json",
74
+ "Authorization": f"Bearer {api_key}"
75
+ }
76
+
77
+
78
+ def prompt_image(api_key: str, image: np.ndarray, prompt: str) -> str:
79
+ headers = compose_headers(api_key=api_key)
80
+ payload = compose_payload(image=image, prompt=prompt)
81
+ response = requests.post(url=API_URL, headers=headers, json=payload).json()
82
+
83
+ if 'error' in response:
84
+ raise ValueError(response['error']['message'])
85
+ return response['choices'][0]['message']['content']
86
+
87
+
88
+ def classify_image(api_key: str, image: np.ndarray) -> str:
89
+ if not api_key:
90
+ raise ValueError(
91
+ "API_KEY is not set. "
92
+ "Please follow the instructions in the README to set it up.")
93
+ image = preprocess_image(image=image)
94
+ prompt = compose_classification_prompt(classes=CLASSES)
95
+ response = prompt_image(api_key=api_key, image=image, prompt=prompt)
96
+ return response
97
+
98
+
99
+ with gr.Blocks() as demo:
100
+ gr.Markdown(MARKDOWN)
101
+ api_key_textbox = gr.Textbox(
102
+ label="πŸ”‘ OpenAI API", type="password")
103
+
104
+ with gr.TabItem("Basic"):
105
+ with gr.Column():
106
+ input_image = gr.Image(
107
+ image_mode='RGB', type='numpy', height=500)
108
+ output_text = gr.Textbox(
109
+ label="Output")
110
+ submit_button = gr.Button("Submit")
111
+
112
+ submit_button.click(
113
+ fn=classify_image,
114
+ inputs=[api_key_textbox, input_image],
115
+ outputs=output_text)
116
+
117
+ demo.launch(debug=False, show_error=True)
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ numpy
2
+ opencv-python
3
+ requests
4
+ gradio==3.50.2