Upload app.py
Browse files
app.py
ADDED
@@ -0,0 +1,142 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
from PIL import Image
|
3 |
+
import torch
|
4 |
+
import numpy as np
|
5 |
+
import faiss
|
6 |
+
|
7 |
+
from transformers import (
|
8 |
+
GitProcessor,
|
9 |
+
GitForCausalLM,
|
10 |
+
AutoTokenizer,
|
11 |
+
AutoModelForCausalLM,
|
12 |
+
CLIPProcessor,
|
13 |
+
CLIPModel
|
14 |
+
)
|
15 |
+
from sentence_transformers import SentenceTransformer
|
16 |
+
from datasets import load_dataset
|
17 |
+
|
18 |
+
device = torch.device("mps" if torch.backends.mps.is_available() else "cuda" if torch.cuda.is_available() else "cpu")
|
19 |
+
|
20 |
+
tokenizer_llama = AutoTokenizer.from_pretrained("TinyLlama/TinyLlama-1.1B-Chat-v1.0")
|
21 |
+
model_llama = AutoModelForCausalLM.from_pretrained(
|
22 |
+
"TinyLlama/TinyLlama-1.1B-Chat-v1.0",
|
23 |
+
torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
|
24 |
+
device_map="auto"
|
25 |
+
).eval()
|
26 |
+
|
27 |
+
text_encoder = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
|
28 |
+
|
29 |
+
clip_model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32").to(device).eval()
|
30 |
+
clip_processor = CLIPProcessor.from_pretrained("openai/clip-vit-base-patch32")
|
31 |
+
|
32 |
+
# Загрузка только первых 10000 изображений через streaming
|
33 |
+
MAX_IMAGES = 10_000
|
34 |
+
dataset_stream = load_dataset("huggan/wikiart", split="train", streaming=True)
|
35 |
+
first_10000 = [x for i, x in enumerate(dataset_stream) if i < MAX_IMAGES]
|
36 |
+
|
37 |
+
image_index = faiss.read_index("image_index_llama.faiss")
|
38 |
+
text_index = faiss.read_index("text_index_llama.faiss")
|
39 |
+
|
40 |
+
def clean_caption(text):
|
41 |
+
return text.replace("[ unused0 ]", "").strip()
|
42 |
+
|
43 |
+
def generate_captions(image: Image.Image):
|
44 |
+
inputs = git_processor(images=image, return_tensors="pt")["pixel_values"].to(device)
|
45 |
+
|
46 |
+
captions = []
|
47 |
+
with torch.no_grad():
|
48 |
+
deterministic_ids = git_model.generate(
|
49 |
+
pixel_values=inputs,
|
50 |
+
max_new_tokens=30,
|
51 |
+
do_sample=False
|
52 |
+
)
|
53 |
+
captions.append(clean_caption(git_processor.tokenizer.decode(deterministic_ids[0], skip_special_tokens=True)))
|
54 |
+
|
55 |
+
sampled_ids = git_model.generate(
|
56 |
+
pixel_values=inputs,
|
57 |
+
max_new_tokens=30,
|
58 |
+
do_sample=True,
|
59 |
+
top_k=100,
|
60 |
+
temperature=0.8,
|
61 |
+
num_return_sequences=2
|
62 |
+
)
|
63 |
+
sampled = git_processor.tokenizer.batch_decode(sampled_ids, skip_special_tokens=True)
|
64 |
+
captions.extend([clean_caption(c) for c in sampled])
|
65 |
+
|
66 |
+
return captions
|
67 |
+
|
68 |
+
def refine_caption(base, desc1, desc2):
|
69 |
+
prompt = f"""
|
70 |
+
Given the base caption that is true and factual:
|
71 |
+
\"{base}\"
|
72 |
+
|
73 |
+
And two descriptive captions:
|
74 |
+
1) {desc1}
|
75 |
+
2) {desc2}
|
76 |
+
|
77 |
+
Write a short, coherent description that is faithful to the base caption but incorporates descriptive elements from captions 1 and 2 without contradicting the original meaning.
|
78 |
+
"""
|
79 |
+
inputs = tokenizer_llama(prompt, return_tensors="pt").to(model_llama.device)
|
80 |
+
with torch.no_grad():
|
81 |
+
output = model_llama.generate(**inputs, max_new_tokens=100, do_sample=False)
|
82 |
+
text = tokenizer_llama.decode(output[0], skip_special_tokens=True)
|
83 |
+
answer = text[len(prompt):].strip()
|
84 |
+
for prefix in ["Example:", "example:"]:
|
85 |
+
if answer.startswith(prefix):
|
86 |
+
answer = answer[len(prefix):].strip()
|
87 |
+
return answer
|
88 |
+
|
89 |
+
def get_text_embedding(text):
|
90 |
+
emb = text_encoder.encode([text], normalize_embeddings=False).astype("float32")
|
91 |
+
faiss.normalize_L2(emb)
|
92 |
+
return emb
|
93 |
+
|
94 |
+
def get_image_embedding(image):
|
95 |
+
inputs = clip_processor(images=image, return_tensors="pt").to(device)
|
96 |
+
with torch.no_grad():
|
97 |
+
image_features = clip_model.get_image_features(**inputs)
|
98 |
+
emb = image_features.cpu().numpy().astype("float32")
|
99 |
+
faiss.normalize_L2(emb)
|
100 |
+
return emb
|
101 |
+
|
102 |
+
def get_results_with_images(embedding, index, top_k=2):
|
103 |
+
D, I = index.search(embedding, top_k)
|
104 |
+
results = []
|
105 |
+
for idx in I[0]:
|
106 |
+
if idx >= MAX_IMAGES:
|
107 |
+
continue
|
108 |
+
try:
|
109 |
+
item = first_10000[idx]
|
110 |
+
img = item["image"]
|
111 |
+
caption = item["caption"]
|
112 |
+
caption_text = f"ID: {idx}\n{caption}"
|
113 |
+
results.append((img, caption_text))
|
114 |
+
except IndexError:
|
115 |
+
continue
|
116 |
+
return results
|
117 |
+
|
118 |
+
def search_similar_images(image: Image.Image):
|
119 |
+
captions = generate_captions(image)
|
120 |
+
refined = refine_caption(captions[0], captions[1], captions[2])
|
121 |
+
|
122 |
+
text_emb = get_text_embedding(refined)
|
123 |
+
image_emb = get_image_embedding(image)
|
124 |
+
|
125 |
+
text_results = get_results_with_images(text_emb, text_index)
|
126 |
+
image_results = get_results_with_images(image_emb, image_index)
|
127 |
+
|
128 |
+
return refined, text_results, image_results
|
129 |
+
|
130 |
+
demo = gr.Interface(
|
131 |
+
fn=search_similar_images,
|
132 |
+
inputs=gr.Image(label="Загрузите изображение", type="pil"),
|
133 |
+
outputs=[
|
134 |
+
gr.Textbox(label="📜 Сгенерированное описание"),
|
135 |
+
gr.Gallery(label="🔍 Похожие по описанию (caption)", height="auto", columns=2),
|
136 |
+
gr.Gallery(label="🎨 Похожие по изображению (CLIP)", height="auto", columns=2)
|
137 |
+
],
|
138 |
+
title="🎨 Semantic WikiArt Search",
|
139 |
+
description="Загрузите изображение. Модель сгенерирует описание, получит эмбеддинги и найдёт похожие картины по описанию и изображению."
|
140 |
+
)
|
141 |
+
|
142 |
+
demo.launch()
|