rayochoajr commited on
Commit
36c97d5
1 Parent(s): 24c66ec

Create App.py

Browse files
Files changed (1) hide show
  1. App.py +78 -0
App.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+ import shutil
4
+ import hashlib
5
+ import subprocess
6
+ import pandas as pd
7
+ from PIL import Image
8
+ from datetime import datetime
9
+ import io
10
+ import base64
11
+ import requests
12
+ import json
13
+ import logging
14
+
15
+ # Hardcoded Values
16
+ API_KEY = "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"
17
+ IMAGE_FOLDER = "./Images"
18
+ THUMBS_UP_FOLDER = os.path.join(IMAGE_FOLDER, "Thumbs_Up")
19
+ THUMBS_DOWN_FOLDER = os.path.join(IMAGE_FOLDER, "Thumbs_Down")
20
+ BACKUP_FOLDER = "Backup_Scripts"
21
+ ALLOWED_EXTENSIONS = ['.jpg', '.jpeg', '.png', '.gif', '.bmp']
22
+ LOGGING_LEVEL = logging.INFO
23
+ API_URL = "https://api.openai.com/v1/chat/completions"
24
+
25
+ # Setup logging
26
+ logging.basicConfig(level=LOGGING_LEVEL)
27
+
28
+ # Ensure necessary directories exist
29
+ os.makedirs(IMAGE_FOLDER, exist_ok=True)
30
+ os.makedirs(THUMBS_UP_FOLDER, exist_ok=True)
31
+ os.makedirs(THUMBS_DOWN_FOLDER, exist_ok=True)
32
+ os.makedirs(BACKUP_FOLDER, exist_ok=True)
33
+
34
+ def load_gallery(folder):
35
+ return sorted([os.path.join(folder, f) for f in os.listdir(folder) if os.path.splitext(f)[1].lower() in ALLOWED_EXTENSIONS], key=lambda x: os.path.basename(x).lower())
36
+
37
+ def get_image_description(image, custom_prompt):
38
+ if not custom_prompt.strip():
39
+ custom_prompt = "Describe this image"
40
+ headers = {"Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json"}
41
+ payload = json.dumps({
42
+ "model": "gpt-4-vision-preview",
43
+ "messages": [{
44
+ "role": "user",
45
+ "content": [{"type": "text", "text": custom_prompt},
46
+ {"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{encode_image(image)}"}}
47
+ ]
48
+ }],
49
+ "max_tokens": 300
50
+ })
51
+ response = requests.post(API_URL, headers=headers, data=payload)
52
+ return json.loads(response.text).get('choices', [])[0].get('message', {}).get('content', '')
53
+
54
+ def encode_image(image):
55
+ with io.BytesIO() as image_bytes:
56
+ image.convert('RGB').save(image_bytes, format='JPEG')
57
+ return base64.b64encode(image_bytes.getvalue()).decode('utf-8')
58
+
59
+ def save_image_description(image_path, description):
60
+ text_file_path = f"{os.path.splitext(image_path)[0]}.txt"
61
+ with open(text_file_path, 'w') as file:
62
+ file.write(description)
63
+
64
+ with gr.Blocks() as app:
65
+ with gr.Row():
66
+ upload_btn = gr.File(label="Upload Images", type="binary", file_count='multiple')
67
+ gallery = gr.Gallery(label="Uploaded Images Gallery")
68
+ upload_btn.change(fn=lambda files: [save_image_description(file.name, get_image_description(Image.open(io.BytesIO(file)), "")) for file in files if file.name.lower().endswith(tuple(ALLOWED_EXTENSIONS))], inputs=upload_btn, outputs=gallery)
69
+
70
+ with gr.Accordion("Training Data"):
71
+ details_df = gr.Dataframe()
72
+ thumbs_up_gallery = gr.Gallery(value=load_gallery(THUMBS_UP_FOLDER), label="Thumbs Up Gallery")
73
+ thumbs_down_gallery = gr.Gallery(value=load_gallery(THUMBS_DOWN_FOLDER), label="Thumbs Down Gallery")
74
+
75
+ refresh_btn = gr.Button("Refresh")
76
+ refresh_btn.click(lambda: details_df.update(load_gallery(IMAGE_FOLDER)), inputs=[], outputs=[details_df, thumbs_up_gallery, thumbs_down_gallery])
77
+
78
+ app.launch()