Img-label / App.py
rayochoajr's picture
Create App.py
36c97d5 verified
raw
history blame
No virus
3.19 kB
import gradio as gr
import os
import shutil
import hashlib
import subprocess
import pandas as pd
from PIL import Image
from datetime import datetime
import io
import base64
import requests
import json
import logging
# Hardcoded Values
API_KEY = "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"
IMAGE_FOLDER = "./Images"
THUMBS_UP_FOLDER = os.path.join(IMAGE_FOLDER, "Thumbs_Up")
THUMBS_DOWN_FOLDER = os.path.join(IMAGE_FOLDER, "Thumbs_Down")
BACKUP_FOLDER = "Backup_Scripts"
ALLOWED_EXTENSIONS = ['.jpg', '.jpeg', '.png', '.gif', '.bmp']
LOGGING_LEVEL = logging.INFO
API_URL = "https://api.openai.com/v1/chat/completions"
# Setup logging
logging.basicConfig(level=LOGGING_LEVEL)
# Ensure necessary directories exist
os.makedirs(IMAGE_FOLDER, exist_ok=True)
os.makedirs(THUMBS_UP_FOLDER, exist_ok=True)
os.makedirs(THUMBS_DOWN_FOLDER, exist_ok=True)
os.makedirs(BACKUP_FOLDER, exist_ok=True)
def load_gallery(folder):
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())
def get_image_description(image, custom_prompt):
if not custom_prompt.strip():
custom_prompt = "Describe this image"
headers = {"Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json"}
payload = json.dumps({
"model": "gpt-4-vision-preview",
"messages": [{
"role": "user",
"content": [{"type": "text", "text": custom_prompt},
{"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{encode_image(image)}"}}
]
}],
"max_tokens": 300
})
response = requests.post(API_URL, headers=headers, data=payload)
return json.loads(response.text).get('choices', [])[0].get('message', {}).get('content', '')
def encode_image(image):
with io.BytesIO() as image_bytes:
image.convert('RGB').save(image_bytes, format='JPEG')
return base64.b64encode(image_bytes.getvalue()).decode('utf-8')
def save_image_description(image_path, description):
text_file_path = f"{os.path.splitext(image_path)[0]}.txt"
with open(text_file_path, 'w') as file:
file.write(description)
with gr.Blocks() as app:
with gr.Row():
upload_btn = gr.File(label="Upload Images", type="binary", file_count='multiple')
gallery = gr.Gallery(label="Uploaded Images Gallery")
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)
with gr.Accordion("Training Data"):
details_df = gr.Dataframe()
thumbs_up_gallery = gr.Gallery(value=load_gallery(THUMBS_UP_FOLDER), label="Thumbs Up Gallery")
thumbs_down_gallery = gr.Gallery(value=load_gallery(THUMBS_DOWN_FOLDER), label="Thumbs Down Gallery")
refresh_btn = gr.Button("Refresh")
refresh_btn.click(lambda: details_df.update(load_gallery(IMAGE_FOLDER)), inputs=[], outputs=[details_df, thumbs_up_gallery, thumbs_down_gallery])
app.launch()