matinsn2000 commited on
Commit
4d4fccb
·
1 Parent(s): fa7dceb

Utilized two models and faliover for retreieving image meta data

Browse files
AI_USAGE_REPORT.txt CHANGED
@@ -1,359 +1,136 @@
1
  ================================================================================
2
- AI USAGE REPORT
3
  Cloudzy AI Challenge - Photo Album Management System
4
  ================================================================================
5
 
6
  PROJECT OVERVIEW
7
  ================
8
- This project implements an AI-enhanced photo management system that uses machine learning
9
- models for generating embeddings and AI summaries for photo clusters. The system allows
10
- users to upload photos, search by similarity, and organize them into meaningful albums
11
- with AI-generated summaries.
12
 
13
  ================================================================================
14
- 1. WHERE AND HOW AI WAS USED
15
  ================================================================================
16
 
17
- A. IMAGE EMBEDDING GENERATION
18
- Location: cloudzy/ai_utils.py - ImageEmbeddingGenerator class
19
- Purpose: Convert photo metadata (tags, description, caption) into 1024-dimensional
20
- vector embeddings for similarity search
21
 
22
- Model Used:
23
- - Provider: Hugging Face Hub (InferenceClient)
24
- - Model Name: intfloat/multilingual-e5-large
25
- - Endpoint: feature_extraction
26
 
27
- How It's Used:
28
- 1. User uploads photo with metadata (tags, caption, description)
29
- 2. metadata is combined into a single text string
30
- 3. Text is sent to HF model via InferenceClient.feature_extraction()
31
- 4. Model returns 1024-d embedding vector
32
- 5. Embedding is stored in FAISS index for similarity search
33
 
34
- Integration Points:
35
- - cloudzy/routes/upload.py: Called during photo upload
36
- - cloudzy/search_engine.py: Used for vector similarity search
37
- - Database: Embeddings stored as numpy arrays
38
-
39
- B. AI SUMMARY GENERATION
40
- Location: cloudzy/ai_utils.py - TextSummarizer class
41
- Purpose: Generate meaningful summaries of photo clusters based on actual photo metadata
42
-
43
- Model Used:
44
- - Provider: Hugging Face Hub (InferenceClient)
45
- - Model Name: facebook/bart-large-cnn
46
- - Endpoint: summarization
47
-
48
- How It's Used:
49
- 1. User requests /albums endpoint
50
- 2. System retrieves all photo clusters
51
- 3. For each cluster, collects all captions and tags from photos
52
- 4. Combined metadata is sent to BART summarization model
53
- 5. Model generates concise summary (e.g., "A collection of indoor photos featuring...")
54
- 6. Summary replaces placeholder "Cluster of similar photos" in response
55
-
56
- Integration Points:
57
- - cloudzy/routes/photo.py: get_albums() endpoint
58
- - Response Schema: Pydantic AlbumItem model
59
- - Fallback: If summarization fails, returns truncated text
60
-
61
- ================================================================================
62
- 2. PROMPTS AND MODEL INPUTS
63
- ================================================================================
64
-
65
- A. IMAGE EMBEDDING INPUTS
66
- Raw Input Format:
67
- tags: List[str] = ["nature", "sunset", "beach"]
68
- description: str = "A beautiful sunset at the beach with waves"
69
- caption: str = "Sunset beach scene"
70
-
71
- Processing:
72
- Combined Text = " ".join(tags) + " " + description + " " + caption
73
- Example: "nature sunset beach A beautiful sunset at the beach with waves Sunset beach scene"
74
-
75
- Model Request (Hugging Face InferenceClient):
76
- client.feature_extraction(
77
- text=combined_text,
78
- model="intfloat/multilingual-e5-large"
79
- )
80
-
81
- Expected Output:
82
- - Type: List of floats (1024 dimensions)
83
- - Converted to: numpy.ndarray of shape (1024,)
84
- - Data type: float32
85
- - Usage: Stored in FAISS index for vector similarity search
86
-
87
- B. SUMMARIZATION INPUTS
88
- Raw Input Format:
89
- For each album cluster, combine all photo metadata:
90
- texts = []
91
- for photo in cluster_photos:
92
- texts.append(photo.caption)
93
- texts.extend(photo.tags)
94
- combined_input = " ".join(texts)
95
-
96
- Example Input:
97
- "Beach sunset waves ocean Sunset at the ocean view Nature landscape
98
- Seascape beautiful A sunset scene with ocean waves A scenic beach view"
99
-
100
- Model Request (Hugging Face InferenceClient):
101
- client.summarization(
102
- text=combined_input,
103
- model="facebook/bart-large-cnn"
104
- )
105
-
106
- Expected Output:
107
- - Type: List containing dictionary with 'summary_text' key
108
- - Example: "A collection of beach and sunset photographs featuring scenic ocean views"
109
- - Processing: Extract summary_text from returned object
110
- - Type Conversion: Ensure string type for Pydantic validation
111
-
112
- ================================================================================
113
- 3. HOW MODEL OUTPUTS WERE REFINED
114
- ================================================================================
115
-
116
- A. EMBEDDING OUTPUT REFINEMENT
117
- Issue Encountered:
118
- - Expected shape: (512,) per documentation
119
- - Actual shape: (1024,) from model
120
- - Initial: Validation checked for 1024 but comment said 512
121
-
122
- Resolution:
123
- - Updated validation to expect 1024 dimensions (correct model behavior)
124
- - Converged to: if embedding.shape[0] != 1024: raise ValueError
125
- - Added type casting: np.array(result, dtype=np.float32).reshape(-1)
126
- - Reshape(-1) ensures flattening to 1D array
127
-
128
- Code Refinement (ai_utils.py, lines 50-62):
129
- def _embed_text(self, text: str) -> np.ndarray:
130
- result = self.client.feature_extraction(text, model=self.model_name)
131
- embedding = np.array(result, dtype=np.float32).reshape(-1)
132
- if embedding.shape[0] != 1024:
133
- raise ValueError(f"Expected embedding of size 1024, got {embedding.shape[0]}")
134
- return embedding
135
-
136
- B. SUMMARIZATION OUTPUT REFINEMENT
137
- Issue Encountered:
138
- - Pydantic validation error: "Input should be a valid string"
139
- - Received: SummarizationOutput object instead of string
140
- - Root Cause: client.summarization() returns structured object, not string
141
-
142
- Resolution:
143
- - Added type-safe extraction logic
144
- - Implemented multiple fallback formats:
145
- 1. If list: Extract first element's 'summary_text' field
146
- 2. If dict: Get 'summary_text' field directly
147
- 3. Fallback: Convert to string
148
-
149
- Code Refinement (ai_utils.py, lines 90-100):
150
- result = self.client.summarization(text, model=self.model_name)
151
-
152
- # Extract the summary text from the result object
153
- if isinstance(result, list) and len(result) > 0:
154
- return result[0].get("summary_text", str(result[0]))
155
- elif isinstance(result, dict):
156
- return result.get("summary_text", str(result))
157
- else:
158
- return str(result)
159
-
160
- C. ERROR HANDLING AND DEFAULTS
161
- Embedding Generation:
162
- - Validation ensures exact dimension match
163
- - Raises clear error if dimension mismatch
164
- - Prevents downstream vector search issues
165
-
166
- Summarization:
167
- - Try-except block with graceful fallback
168
- - Fallback: Returns truncated input (first 80 chars)
169
- - Empty text handling: Returns default "Album of photos"
170
- - Ensures robustness when HF API is unavailable
171
 
172
  ================================================================================
173
- 4. MANUAL VS AI-GENERATED PARTS
174
  ================================================================================
175
 
176
- MANUAL PARTS (100% Developer-Written)
177
- ====================================
178
- Database schema and models
179
- - cloudzy/models.py: SQLAlchemy Photo model
180
- - cloudzy/database.py: Database connection and session management
181
-
182
- ✓ API Route Handlers
183
- - cloudzy/routes/photo.py: All endpoint logic
184
- - cloudzy/routes/upload.py: File upload handling
185
- - cloudzy/routes/search.py: Search endpoint implementation
186
-
187
- ✓ File Management
188
- - cloudzy/utils/file_upload_service.py: Upload service
189
- - cloudzy/utils/file_utils.py: File utilities
190
-
191
- ✓ Data Serialization
192
- - cloudzy/schemas.py: Pydantic models and validation
193
-
194
- ✓ Search Engine Implementation
195
- - cloudzy/search_engine.py: FAISS vector search logic
196
- - Distance calculation and result ranking
197
-
198
- ✓ Application Configuration
199
- - app.py: FastAPI app setup
200
- - Dockerfile: Containerization
201
- - requirements.txt: Dependencies
202
 
203
- HYBRID PARTS (Manual Integration + AI Models)
204
- ==============================================
205
- ImageEmbeddingGenerator Class
206
- - Manual: Class structure, API client initialization
207
- - Manual: Error handling and validation logic
208
- - Manual: Type conversion and reshaping
209
- - AI: Feature extraction from HF model
210
- - Result: Text → 1024-d vector embeddings
211
 
212
- TextSummarizer Class
213
- - Manual: Class structure, API client initialization
214
- - Manual: Output parsing and extraction logic
215
- - Manual: Error handling and fallbacks
216
- - Manual: Empty text handling
217
- - AI: Summary generation from combined text
218
- - Result: Multi-sentence text → concise summary
219
-
220
- ✓ Album Summary Integration (photo.py)
221
- - Manual: Cluster iteration and photo data collection
222
- - Manual: Text concatenation logic
223
- - Manual: Response structure and schema mapping
224
- - AI: Summary generation
225
- - Result: Photo cluster → meaningful album summary
226
-
227
- AI-GENERATED PARTS
228
- ==================
229
- ✓ Embedding vectors
230
- - Generated by: intfloat/multilingual-e5-large
231
- - Content: Semantic representation of photo metadata
232
- - Used for: Similarity search and clustering
233
-
234
- ✓ Album summaries
235
- - Generated by: facebook/bart-large-cnn
236
- - Content: Concise description of photo cluster themes
237
- - Used for: Album display and description
238
-
239
- ✓ Model-specific responses
240
- - Output format: Determined by HF models
241
- - Processing: Handled by manual extraction code
242
 
243
  ================================================================================
244
- 5. DEVELOPMENT PROCESS AND DECISIONS
245
  ================================================================================
246
 
247
- DECISION 1: Model Selection
248
- Manual Decision: Why facebook/bart-large-cnn?
249
- - Reasons:
250
- * Pre-trained on CNN/DailyMail summarization corpus
251
- * Optimized for multi-sentence summarization
252
- * Fast inference through Hugging Face API
253
- * Produces concise, extractive summaries
254
-
255
- Alternative considered: facebook/bart-base (smaller, faster but lower quality)
256
 
257
- DECISION 2: Embedding Dimension Resolution
258
- Manual Decision: Accept 1024-d embeddings (not 512-d)
259
- - Reason:
260
- * intfloat/multilingual-e5-large actually produces 1024 dimensions
261
- * Better semantic representation than 512-d
262
- * FAISS index configured for 1024-d vectors
263
- * Updated validation to reflect actual model output
264
 
265
- DECISION 3: Error Handling Strategy
266
- Manual Decision: Graceful degradation with fallbacks
267
- - Implementation:
268
- * Try summarization first
269
- * If fails, return truncated text
270
- * If text is empty, return default message
271
- * Ensures endpoint never fails due to AI API issues
272
 
273
- DECISION 4: Output Extraction
274
- Manual Decision: Flexible type handling for model output
275
- - Implementation:
276
- * Handle both list and dict return formats
277
- * Extract 'summary_text' field when available
278
- * Fallback to string conversion
279
- * Ensures compatibility with different API versions
280
 
281
  ================================================================================
282
- 6. TESTING AND VALIDATION
283
  ================================================================================
284
 
285
- Validation Points:
286
- Embedding shape validation (must be 1024-d)
287
- ✓ Type conversion to float32
288
- Summary extraction and string conversion
289
- Pydantic schema validation (AlbumItem requires string album_summary)
290
- Error handling and fallbacks
 
 
291
 
292
- Testing Done:
293
- Manual endpoint testing with sample photos
294
- Verified embedding shape and type
295
- Tested summarization with various input lengths
296
- Validated API error handling
297
- ✓ Checked Pydantic schema compliance
298
 
299
  ================================================================================
300
- 7. ENVIRONMENT CONFIGURATION
301
  ================================================================================
302
 
303
- Required Environment Variables:
304
- - HF_TOKEN: Hugging Face API token (for authentication)
305
- Location: Set in .env file
306
- Usage: InferenceClient initialization
307
- Scope: Both ImageEmbeddingGenerator and TextSummarizer
308
-
309
- API Access:
310
- - Provider: Hugging Face Inference API
311
- - Authentication: Token-based via HF_TOKEN
312
- - Rate Limiting: Subject to HF plan limits
313
- - Fallback: When unavailable, gracefully returns truncated text
314
 
315
  ================================================================================
316
- 8. PERFORMANCE CONSIDERATIONS
317
  ================================================================================
318
 
319
- Current Implementation:
320
- - Summarization called per album cluster (on-demand)
321
- - Embedding generation per photo upload
322
- - FAISS vector search (fast, local)
323
-
324
- Potential Optimizations:
325
- ✓ Cache summaries in database (reduce API calls)
326
- ✓ Batch embedding generation for multiple uploads
327
- ✓ Implement summary caching with TTL
328
- ✓ Consider async processing for large clusters
329
-
330
- Current Trade-offs:
331
- - Speed vs Freshness: Summaries generated on-demand (fresh, slower)
332
- - Accuracy vs Cost: Full text summarization vs cached summaries
333
 
334
  ================================================================================
335
  SUMMARY
336
  ================================================================================
337
 
338
- This project demonstrates responsible AI integration:
339
-
340
- 1. Clear Separation: Manual development (infrastructure, logic) vs AI (models)
341
- 2. Error Handling: Graceful degradation when AI services unavailable
342
- 3. Transparency: Documented model choices and output processing
343
- 4. Flexibility: Handle various model output formats
344
- 5. Validation: Schema validation ensures data integrity
345
- 6. Integration: AI models complement, not replace, core functionality
346
 
347
- AI Value Added:
348
- - Semantic search capabilities (embeddings)
349
- - Automated summary generation (reduces manual effort)
350
- - Better user experience (meaningful album descriptions)
351
 
352
- Human Involvement:
353
- - System design and architecture
354
- - Error handling and edge cases
355
- - API integration and data processing
356
- - Schema definition and validation
357
- - Deployment and configuration
358
 
359
  ================================================================================
 
1
  ================================================================================
2
+ AI USAGE REPORT (SUMMARY)
3
  Cloudzy AI Challenge - Photo Album Management System
4
  ================================================================================
5
 
6
  PROJECT OVERVIEW
7
  ================
8
+ AI-enhanced photo management system with semantic search, album summarization,
9
+ and image generation capabilities.
 
 
10
 
11
  ================================================================================
12
+ AI MODELS USED
13
  ================================================================================
14
 
15
+ 1. IMAGE EMBEDDING: intfloat/multilingual-e5-large
16
+ - Location: cloudzy/ai_utils.py (ImageEmbeddingGenerator)
17
+ - Purpose: Convert photo metadata into 1024-d vectors for similarity search
18
+ - Used in: Photo upload, semantic search, album clustering
19
 
20
+ 2. SUMMARIZATION: facebook/bart-large-cnn
21
+ - Location: cloudzy/ai_utils.py (TextSummarizer)
22
+ - Purpose: Generate summaries of photo clusters
23
+ - Used in: /albums endpoint (creates album descriptions)
24
 
25
+ 3. IMAGE ANALYSIS: Google Gemini 2.0-flash
26
+ - Location: cloudzy/agents/image_analyzer_2.py (ImageAnalyzerAgent)
27
+ - Purpose: Analyze images and generate detailed descriptions
28
+ - Used in: /generate-similar-image endpoint (Step 1)
 
 
29
 
30
+ 4. IMAGE GENERATION: black-forest-labs/FLUX.1-dev
31
+ - Location: cloudzy/inference_models/text_to_image.py (TextToImageGenerator)
32
+ - Purpose: Generate high-quality images from text prompts
33
+ - Used in: /generate-similar-image endpoint (Step 3)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
 
35
  ================================================================================
36
+ MANUAL VS AI-GENERATED
37
  ================================================================================
38
 
39
+ MANUAL WORK (100% Developer-Written):
40
+ ✓ Database schema, API routes, file management
41
+ FastAPI application setup and middleware
42
+ Error handling and validation logic
43
+ File upload service and utilities
44
+ ✓ FAISS vector search implementation
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
 
46
+ HYBRID (Manual Integration + AI Models):
47
+ ✓ ImageEmbeddingGenerator: Text → 1024-d embeddings (AI model)
48
+ TextSummarizer: Metadata → album summary (AI model)
49
+ ImageAnalyzerAgent: Image description (AI model)
50
+ TextToImageGenerator: Prompt generated image (AI model)
 
 
 
51
 
52
+ AI-GENERATED CONTENT:
53
+ Embedding vectors (semantic representations)
54
+ Album summaries (cluster descriptions)
55
+ Image descriptions (visual analysis)
56
+ Generated images (from text prompts)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57
 
58
  ================================================================================
59
+ NEW ENDPOINT: /generate-similar-image
60
  ================================================================================
61
 
62
+ Endpoint: POST /generate-similar-image
63
+ Location: cloudzy/routes/generate.py
 
 
 
 
 
 
 
64
 
65
+ Workflow:
66
+ 1. User uploads an image
67
+ 2. ImageAnalyzerAgent analyzes it → gets description
68
+ 3. TextToImageGenerator creates new image from description
69
+ 4. Returns generated image URL + description
 
 
70
 
71
+ Response:
72
+ {
73
+ "description": "Detailed image analysis from Gemini",
74
+ "generated_image_url": "http://127.0.0.1:8000/uploads/generated_20241025_123456_789.png",
75
+ "message": "Similar image generated successfully"
76
+ }
 
77
 
78
+ Performance: ~40-75 seconds per request
79
+ - Image analysis: ~5-10s (Gemini)
80
+ - Image generation: ~30-60s (FLUX.1-dev)
 
 
 
 
81
 
82
  ================================================================================
83
+ PROMPTS USED IN PROJECT
84
  ================================================================================
85
 
86
+ 1. IMAGE ANALYSIS PROMPT (ImageAnalyzerAgent - Gemini):
87
+ Location: cloudzy/agents/image_analyzer_2.py
88
+
89
+ "Describe this image in a way that could be used as a prompt for generating
90
+ a new image inspired by it. Focus on the main subjects, composition, style,
91
+ mood, and colors. Avoid mentioning specific names or exact details — instead,
92
+ describe the overall aesthetic and atmosphere so the result feels similar but
93
+ not identical."
94
 
95
+ 2. IMAGE GENERATION PROMPT:
96
+ - Input: Description from ImageAnalyzerAgent (above)
97
+ - Model: FLUX.1-dev (black-forest-labs/FLUX.1-dev)
98
+ - Location: cloudzy/inference_models/text_to_image.py
99
+ - Strategy: Direct prompt passing to image generation model
 
100
 
101
  ================================================================================
102
+ ENVIRONMENT VARIABLES
103
  ================================================================================
104
 
105
+ Required:
106
+ - HF_TOKEN: Hugging Face API key (embeddings, summarization)
107
+ - GEMINI_API_KEY: Google Gemini API key (image analysis)
108
+ - HF_TOKEN_1: Alternative HF token (image generation)
109
+ - APP_DOMAIN: App URL (default: http://127.0.0.1:8000/)
 
 
 
 
 
 
110
 
111
  ================================================================================
112
+ KEY DECISIONS
113
  ================================================================================
114
 
115
+ 1. Used FLUX.1-dev for high-quality image generation (vs Stable Diffusion)
116
+ 2. Composable pipeline: ImageAnalyzer TextToImageGenerator (reusable components)
117
+ 3. Graceful error handling with fallbacks when APIs unavailable
118
+ 4. Temporary file handling: saves uploads locally for Gemini analysis
 
 
 
 
 
 
 
 
 
 
119
 
120
  ================================================================================
121
  SUMMARY
122
  ================================================================================
123
 
124
+ This project integrates 4 AI models responsibly:
125
+ - Embeddings for semantic search
126
+ - Summarization for album descriptions
127
+ - Vision AI for image analysis
128
+ - Generative AI for image creation
 
 
 
129
 
130
+ All manual work handles infrastructure, logic, validation, and error handling.
131
+ AI models are called for their specialized tasks only.
 
 
132
 
133
+ New capability: Generate creative image variations from uploaded photos using
134
+ intelligent analysis + high-quality generation pipeline.
 
 
 
 
135
 
136
  ================================================================================
app.py CHANGED
@@ -6,7 +6,7 @@ from fastapi.staticfiles import StaticFiles
6
  from dotenv import load_dotenv
7
 
8
  from cloudzy.database import create_db_and_tables
9
- from cloudzy.routes import upload, photo, search
10
  from cloudzy.search_engine import SearchEngine
11
  import os
12
 
@@ -55,6 +55,7 @@ app.add_middleware(
55
  app.include_router(upload.router)
56
  app.include_router(photo.router)
57
  app.include_router(search.router)
 
58
 
59
  UPLOAD_DIR = os.path.join(os.getcwd(), "uploads")
60
  os.makedirs(UPLOAD_DIR, exist_ok=True)
@@ -76,6 +77,7 @@ async def root():
76
  "list_photos": "GET /photos - List all photos",
77
  "search": "GET /search?q=... - Semantic search",
78
  "image_to_image": "POST /search/image-to-image - Similar images",
 
79
  "docs": "/docs - Interactive API documentation",
80
  }
81
  }
 
6
  from dotenv import load_dotenv
7
 
8
  from cloudzy.database import create_db_and_tables
9
+ from cloudzy.routes import upload, photo, search, generate
10
  from cloudzy.search_engine import SearchEngine
11
  import os
12
 
 
55
  app.include_router(upload.router)
56
  app.include_router(photo.router)
57
  app.include_router(search.router)
58
+ app.include_router(generate.router)
59
 
60
  UPLOAD_DIR = os.path.join(os.getcwd(), "uploads")
61
  os.makedirs(UPLOAD_DIR, exist_ok=True)
 
77
  "list_photos": "GET /photos - List all photos",
78
  "search": "GET /search?q=... - Semantic search",
79
  "image_to_image": "POST /search/image-to-image - Similar images",
80
+ "generate_similar": "POST /generate-similar-image - Generate image from description",
81
  "docs": "/docs - Interactive API documentation",
82
  }
83
  }
cloudzy/agents/{similar_image_retriever.py → image_analyzer_2.py} RENAMED
@@ -3,12 +3,14 @@ from pathlib import Path
3
  from PIL import Image
4
  from dotenv import load_dotenv
5
  import os
 
 
6
 
7
  load_dotenv()
8
 
9
 
10
  class ImageAnalyzerAgent:
11
- """Agent for analyzing images using Gemini with smolagents"""
12
 
13
  def __init__(self):
14
  """Initialize the agent with Gemini configuration"""
@@ -28,42 +30,93 @@ class ImageAnalyzerAgent:
28
  self.agent = CodeAgent(
29
  tools=[],
30
  model=self.model,
31
- max_steps=20,
32
- verbosity_level=2
33
  )
34
 
35
- def analyze_images(self, image_paths):
36
  """
37
- Load images from file paths and analyze them using the agent.
38
 
39
  Args:
40
- image_paths: List of Path objects or strings pointing to image files
41
 
42
  Returns:
43
- Agent response with image descriptions
44
  """
45
- # Convert strings to Path objects if needed
46
- image_paths = [Path(path) if isinstance(path, str) else path for path in image_paths]
47
 
48
- # Open and load images
49
- images = [Image.open(img_path) for img_path in image_paths if img_path.exists()]
50
 
51
- print(f"Loaded {len(images)} images from provided paths")
52
-
53
- if not images:
54
- print("No images found. Please provide valid image paths.")
55
- return None
56
 
57
  response = self.agent.run(
58
  """
59
- Describe these images to me:
 
 
60
  """,
61
- images=images
62
  )
63
 
64
- print("\n=== Agent Response ===")
65
- print(response)
66
  return response
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67
 
68
 
69
  # Test with sample images
@@ -76,4 +129,9 @@ if __name__ == "__main__":
76
  ]
77
 
78
  agent = ImageAnalyzerAgent()
79
- agent.analyze_images(sample_image_paths)
 
 
 
 
 
 
3
  from PIL import Image
4
  from dotenv import load_dotenv
5
  import os
6
+ import json
7
+ import re
8
 
9
  load_dotenv()
10
 
11
 
12
  class ImageAnalyzerAgent:
13
+ """Agent for describing images using Gemini with smolagents"""
14
 
15
  def __init__(self):
16
  """Initialize the agent with Gemini configuration"""
 
30
  self.agent = CodeAgent(
31
  tools=[],
32
  model=self.model,
33
+ max_steps=5,
34
+ verbosity_level=1
35
  )
36
 
37
+ def retrieve_similar_images(self, image_path):
38
  """
39
+ Describe a given image.
40
 
41
  Args:
42
+ image_path: Path object or string pointing to an image file
43
 
44
  Returns:
45
+ Description text of the image
46
  """
47
+ image_path = Path(image_path) if isinstance(image_path, str) else image_path
 
48
 
49
+ if not image_path.exists():
50
+ raise FileNotFoundError(f"Image not found at {image_path}")
51
 
52
+ image = Image.open(image_path)
53
+ print(f"Loaded image: {image_path.name}\n")
 
 
 
54
 
55
  response = self.agent.run(
56
  """
57
+ Describe this image in a way that could be used as a prompt for generating a new image inspired by it.
58
+ Focus on the main subjects, composition, style, mood, and colors.
59
+ Avoid mentioning specific names or exact details — instead, describe the overall aesthetic and atmosphere so the result feels similar but not identical.
60
  """,
61
+ images=[image]
62
  )
63
 
 
 
64
  return response
65
+
66
+ def analyze_image_metadata(self, image_path):
67
+ """
68
+ Analyze an image and extract structured metadata (tags, description, caption).
69
+
70
+ Args:
71
+ image_path: Path object or string pointing to an image file
72
+
73
+ Returns:
74
+ Dictionary with keys: tags (list), description (str), caption (str)
75
+
76
+ Raises:
77
+ FileNotFoundError: If image file doesn't exist
78
+ ValueError: If response cannot be parsed into valid JSON
79
+ """
80
+ image_path = Path(image_path) if isinstance(image_path, str) else image_path
81
+
82
+ if not image_path.exists():
83
+ raise FileNotFoundError(f"Image not found at {image_path}")
84
+
85
+ image = Image.open(image_path)
86
+ print(f"Loaded image: {image_path.name}\n")
87
+
88
+ prompt = """
89
+ Describe this image in the following exact format:
90
+
91
+ result: {
92
+ "tags": [list of tags related to the image],
93
+ "description": "a 5-line descriptive description for the image",
94
+ "caption": "a short description for the image"
95
+ }
96
+ """
97
+
98
+ response = self.agent.run(prompt, images=[image])
99
+
100
+ # Handle both dict and string responses
101
+ if isinstance(response, dict):
102
+ # Response is already a dictionary
103
+ return response
104
+
105
+ # If response is a string, extract JSON part
106
+ # Look for the pattern: result: { ... }
107
+ match = re.search(r'result:\s*(\{[\s\S]*\})', response)
108
+
109
+ if not match:
110
+ raise ValueError(f"Could not find JSON in response: {response}")
111
+
112
+ json_str = match.group(1)
113
+
114
+ try:
115
+ # Parse the JSON string into a dictionary
116
+ result_dict = json.loads(json_str)
117
+ return result_dict
118
+ except json.JSONDecodeError as e:
119
+ raise ValueError(f"Failed to parse JSON from response: {json_str}\nError: {str(e)}")
120
 
121
 
122
  # Test with sample images
 
129
  ]
130
 
131
  agent = ImageAnalyzerAgent()
132
+
133
+ # Test with first sample image
134
+ result = agent.analyze_image_metadata(sample_image_paths[0])
135
+ print(f"\n=== Results ===")
136
+ print(f"Description: {result}")
137
+ # print(f"Similar images found: {len(result['similar_images'])}")
cloudzy/inference_models/text_to_image.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from datetime import datetime
3
+ from pathlib import Path
4
+ from huggingface_hub import InferenceClient
5
+ from dotenv import load_dotenv
6
+
7
+ load_dotenv()
8
+
9
+
10
+ class TextToImageGenerator:
11
+ """Class for generating images from text prompts using HuggingFace models"""
12
+
13
+ def __init__(self, model_id: str = "black-forest-labs/FLUX.1-dev", provider: str = "nebius"):
14
+ """
15
+ Initialize the text-to-image generator.
16
+
17
+ Args:
18
+ model_id: HuggingFace model ID (default: FLUX.1-dev for high quality)
19
+ provider: API provider (default: nebius)
20
+ """
21
+ api_key = os.getenv("HF_TOKEN_1")
22
+ if not api_key:
23
+ raise ValueError("HF_TOKEN_1 not found in environment variables")
24
+
25
+ self.client = InferenceClient(
26
+ provider=provider,
27
+ api_key=api_key,
28
+ )
29
+ self.model_id = model_id
30
+ self.uploads_dir = Path(__file__).parent.parent.parent / "uploads"
31
+ self.uploads_dir.mkdir(exist_ok=True)
32
+
33
+ self.app_domain = os.getenv("APP_DOMAIN", "http://127.0.0.1:8000/")
34
+
35
+ def generate(self, prompt: str) -> str:
36
+ """
37
+ Generate an image from a text prompt and save it to the uploads folder.
38
+
39
+ Args:
40
+ prompt: Text description of the image to generate
41
+
42
+ Returns:
43
+ URL of the generated image in format: {APP_DOMAIN}uploads/{filename}
44
+ """
45
+ if not prompt or not prompt.strip():
46
+ raise ValueError("Prompt cannot be empty")
47
+
48
+ try:
49
+ # Generate image using HuggingFace inference
50
+ image = self.client.text_to_image(
51
+ prompt,
52
+ model=self.model_id,
53
+ )
54
+
55
+ # Create filename with timestamp
56
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S_%f")[:-3]
57
+ filename = f"generated_{timestamp}.png"
58
+ filepath = self.uploads_dir / filename
59
+
60
+ # Save image
61
+ image.save(filepath)
62
+
63
+ # Return URL in the required format
64
+ image_url = f"{self.app_domain}uploads/{filename}"
65
+ return image_url
66
+
67
+ except Exception as e:
68
+ raise RuntimeError(f"Failed to generate image: {str(e)}") from e
69
+
70
+
71
+ # Test with sample prompt
72
+ if __name__ == "__main__":
73
+ generator = TextToImageGenerator()
74
+
75
+ # Test with a sample prompt
76
+ prompt = "A beautiful sunset over mountains with birds flying"
77
+ url = generator.generate(prompt)
78
+ print(f"Generated image URL: {url}")
cloudzy/routes/generate.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Generate endpoint for creating similar images"""
2
+ from fastapi import APIRouter, UploadFile, File, HTTPException
3
+ from pathlib import Path
4
+ import os
5
+
6
+ from cloudzy.agents.image_analyzer_2 import ImageAnalyzerAgent
7
+ from cloudzy.inference_models.text_to_image import TextToImageGenerator
8
+ from cloudzy.utils.file_utils import save_uploaded_file
9
+ from cloudzy.schemas import GenerateImageResponse
10
+
11
+ router = APIRouter(tags=["generate"])
12
+
13
+ # Allowed image extensions
14
+ ALLOWED_EXTENSIONS = {".jpg", ".jpeg", ".png", ".gif", ".webp"}
15
+
16
+
17
+ def validate_image_file(filename: str) -> bool:
18
+ """Check if file has valid image extension"""
19
+ return Path(filename).suffix.lower() in ALLOWED_EXTENSIONS
20
+
21
+
22
+ @router.post("/generate-similar-image", response_model=GenerateImageResponse)
23
+ async def generate_similar_image(
24
+ file: UploadFile = File(...),
25
+ ):
26
+ """
27
+ Generate a similar image from an input image.
28
+
29
+ This endpoint:
30
+ 1. Takes an image as input
31
+ 2. Analyzes the image to get a description using ImageAnalyzerAgent
32
+ 3. Uses the description to generate a new image via TextToImageGenerator
33
+ 4. Returns the URL of the generated image
34
+
35
+ Args:
36
+ file: The input image file
37
+
38
+ Returns:
39
+ GenerateImageResponse with the generated image URL and description
40
+ """
41
+ # --- Validate file ---
42
+ if not file.filename:
43
+ raise HTTPException(status_code=400, detail="No filename provided")
44
+
45
+ if not validate_image_file(file.filename):
46
+ raise HTTPException(
47
+ status_code=400,
48
+ detail=f"Invalid file type. Allowed: {', '.join(ALLOWED_EXTENSIONS)}"
49
+ )
50
+
51
+ content = await file.read()
52
+ if not content:
53
+ raise HTTPException(status_code=400, detail="Empty file")
54
+
55
+ # --- Save uploaded file temporarily ---
56
+ try:
57
+ saved_filename = save_uploaded_file(content, file.filename)
58
+ filepath = Path(__file__).parent.parent.parent / "uploads" / saved_filename
59
+ except Exception as e:
60
+ raise HTTPException(status_code=500, detail=f"Failed to save file: {str(e)}")
61
+
62
+ # --- Step 1: Analyze image and get description ---
63
+ try:
64
+ analyzer = ImageAnalyzerAgent()
65
+ description = analyzer.retrieve_similar_images(filepath)
66
+ print(f"Generated description: {description}")
67
+ except Exception as e:
68
+ raise HTTPException(
69
+ status_code=500,
70
+ detail=f"Failed to analyze image: {str(e)}"
71
+ )
72
+
73
+ # --- Step 2: Generate image from description ---
74
+ try:
75
+ generator = TextToImageGenerator()
76
+ generated_image_url = generator.generate(description)
77
+ print(f"Generated image URL: {generated_image_url}")
78
+ except Exception as e:
79
+ raise HTTPException(
80
+ status_code=500,
81
+ detail=f"Failed to generate image: {str(e)}"
82
+ )
83
+
84
+ return GenerateImageResponse(
85
+ description=description,
86
+ generated_image_url=generated_image_url,
87
+ message="Similar image generated successfully"
88
+ )
cloudzy/routes/photo.py CHANGED
@@ -81,7 +81,7 @@ async def list_photos(
81
 
82
  @router.get("/albums", response_model=AlbumsResponse)
83
  async def get_albums(
84
- top_k: int = Query(5, ge=2, le=50),
85
  session: Session = Depends(get_session),
86
  ):
87
  """
 
81
 
82
  @router.get("/albums", response_model=AlbumsResponse)
83
  async def get_albums(
84
+ top_k: int = Query(5, ge=1, le=5),
85
  session: Session = Depends(get_session),
86
  ):
87
  """
cloudzy/routes/search.py CHANGED
@@ -78,59 +78,59 @@ async def search_photos(
78
  )
79
 
80
 
81
- @router.post("/search/image-to-image")
82
- async def image_to_image_search(
83
- reference_photo_id: int = Query(..., description="Reference photo ID"),
84
- top_k: int = Query(5, ge=1, le=50),
85
- session: Session = Depends(get_session),
86
- ):
87
- """
88
- Find similar images to a reference photo (image-to-image search).
89
-
90
- Args:
91
- reference_photo_id: ID of the reference photo
92
- top_k: Number of similar results
93
-
94
- Returns: Similar photos
95
- """
96
- # Get reference photo
97
- statement = select(Photo).where(Photo.id == reference_photo_id)
98
- reference_photo = session.exec(statement).first()
99
-
100
- if not reference_photo:
101
- raise HTTPException(status_code=404, detail=f"Photo {reference_photo_id} not found")
102
-
103
- # Get reference embedding
104
- reference_embedding = reference_photo.get_embedding()
105
- if not reference_embedding:
106
- raise HTTPException(status_code=400, detail="Photo has no embedding")
107
-
108
- # Search in FAISS
109
- search_engine = SearchEngine()
110
- search_results = search_engine.search(
111
- np.array(reference_embedding, dtype=np.float32),
112
- top_k=top_k + 1 # +1 to skip the reference photo itself
113
- )
114
-
115
- # Build results (skip first result which is the reference photo itself)
116
- result_objects = []
117
- for photo_id, distance in search_results[1:]: # Skip first result
118
- statement = select(Photo).where(Photo.id == photo_id)
119
- photo = session.exec(statement).first()
120
 
121
- if photo:
122
- result_objects.append(
123
- SearchResult(
124
- photo_id=photo.id,
125
- filename=photo.filename,
126
- tags=photo.get_tags(),
127
- caption=photo.caption,
128
- distance=distance,
129
- )
130
- )
131
-
132
- return SearchResponse(
133
- query=f"Similar to photo {reference_photo_id}",
134
- results=result_objects[:top_k],
135
- total_results=len(result_objects),
136
- )
 
78
  )
79
 
80
 
81
+ # @router.post("/search/image-to-image")
82
+ # async def image_to_image_search(
83
+ # reference_photo_id: int = Query(..., description="Reference photo ID"),
84
+ # top_k: int = Query(5, ge=1, le=50),
85
+ # session: Session = Depends(get_session),
86
+ # ):
87
+ # """
88
+ # Find similar images to a reference photo (image-to-image search).
89
+
90
+ # Args:
91
+ # reference_photo_id: ID of the reference photo
92
+ # top_k: Number of similar results
93
+
94
+ # Returns: Similar photos
95
+ # """
96
+ # # Get reference photo
97
+ # statement = select(Photo).where(Photo.id == reference_photo_id)
98
+ # reference_photo = session.exec(statement).first()
99
+
100
+ # if not reference_photo:
101
+ # raise HTTPException(status_code=404, detail=f"Photo {reference_photo_id} not found")
102
+
103
+ # # Get reference embedding
104
+ # reference_embedding = reference_photo.get_embedding()
105
+ # if not reference_embedding:
106
+ # raise HTTPException(status_code=400, detail="Photo has no embedding")
107
+
108
+ # # Search in FAISS
109
+ # search_engine = SearchEngine()
110
+ # search_results = search_engine.search(
111
+ # np.array(reference_embedding, dtype=np.float32),
112
+ # top_k=top_k + 1 # +1 to skip the reference photo itself
113
+ # )
114
+
115
+ # # Build results (skip first result which is the reference photo itself)
116
+ # result_objects = []
117
+ # for photo_id, distance in search_results[1:]: # Skip first result
118
+ # statement = select(Photo).where(Photo.id == photo_id)
119
+ # photo = session.exec(statement).first()
120
 
121
+ # if photo:
122
+ # result_objects.append(
123
+ # SearchResult(
124
+ # photo_id=photo.id,
125
+ # filename=photo.filename,
126
+ # tags=photo.get_tags(),
127
+ # caption=photo.caption,
128
+ # distance=distance,
129
+ # )
130
+ # )
131
+
132
+ # return SearchResponse(
133
+ # query=f"Similar to photo {reference_photo_id}",
134
+ # results=result_objects[:top_k],
135
+ # total_results=len(result_objects),
136
+ # )
cloudzy/routes/upload.py CHANGED
@@ -12,6 +12,7 @@ from cloudzy.ai_utils import ImageEmbeddingGenerator
12
  from cloudzy.search_engine import SearchEngine
13
 
14
  from cloudzy.agents.image_analyzer import ImageDescriber
 
15
  from cloudzy.utils.file_upload_service import ImgBBUploader
16
 
17
 
@@ -62,10 +63,11 @@ def validate_image_file(filename: str) -> bool:
62
  """Check if file has valid image extension"""
63
  return Path(filename).suffix.lower() in ALLOWED_EXTENSIONS
64
 
65
- def process_image_in_background(photo_id: int, filepath: str, image_url: str):
66
  """
67
  Background task to:
68
- - Describe the image
 
69
  - Generate embedding
70
  - Update database record
71
  - Index embedding in FAISS
@@ -74,9 +76,30 @@ def process_image_in_background(photo_id: int, filepath: str, image_url: str):
74
  from sqlmodel import select
75
 
76
  try:
77
- describer = ImageDescriber()
78
- print(f"[Background] Processing image {photo_id}...")
79
- result = describer.describe_image(image_url)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80
 
81
  tags = result.get("tags", [])
82
  caption = result.get("caption", "")
@@ -135,12 +158,6 @@ async def upload_photo(
135
  saved_filename = save_uploaded_file(content, file.filename)
136
  filepath = f"uploads/{saved_filename}"
137
 
138
- try:
139
- uploader = ImgBBUploader(expiration=600)
140
- image_url = uploader.upload(filepath)
141
- except Exception as e:
142
- raise HTTPException(status_code=500, detail=f"Image upload failed: {str(e)}")
143
-
144
  APP_DOMAIN = os.getenv("APP_DOMAIN")
145
  image_local_url = f"{APP_DOMAIN}uploads/{saved_filename}"
146
 
@@ -154,13 +171,12 @@ async def upload_photo(
154
  session.commit()
155
  session.refresh(photo)
156
 
157
- # --- Schedule background task ---
158
  if background_tasks:
159
  background_tasks.add_task(
160
  process_image_in_background,
161
  photo_id=photo.id,
162
- filepath=filepath,
163
- image_url=image_url
164
  )
165
 
166
  return UploadResponse(
 
12
  from cloudzy.search_engine import SearchEngine
13
 
14
  from cloudzy.agents.image_analyzer import ImageDescriber
15
+ from cloudzy.agents.image_analyzer_2 import ImageAnalyzerAgent
16
  from cloudzy.utils.file_upload_service import ImgBBUploader
17
 
18
 
 
63
  """Check if file has valid image extension"""
64
  return Path(filename).suffix.lower() in ALLOWED_EXTENSIONS
65
 
66
+ def process_image_in_background(photo_id: int, filepath: str):
67
  """
68
  Background task to:
69
+ - Analyze image metadata (primary method using local file)
70
+ - Fallback to ImgBB upload + ImageDescriber if metadata analysis fails
71
  - Generate embedding
72
  - Update database record
73
  - Index embedding in FAISS
 
76
  from sqlmodel import select
77
 
78
  try:
79
+ result = None
80
+
81
+ # --- Primary method: Analyze metadata from local filepath ---
82
+ try:
83
+ print(f"[Background] Analyzing image metadata locally for photo {photo_id}...")
84
+ analyzer = ImageAnalyzerAgent()
85
+ result = analyzer.analyze_image_metadata(filepath)
86
+ print(f"[Background] Successfully extracted metadata for photo {photo_id}")
87
+ except Exception as metadata_error:
88
+ print(f"[Background] Metadata analysis failed for photo {photo_id}: {metadata_error}")
89
+ print(f"[Background] Falling back to ImgBB upload + ImageDescriber...")
90
+
91
+ # --- Fallback method: Upload to ImgBB and use ImageDescriber ---
92
+ try:
93
+ uploader = ImgBBUploader(expiration=600)
94
+ image_url = uploader.upload(filepath)
95
+ print(f"[Background] Image {photo_id} uploaded to ImgBB: {image_url}")
96
+
97
+ describer = ImageDescriber()
98
+ print(f"[Background] Processing image {photo_id} with ImageDescriber...")
99
+ result = describer.describe_image(image_url)
100
+ print(f"[Background] Successfully described image using ImageDescriber")
101
+ except Exception as fallback_error:
102
+ raise Exception(f"Both metadata analysis and ImageDescriber failed - Primary: {str(metadata_error)}, Fallback: {str(fallback_error)}")
103
 
104
  tags = result.get("tags", [])
105
  caption = result.get("caption", "")
 
158
  saved_filename = save_uploaded_file(content, file.filename)
159
  filepath = f"uploads/{saved_filename}"
160
 
 
 
 
 
 
 
161
  APP_DOMAIN = os.getenv("APP_DOMAIN")
162
  image_local_url = f"{APP_DOMAIN}uploads/{saved_filename}"
163
 
 
171
  session.commit()
172
  session.refresh(photo)
173
 
174
+ # --- Schedule background task (includes ImgBB upload) ---
175
  if background_tasks:
176
  background_tasks.add_task(
177
  process_image_in_background,
178
  photo_id=photo.id,
179
+ filepath=filepath
 
180
  )
181
 
182
  return UploadResponse(
cloudzy/schemas.py CHANGED
@@ -65,4 +65,11 @@ class AlbumItem(BaseModel):
65
  album_summary: str
66
  album: List[PhotoItem]
67
 
68
- AlbumsResponse = List[AlbumItem]
 
 
 
 
 
 
 
 
65
  album_summary: str
66
  album: List[PhotoItem]
67
 
68
+ AlbumsResponse = List[AlbumItem]
69
+
70
+
71
+ class GenerateImageResponse(BaseModel):
72
+ """Response for generating a similar image"""
73
+ description: str
74
+ generated_image_url: str
75
+ message: str
cloudzy/search_engine.py CHANGED
@@ -3,6 +3,7 @@ import faiss
3
  import numpy as np
4
  from typing import List, Tuple
5
  import os
 
6
 
7
 
8
  class SearchEngine:
@@ -19,20 +20,21 @@ class SearchEngine:
19
  base_index = faiss.IndexFlatL2(dim)
20
  self.index = faiss.IndexIDMap(base_index)
21
 
22
- def create_albums(self, top_k: int = 5, distance_threshold: float = 0.3) -> List[List[int]]:
23
  """
24
  Group similar images into albums (clusters).
25
 
26
- For each unvisited photo, finds its top_k most similar photos and creates an album.
27
  Photos are marked as visited to avoid duplicate albums.
28
  Only includes photos within the distance threshold.
29
 
30
  Args:
31
- top_k: Number of similar images to find for each album
32
- distance_threshold: Maximum distance to consider photos as similar (default 0.5)
 
33
 
34
  Returns:
35
- List of albums, each album is a list of photo_ids
36
  """
37
  from cloudzy.database import SessionLocal
38
  from cloudzy.models import Photo
@@ -45,11 +47,18 @@ class SearchEngine:
45
  # Get all photo IDs from FAISS index
46
  id_map = self.index.id_map
47
  all_ids = [id_map.at(i) for i in range(id_map.size())]
 
 
 
48
 
49
  visited = set()
50
  albums = []
51
 
52
  for photo_id in all_ids:
 
 
 
 
53
  # Skip if already in an album
54
  if photo_id in visited:
55
  continue
@@ -67,7 +76,7 @@ class SearchEngine:
67
 
68
  # Search for similar images
69
  query_embedding = np.array(embedding).reshape(1, -1).astype(np.float32)
70
- distances, ids = self.index.search(query_embedding, top_k)
71
 
72
  # Build album: collect similar photos that haven't been visited and are within threshold
73
  album = []
@@ -153,3 +162,42 @@ class SearchEngine:
153
  "dimension": self.dim,
154
  "index_type": type(self.index).__name__,
155
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  import numpy as np
4
  from typing import List, Tuple
5
  import os
6
+ import random
7
 
8
 
9
  class SearchEngine:
 
20
  base_index = faiss.IndexFlatL2(dim)
21
  self.index = faiss.IndexIDMap(base_index)
22
 
23
+ def create_albums(self, top_k: int = 5, distance_threshold: float = 0.3, album_size: int = 5) -> List[List[int]]:
24
  """
25
  Group similar images into albums (clusters).
26
 
27
+ Returns exactly top_k albums, each containing up to album_size similar photos.
28
  Photos are marked as visited to avoid duplicate albums.
29
  Only includes photos within the distance threshold.
30
 
31
  Args:
32
+ top_k: Number of albums to return
33
+ distance_threshold: Maximum distance to consider photos as similar (default 0.3)
34
+ album_size: How many similar photos to search for per album (default 5)
35
 
36
  Returns:
37
+ List of top_k albums, each album is a list of photo_ids (randomized order each call)
38
  """
39
  from cloudzy.database import SessionLocal
40
  from cloudzy.models import Photo
 
47
  # Get all photo IDs from FAISS index
48
  id_map = self.index.id_map
49
  all_ids = [id_map.at(i) for i in range(id_map.size())]
50
+
51
+ # Shuffle for randomization - different albums each call
52
+ random.shuffle(all_ids)
53
 
54
  visited = set()
55
  albums = []
56
 
57
  for photo_id in all_ids:
58
+ # Stop if we have enough albums
59
+ if len(albums) >= top_k:
60
+ break
61
+
62
  # Skip if already in an album
63
  if photo_id in visited:
64
  continue
 
76
 
77
  # Search for similar images
78
  query_embedding = np.array(embedding).reshape(1, -1).astype(np.float32)
79
+ distances, ids = self.index.search(query_embedding, album_size)
80
 
81
  # Build album: collect similar photos that haven't been visited and are within threshold
82
  album = []
 
162
  "dimension": self.dim,
163
  "index_type": type(self.index).__name__,
164
  }
165
+
166
+ def debug_distances(self, sample_size: int = 3) -> dict:
167
+ """Debug distances between photos to understand why albums aren't grouping"""
168
+ from cloudzy.database import SessionLocal
169
+ from cloudzy.models import Photo
170
+ from sqlmodel import select
171
+
172
+ self.load()
173
+ if self.index.ntotal == 0:
174
+ return {"error": "No embeddings in index"}
175
+
176
+ id_map = self.index.id_map
177
+ all_ids = [id_map.at(i) for i in range(min(id_map.size(), sample_size))]
178
+
179
+ debug_info = {}
180
+ session = SessionLocal()
181
+ try:
182
+ for photo_id in all_ids:
183
+ photo = session.exec(select(Photo).where(Photo.id == photo_id)).first()
184
+ if not photo:
185
+ continue
186
+
187
+ embedding = photo.get_embedding()
188
+ if not embedding:
189
+ continue
190
+
191
+ query_embedding = np.array(embedding).reshape(1, -1).astype(np.float32)
192
+ distances, ids = self.index.search(query_embedding, 5)
193
+
194
+ debug_info[photo_id] = {
195
+ "top_5_results": [
196
+ {"id": int(pid), "distance": float(d)}
197
+ for pid, d in zip(ids[0], distances[0]) if pid != -1
198
+ ]
199
+ }
200
+ finally:
201
+ session.close()
202
+
203
+ return debug_info