SkalskiP commited on
Commit
0e0b22e
1 Parent(s): 118e0ca

:tada: initial commit

Browse files
Files changed (4) hide show
  1. .gitignore +2 -0
  2. README.md +4 -4
  3. app.py +122 -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: WebcamGPT
3
- emoji: 🏢
4
- colorFrom: red
5
- colorTo: gray
6
  sdk: gradio
7
- sdk_version: 4.1.1
8
  app_file: app.py
9
  pinned: false
10
  ---
 
1
  ---
2
  title: WebcamGPT
3
+ emoji: 💬📸
4
+ colorFrom: pink
5
+ colorTo: purple
6
  sdk: gradio
7
+ sdk_version: 3.50.2
8
  app_file: app.py
9
  pinned: false
10
  ---
app.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import base64
2
+ import os
3
+ import uuid
4
+
5
+ import cv2
6
+ import gradio as gr
7
+ import numpy as np
8
+ import requests
9
+
10
+ MARKDOWN = """
11
+ # WebcamGPT 💬 + 📸
12
+
13
+ webcamGPT is a tool that allows you to chat with video using OpenAI Vision API.
14
+
15
+ Visit [awesome-openai-vision-api-experiments](https://github.com/roboflow/awesome-openai-vision-api-experiments)
16
+ repository to find more OpenAI Vision API experiments or contribute your own.
17
+ """
18
+ AVATARS = (
19
+ "https://media.roboflow.com/spaces/roboflow_raccoon_full.png",
20
+ "https://media.roboflow.com/spaces/openai-white-logomark.png"
21
+ )
22
+ IMAGE_CACHE_DIRECTORY = "data"
23
+ API_URL = "https://api.openai.com/v1/chat/completions"
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_headers(api_key: str) -> dict:
66
+ return {
67
+ "Content-Type": "application/json",
68
+ "Authorization": f"Bearer {api_key}"
69
+ }
70
+
71
+
72
+ def prompt_image(api_key: str, image: np.ndarray, prompt: str) -> str:
73
+ headers = compose_headers(api_key=api_key)
74
+ payload = compose_payload(image=image, prompt=prompt)
75
+ response = requests.post(url=API_URL, headers=headers, json=payload).json()
76
+
77
+ if 'error' in response:
78
+ raise ValueError(response['error']['message'])
79
+ return response['choices'][0]['message']['content']
80
+
81
+
82
+ def cache_image(image: np.ndarray) -> str:
83
+ image_filename = f"{uuid.uuid4()}.jpeg"
84
+ os.makedirs(IMAGE_CACHE_DIRECTORY, exist_ok=True)
85
+ image_path = os.path.join(IMAGE_CACHE_DIRECTORY, image_filename)
86
+ cv2.imwrite(image_path, image)
87
+ return image_path
88
+
89
+
90
+ def respond(api_key: str, image: np.ndarray, prompt: str, chat_history):
91
+ if not api_key:
92
+ raise ValueError(
93
+ "API_KEY is not set. "
94
+ "Please follow the instructions in the README to set it up.")
95
+
96
+ image = preprocess_image(image=image)
97
+ cached_image_path = cache_image(image)
98
+ response = prompt_image(api_key=api_key, image=image, prompt=prompt)
99
+ chat_history.append(((cached_image_path,), None))
100
+ chat_history.append((prompt, response))
101
+ return "", chat_history
102
+
103
+
104
+ with gr.Blocks() as demo:
105
+ gr.Markdown(MARKDOWN)
106
+ with gr.Row():
107
+ webcam = gr.Image(source="webcam", streaming=True)
108
+ with gr.Column():
109
+ api_key_textbox = gr.Textbox(
110
+ label="OpenAI API KEY", type="password")
111
+ chatbot = gr.Chatbot(
112
+ height=500, bubble_full_width=False, avatar_images=AVATARS)
113
+ message_textbox = gr.Textbox()
114
+ clear_button = gr.ClearButton([message_textbox, chatbot])
115
+
116
+ message_textbox.submit(
117
+ fn=respond,
118
+ inputs=[api_key_textbox, webcam, message_textbox, chatbot],
119
+ outputs=[message_textbox, chatbot]
120
+ )
121
+
122
+ 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