Spaces:
Runtime error
Runtime error
Update app.py
#2
by Futuretop - opened
app.py
CHANGED
|
@@ -1,154 +1,45 @@
|
|
| 1 |
-
from PIL import Image
|
| 2 |
-
from transformers import BlipProcessor, BlipForConditionalGeneration
|
| 3 |
-
import numpy as np
|
| 4 |
-
import cv2
|
| 5 |
-
from deepface import DeepFace
|
| 6 |
import gradio as gr
|
| 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 |
-
age = analysis[0]['age']
|
| 52 |
-
gender = analysis[0]['gender']
|
| 53 |
-
emotion = analysis[0]['dominant_emotion']
|
| 54 |
-
|
| 55 |
-
if age < 13:
|
| 56 |
-
age_group = "child"
|
| 57 |
-
elif age < 20:
|
| 58 |
-
age_group = "teen"
|
| 59 |
-
elif age < 60:
|
| 60 |
-
age_group = "adult"
|
| 61 |
-
else:
|
| 62 |
-
age_group = "senior"
|
| 63 |
-
|
| 64 |
-
face_infos.append({
|
| 65 |
-
"age": age,
|
| 66 |
-
"gender": gender,
|
| 67 |
-
"age_group": age_group,
|
| 68 |
-
"emotion": emotion
|
| 69 |
-
})
|
| 70 |
-
except Exception:
|
| 71 |
-
continue
|
| 72 |
-
|
| 73 |
-
# Summary stats
|
| 74 |
-
num_faces = len(face_infos)
|
| 75 |
-
gender_counts = {"Man": 0, "Woman": 0}
|
| 76 |
-
age_summary = {}
|
| 77 |
-
emotion_summary = {}
|
| 78 |
-
|
| 79 |
-
for face in face_infos:
|
| 80 |
-
gender = face['gender']
|
| 81 |
-
age_group = face['age_group']
|
| 82 |
-
emotion = face['emotion']
|
| 83 |
-
|
| 84 |
-
gender_counts[gender] += 1
|
| 85 |
-
age_summary[age_group] = age_summary.get(age_group, 0) + 1
|
| 86 |
-
emotion_summary[emotion] = emotion_summary.get(emotion, 0) + 1
|
| 87 |
-
|
| 88 |
-
# Clothing info from caption
|
| 89 |
-
colors, patterns, items = extract_clothing(caption)
|
| 90 |
-
|
| 91 |
-
# Generate 15 sentences
|
| 92 |
-
sentences = []
|
| 93 |
-
sentences.append(f"According to the BLIP model, the scene can be described as: \"{caption}\".")
|
| 94 |
-
sentences.append(f"The image contains {num_faces} visible face(s) detected using DeepFace (RetinaFace backend).")
|
| 95 |
-
|
| 96 |
-
gender_desc = []
|
| 97 |
-
if gender_counts["Man"] > 0:
|
| 98 |
-
gender_desc.append(f"{gender_counts['Man']} male(s)")
|
| 99 |
-
if gender_counts["Woman"] > 0:
|
| 100 |
-
gender_desc.append(f"{gender_counts['Woman']} female(s)")
|
| 101 |
-
if gender_desc:
|
| 102 |
-
sentences.append("Gender distribution shows " + " and ".join(gender_desc) + ".")
|
| 103 |
-
else:
|
| 104 |
-
sentences.append("Gender analysis was inconclusive.")
|
| 105 |
-
|
| 106 |
-
if age_summary:
|
| 107 |
-
age_list = [f"{count} {group}(s)" for group, count in age_summary.items()]
|
| 108 |
-
sentences.append("Age groups represented include " + ", ".join(age_list) + ".")
|
| 109 |
-
else:
|
| 110 |
-
sentences.append("No conclusive age groupings found.")
|
| 111 |
-
|
| 112 |
-
if emotion_summary:
|
| 113 |
-
emo_list = [f"{count} showing {emo}" for emo, count in emotion_summary.items()]
|
| 114 |
-
sentences.append("Facial expressions include " + ", ".join(emo_list) + ".")
|
| 115 |
-
else:
|
| 116 |
-
sentences.append("Emotion detection yielded limited results.")
|
| 117 |
-
|
| 118 |
-
if colors or patterns or items:
|
| 119 |
-
cloth_parts = []
|
| 120 |
-
if colors:
|
| 121 |
-
cloth_parts.append(f"colors like {', '.join(colors)}")
|
| 122 |
-
if patterns:
|
| 123 |
-
cloth_parts.append(f"patterns such as {', '.join(patterns)}")
|
| 124 |
-
if items:
|
| 125 |
-
cloth_parts.append(f"items like {', '.join(items)}")
|
| 126 |
-
sentences.append("The clothing observed includes " + " and ".join(cloth_parts) + ".")
|
| 127 |
-
else:
|
| 128 |
-
sentences.append("Clothing details were not clearly identified.")
|
| 129 |
-
|
| 130 |
-
if num_faces > 0:
|
| 131 |
-
sentences.append("Faces are distributed naturally across the image.")
|
| 132 |
-
sentences.append("Differences in face size suggest variation in distance from the camera.")
|
| 133 |
-
sentences.append("Hairstyles appear diverse, from short to tied-back styles.")
|
| 134 |
-
sentences.append("Lighting emphasizes certain facial features and expressions.")
|
| 135 |
-
sentences.append("Some individuals face the camera while others look away.")
|
| 136 |
-
sentences.append("Mood diversity is reflected in the variety of facial expressions.")
|
| 137 |
-
sentences.append("The clothing style appears casual or semi-formal.")
|
| 138 |
-
else:
|
| 139 |
-
sentences.append("No visible faces were found to analyze further visual characteristics.")
|
| 140 |
-
|
| 141 |
-
sentences.append("Overall, the image integrates facial, emotional, and clothing features into a cohesive scene.")
|
| 142 |
-
|
| 143 |
-
return "\n".join([f"{i+1}. {s}" for i, s in enumerate(sentences)])
|
| 144 |
-
|
| 145 |
-
# Gradio Interface
|
| 146 |
-
demo = gr.Interface(
|
| 147 |
-
fn=analyze_image,
|
| 148 |
-
inputs=gr.Image(type="pil"),
|
| 149 |
-
outputs=gr.Textbox(label="📝 15-Sentence Detailed Description"),
|
| 150 |
-
title="🖼️ Image Analysis with BLIP + DeepFace",
|
| 151 |
-
description ="Upload an image to get a detailed 15-sentence description of facial features, age, gender, clothing, and more."
|
| 152 |
-
)
|
| 153 |
-
|
| 154 |
-
demo.launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
+
import subprocess
|
| 3 |
+
import torch
|
| 4 |
+
from PIL import Image
|
| 5 |
+
from transformers import AutoProcessor, AutoModelForCausalLM
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
subprocess.run('pip install flash-attn --no-build-isolation', env={'FLASH_ATTENTION_SKIP_CUDA_BUILD': "TRUE"}, shell=True)
|
| 10 |
+
|
| 11 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 12 |
+
florence_model = AutoModelForCausalLM.from_pretrained('microsoft/Florence-2-base', trust_remote_code=True).to(device).eval()
|
| 13 |
+
florence_processor = AutoProcessor.from_pretrained('microsoft/Florence-2-base', trust_remote_code=True)
|
| 14 |
+
|
| 15 |
+
def generate_caption(image):
|
| 16 |
+
if not isinstance(image, Image.Image):
|
| 17 |
+
image = Image.fromarray(image)
|
| 18 |
+
|
| 19 |
+
inputs = florence_processor(text="<MORE_DETAILED_CAPTION>", images=image, return_tensors="pt").to(device)
|
| 20 |
+
generated_ids = florence_model.generate(
|
| 21 |
+
input_ids=inputs["input_ids"],
|
| 22 |
+
pixel_values=inputs["pixel_values"],
|
| 23 |
+
max_new_tokens=1024,
|
| 24 |
+
early_stopping=False,
|
| 25 |
+
do_sample=False,
|
| 26 |
+
num_beams=3,
|
| 27 |
+
)
|
| 28 |
+
generated_text = florence_processor.batch_decode(generated_ids, skip_special_tokens=False)[0]
|
| 29 |
+
parsed_answer = florence_processor.post_process_generation(
|
| 30 |
+
generated_text,
|
| 31 |
+
task="<MORE_DETAILED_CAPTION>",
|
| 32 |
+
image_size=(image.width, image.height)
|
| 33 |
+
)
|
| 34 |
+
prompt = parsed_answer["<MORE_DETAILED_CAPTION>"]
|
| 35 |
+
print("\n\nGeneration completed!:"+ prompt)
|
| 36 |
+
return prompt
|
| 37 |
+
|
| 38 |
+
io = gr.Interface(generate_caption,
|
| 39 |
+
inputs=[gr.Image(label="Input Image")],
|
| 40 |
+
outputs = [gr.Textbox(label="Output Prompt", lines=3, show_copy_button = True),
|
| 41 |
+
],
|
| 42 |
+
theme="Yntec/HaleyCH_Theme_Orange",
|
| 43 |
+
description="⚠ Sorry for the inconvenience. The space are currently running on the CPU, which might affect performance. We appreciate your understanding."
|
| 44 |
+
)
|
| 45 |
+
io.launch(debug=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|