Upload app.py with huggingface_hub
Browse files
app.py
CHANGED
|
@@ -129,30 +129,41 @@ def get_training_embeddings_sample(n=100000):
|
|
| 129 |
"""Load a sample of training data for recommendations."""
|
| 130 |
import pandas as pd
|
| 131 |
from sklearn.model_selection import train_test_split
|
| 132 |
-
|
| 133 |
data = pd.read_csv('xkcd_scaled_data_Final.txt', nrows=n)
|
| 134 |
data = data.dropna(subset=['name']).reset_index(drop=True)
|
| 135 |
data['name_clean'] = data['name'].apply(clean_color_name)
|
| 136 |
data = data[data['name_clean'].str.len() > 0].reset_index(drop=True)
|
| 137 |
-
|
| 138 |
indices = np.arange(len(data))
|
| 139 |
train_idx, _ = train_test_split(indices, test_size=0.25, random_state=42)
|
| 140 |
-
|
| 141 |
train_names = data.loc[train_idx, 'name_clean'].tolist()
|
| 142 |
train_rgbs = data.loc[train_idx, ['red', 'green', 'blue']].values
|
| 143 |
-
|
| 144 |
# Build embeddings
|
| 145 |
X = np.zeros((len(train_names), MAX_TOKENS, VEC_SIZE), dtype=np.float32)
|
| 146 |
for i, name in enumerate(train_names):
|
| 147 |
tokens = name.split()
|
| 148 |
for j, token in enumerate(tokens[:MAX_TOKENS]):
|
| 149 |
X[i, j] = fasttext.wv[token]
|
| 150 |
-
|
| 151 |
return X, train_names, train_rgbs
|
| 152 |
|
|
|
|
| 153 |
print("Loading training data for recommendations...")
|
| 154 |
-
|
| 155 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 156 |
|
| 157 |
# ββ Color Space Conversions ββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 158 |
def rgb_to_hex(r, g, b):
|
|
@@ -215,11 +226,13 @@ def predict_color(name):
|
|
| 215 |
return r, g, b
|
| 216 |
|
| 217 |
def cosine_similarity(query_vec, reference_vecs=X_train):
|
|
|
|
|
|
|
| 218 |
m, n = query_vec.shape
|
| 219 |
test_new = query_vec.reshape(m * n)
|
| 220 |
word_mag = np.linalg.norm(test_new)
|
| 221 |
if word_mag == 0:
|
| 222 |
-
return np.
|
| 223 |
|
| 224 |
p, q, r = reference_vecs.shape
|
| 225 |
ref_new = reference_vecs.reshape(p, q * r)
|
|
@@ -230,6 +243,8 @@ def cosine_similarity(query_vec, reference_vecs=X_train):
|
|
| 230 |
|
| 231 |
def get_recommendations(query_embedding, top_k=5):
|
| 232 |
"""Get top-k similar colors from training data."""
|
|
|
|
|
|
|
| 233 |
indices = cosine_similarity(query_embedding)
|
| 234 |
results = []
|
| 235 |
for idx in indices[:top_k]:
|
|
@@ -266,26 +281,29 @@ def process_color_name(color_name):
|
|
| 266 |
query_emb = get_embedding(color_name)
|
| 267 |
recommendations = get_recommendations(query_emb, top_k=5)
|
| 268 |
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
<div style="display: flex;
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 285 |
</div>
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
rec_html += '</div>'
|
| 289 |
|
| 290 |
# Color space conversions
|
| 291 |
L, a, b_lab = rgb_to_lab(r, g, b)
|
|
@@ -363,6 +381,25 @@ with gr.Blocks(css=css, title="Color Name to RGB Predictor") as demo:
|
|
| 363 |
inputs=color_input,
|
| 364 |
label="Try these examples"
|
| 365 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 366 |
|
| 367 |
predict_btn.click(
|
| 368 |
fn=process_color_name,
|
|
|
|
| 129 |
"""Load a sample of training data for recommendations."""
|
| 130 |
import pandas as pd
|
| 131 |
from sklearn.model_selection import train_test_split
|
| 132 |
+
|
| 133 |
data = pd.read_csv('xkcd_scaled_data_Final.txt', nrows=n)
|
| 134 |
data = data.dropna(subset=['name']).reset_index(drop=True)
|
| 135 |
data['name_clean'] = data['name'].apply(clean_color_name)
|
| 136 |
data = data[data['name_clean'].str.len() > 0].reset_index(drop=True)
|
| 137 |
+
|
| 138 |
indices = np.arange(len(data))
|
| 139 |
train_idx, _ = train_test_split(indices, test_size=0.25, random_state=42)
|
| 140 |
+
|
| 141 |
train_names = data.loc[train_idx, 'name_clean'].tolist()
|
| 142 |
train_rgbs = data.loc[train_idx, ['red', 'green', 'blue']].values
|
| 143 |
+
|
| 144 |
# Build embeddings
|
| 145 |
X = np.zeros((len(train_names), MAX_TOKENS, VEC_SIZE), dtype=np.float32)
|
| 146 |
for i, name in enumerate(train_names):
|
| 147 |
tokens = name.split()
|
| 148 |
for j, token in enumerate(tokens[:MAX_TOKENS]):
|
| 149 |
X[i, j] = fasttext.wv[token]
|
| 150 |
+
|
| 151 |
return X, train_names, train_rgbs
|
| 152 |
|
| 153 |
+
# Try to load training data for recommendations (optional)
|
| 154 |
print("Loading training data for recommendations...")
|
| 155 |
+
try:
|
| 156 |
+
X_train, train_names, train_rgbs = get_training_embeddings_sample(100000)
|
| 157 |
+
print(f"Loaded {len(train_names)} training samples for recommendations")
|
| 158 |
+
RECOMMENDATIONS_ENABLED = True
|
| 159 |
+
except FileNotFoundError:
|
| 160 |
+
print("Warning: xkcd_scaled_data_Final.txt not found. Recommendations disabled.")
|
| 161 |
+
X_train, train_names, train_rgbs = None, None, None
|
| 162 |
+
RECOMMENDATIONS_ENABLED = False
|
| 163 |
+
except Exception as e:
|
| 164 |
+
print(f"Warning: Failed to load training data: {e}. Recommendations disabled.")
|
| 165 |
+
X_train, train_names, train_rgbs = None, None, None
|
| 166 |
+
RECOMMENDATIONS_ENABLED = False
|
| 167 |
|
| 168 |
# ββ Color Space Conversions ββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 169 |
def rgb_to_hex(r, g, b):
|
|
|
|
| 226 |
return r, g, b
|
| 227 |
|
| 228 |
def cosine_similarity(query_vec, reference_vecs=X_train):
|
| 229 |
+
if not RECOMMENDATIONS_ENABLED or reference_vecs is None:
|
| 230 |
+
return np.array([])
|
| 231 |
m, n = query_vec.shape
|
| 232 |
test_new = query_vec.reshape(m * n)
|
| 233 |
word_mag = np.linalg.norm(test_new)
|
| 234 |
if word_mag == 0:
|
| 235 |
+
return np.array([])
|
| 236 |
|
| 237 |
p, q, r = reference_vecs.shape
|
| 238 |
ref_new = reference_vecs.reshape(p, q * r)
|
|
|
|
| 243 |
|
| 244 |
def get_recommendations(query_embedding, top_k=5):
|
| 245 |
"""Get top-k similar colors from training data."""
|
| 246 |
+
if not RECOMMENDATIONS_ENABLED:
|
| 247 |
+
return []
|
| 248 |
indices = cosine_similarity(query_embedding)
|
| 249 |
results = []
|
| 250 |
for idx in indices[:top_k]:
|
|
|
|
| 281 |
query_emb = get_embedding(color_name)
|
| 282 |
recommendations = get_recommendations(query_emb, top_k=5)
|
| 283 |
|
| 284 |
+
if not RECOMMENDATIONS_ENABLED:
|
| 285 |
+
rec_html = '<div style="color: #888; font-style: italic; padding: 20px; text-align: center;">π Recommendations require training data (xkcd_scaled_data_Final.txt) β not available in this deployment.</div>'
|
| 286 |
+
else:
|
| 287 |
+
rec_html = '<div style="display: flex; flex-direction: column; gap: 8px;">'
|
| 288 |
+
for name, rec_hex, rec_rgb in recommendations:
|
| 289 |
+
rec_html += f""""
|
| 290 |
+
<div style="display: flex; align-items: center; padding: 10px; background: #f9f9f9; border-radius: 8px; border: 1px solid #eee;">
|
| 291 |
+
<div style="
|
| 292 |
+
width: 50px;
|
| 293 |
+
height: 50px;
|
| 294 |
+
background-color: {rec_hex};
|
| 295 |
+
border: 1px solid #ddd;
|
| 296 |
+
border-radius: 6px;
|
| 297 |
+
margin-right: 16px;
|
| 298 |
+
flex-shrink: 0;
|
| 299 |
+
"></div>
|
| 300 |
+
<div>
|
| 301 |
+
<div style="font-weight: 600; font-size: 14px;">{name}</div>
|
| 302 |
+
<div style="font-family: monospace; color: #666; font-size: 13px;">{rec_hex.upper()}</div>
|
| 303 |
+
</div>
|
| 304 |
</div>
|
| 305 |
+
"""
|
| 306 |
+
rec_html += '</div>'
|
|
|
|
| 307 |
|
| 308 |
# Color space conversions
|
| 309 |
L, a, b_lab = rgb_to_lab(r, g, b)
|
|
|
|
| 381 |
inputs=color_input,
|
| 382 |
label="Try these examples"
|
| 383 |
)
|
| 384 |
+
|
| 385 |
+
# Citation
|
| 386 |
+
gr.Markdown("""
|
| 387 |
+
---
|
| 388 |
+
### π Citation
|
| 389 |
+
If you use this work in your research, please cite:
|
| 390 |
+
```bibtex
|
| 391 |
+
@article{jyothi2023text2color,
|
| 392 |
+
title={Text2Color Networks: Deep Learning Models for Color Generation from Compositional Color Descriptions},
|
| 393 |
+
author={Jyothi, Kondalarao and Okade, Manish},
|
| 394 |
+
journal={International Journal on Artificial Intelligence Tools},
|
| 395 |
+
volume={32},
|
| 396 |
+
number={06},
|
| 397 |
+
pages={2350026},
|
| 398 |
+
year={2023},
|
| 399 |
+
publisher={World Scientific}
|
| 400 |
+
}
|
| 401 |
+
```
|
| 402 |
+
""")
|
| 403 |
|
| 404 |
predict_btn.click(
|
| 405 |
fn=process_color_name,
|