File size: 3,582 Bytes
f296d53
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
import streamlit as st
import torch
import torch
from torchvision import transforms
from PIL import Image
import openai

# Load CLIP model
clip_model, preprocess = openai.load("clip-vit-base-patch32")

# Function to preprocess images for CLIP
def preprocess_image(image_path):
    image = Image.open(image_path).convert("RGB")
    image = preprocess(image)
    return image.unsqueeze(0)
import openai
import timm
import base64
import numpy as np
from PIL import Image, ImageEnhance
from torchvision import transforms
from io import BytesIO

# Load models
device = "cuda" if torch.cuda.is_available() else "cpu"
clip_model, clip_preprocess = clip.load("ViT-B/32", device=device)

aesthetic_model = timm.create_model('hf_hub:timm/convnext_base', pretrained=True, num_classes=1)
aesthetic_model.eval()

# Image Preprocessing
transform = transforms.Compose([
    transforms.Resize((224, 224)),
    transforms.ToTensor(),
    transforms.Normalize(mean=[0.5], std=[0.5])
])

# Function: Predict Aesthetic Score
def predict_aesthetic_score(image):
    image = transform(image).unsqueeze(0)
    with torch.no_grad():
        score = aesthetic_model(image).item()
    return round(score, 2)

# Function: Encode image for GPT-4 Vision
def encode_image(image):
    buffered = BytesIO()
    image.save(buffered, format="JPEG")
    return base64.b64encode(buffered.getvalue()).decode("utf-8")

# Function: Get GPT-4 Vision Feedback
def analyze_image_with_gpt4(image, prompt):
    encoded_image = encode_image(image)
    try:
        response = openai.ChatCompletion.create(
            model="gpt-4-vision-preview",
            messages=[
                {"role": "system", "content": "You are an expert image critic analyzing AI-generated images."},
                {"role": "user", "content": [
                    {"type": "text", "text": prompt},
                    {"type": "image", "image_url": f"data:image/jpeg;base64,{encoded_image}"}
                ]}
            ],
            max_tokens=500
        )
        return response["choices"][0]["message"]["content"]
    except Exception as e:
        return f"GPT-4 Error: {e}"

# Function: AI Auto-Enhance Image
def auto_enhance_image(image, feedback):
    if "dim lighting" in feedback.lower():
        enhancer = ImageEnhance.Brightness(image)
        image = enhancer.enhance(1.2)  # Increase brightness by 20%
    if "low contrast" in feedback.lower():
        enhancer = ImageEnhance.Contrast(image)
        image = enhancer.enhance(1.3)
    if "blurry" in feedback.lower():
        enhancer = ImageEnhance.Sharpness(image)
        image = enhancer.enhance(2.0)
    return image

# Streamlit UI
st.title("AI-Powered Image Evaluator & Enhancer")

uploaded_file = st.file_uploader("Upload an Image", type=["jpg", "png"])
if uploaded_file:
    image = Image.open(uploaded_file)
    st.image(image, caption="Uploaded Image", use_column_width=True)

    # Aesthetic Scoring
    aesthetic_score = predict_aesthetic_score(image)
    st.write(f"**Aesthetic Score:** {aesthetic_score}/10")

    # GPT-4 Feedback
    prompt = "Evaluate this image. Does it match the description 'A futuristic cyberpunk city with neon lights and rain'? Analyze composition, color, and realism."
    feedback = analyze_image_with_gpt4(image, prompt)
    st.write("**AI Feedback:**", feedback)

    # Auto-Enhancement Option
    if st.button("Auto-Enhance Image"):
        enhanced_image = auto_enhance_image(image, feedback)
        st.image(enhanced_image, caption="Enhanced Image", use_column_width=True)
        st.success("Image enhanced successfully!")