Spaces:
Sleeping
Sleeping
File size: 5,401 Bytes
e9e471e | 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 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 | """
Image utilities for BrightMind AI with shorter naming system
"""
import os
import time
import hashlib
from datetime import datetime
from pathlib import Path
def generate_short_image_name(topic, content_type="lesson", index=0):
"""
Generate a short, meaningful image name.
Args:
topic (str): The main topic of the image
content_type (str): Type of content (lesson, worksheet, etc.)
index (int): Index for multiple images of same topic
Returns:
str: Short image name like 'img_alg_123456_0.png'
"""
# Clean topic name - remove special chars, limit length
clean_topic = ''.join(c for c in topic.lower() if c.isalnum())[:6]
# Get timestamp (last 6 digits)
timestamp = str(int(time.time()))[-6:]
# Create short name
short_name = f"img_{clean_topic}_{timestamp}_{index}"
return short_name
def save_image_with_short_name(image_data, topic, description, content_type="lesson", output_dir="generated_images"):
"""
Save image with short name and return the filename.
Args:
image_data (bytes): The actual image data
topic (str): The topic of the image
description (str): Description of the image
content_type (str): Type of content
output_dir (str): Directory to save images
Returns:
tuple: (filename, full_path, metadata)
"""
# Create output directory if it doesn't exist
Path(output_dir).mkdir(exist_ok=True)
# Generate short name
short_name = generate_short_image_name(topic, content_type)
filename = f"{short_name}.png"
full_path = os.path.join(output_dir, filename)
# Save the image
if image_data:
with open(full_path, 'wb') as f:
f.write(image_data)
print(f"๐ธ Image saved: {filename}")
else:
print(f"๐ธ Image name generated: {filename} (no data to save)")
# Create metadata
metadata = {
"short_name": short_name,
"filename": filename,
"full_path": full_path,
"topic": topic,
"description": description,
"content_type": content_type,
"timestamp": datetime.now().isoformat(),
"size_bytes": len(image_data) if image_data else 0
}
return filename, full_path, metadata
def create_image_html_tag(image_path, alt_text="Generated image", width=400, height=300):
"""
Create an HTML img tag for displaying the image.
Args:
image_path (str): Path to the image file
alt_text (str): Alt text for the image
width (int): Width of the image
height (int): Height of the image
Returns:
str: HTML img tag
"""
# Check if image exists
if os.path.exists(image_path):
return f'<img src="{image_path}" alt="{alt_text}" width="{width}" height="{height}" style="max-width: 100%; height: auto; border-radius: 8px; margin: 10px 0;">'
else:
# Return placeholder if image doesn't exist
return f'<div style="width: {width}px; height: {height}px; background: #f0f0f0; border: 2px dashed #ccc; display: flex; align-items: center; justify-content: center; border-radius: 8px; margin: 10px 0; color: #666;">๐ท {alt_text}</div>'
def integrate_with_main_app():
"""
Example of how to integrate short naming with the main app.
"""
print("๐ง Integration example for main app:")
print("""
# In your main app.py, replace the image generation calls with:
from image_utils import save_image_with_short_name, create_image_html_tag
# When generating images:
def generate_real_image(description, topic, content_type):
# ... your existing image generation code ...
if image_data:
filename, full_path, metadata = save_image_with_short_name(
image_data, topic, description, content_type
)
# Create HTML tag for display
html_tag = create_image_html_tag(full_path, description)
return html_tag
else:
# Fallback placeholder
return f'<div class="image-placeholder">{description}</div>'
""")
def demo_integration():
"""
Demo the integration with sample data.
"""
print("๐ Image Utils Integration Demo")
print("=" * 40)
# Sample image data (in real app, this would be actual image bytes)
sample_topics = [
("Algebra", "Visual introduction to algebraic concepts", "lesson"),
("Geometry", "Diagram showing geometric shapes", "worksheet"),
("Physics", "Real-world physics examples", "activity")
]
for topic, description, content_type in sample_topics:
print(f"\n๐ Processing: {topic}")
# Generate short name and save (simulated)
filename, full_path, metadata = save_image_with_short_name(
None, # No actual image data in demo
topic,
description,
content_type
)
# Create HTML tag
html_tag = create_image_html_tag(full_path, description)
print(f" โ
Generated: {filename}")
print(f" ๐ Path: {full_path}")
print(f" ๐ท๏ธ HTML: {html_tag[:100]}...")
if __name__ == "__main__":
demo_integration()
print("\n" + "="*50)
integrate_with_main_app()
|