Fraser commited on
Commit
0d9403e
ยท
1 Parent(s): 69b86e7

cool stuff

Browse files
Files changed (4) hide show
  1. .gitignore +1 -0
  2. CLAUDE.md +153 -50
  3. app.py +693 -73
  4. requirements.txt +1 -0
.gitignore ADDED
@@ -0,0 +1 @@
 
 
1
+ *.pyc
CLAUDE.md CHANGED
@@ -4,9 +4,11 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
4
 
5
  ## Project Overview
6
 
7
- This is a Hugging Face Space that serves as a backend server for the Piclets Discovery game. It uses Gradio to provide API endpoints and HuggingFace Datasets for persistent storage.
8
 
9
- **Core Concept**: Each real-world object has ONE canonical Piclet! Players discover these by scanning objects, with variations tracked based on attributes (e.g., "velvet pillow" is a variation of the canonical "pillow").
 
 
10
 
11
  ## Architecture
12
 
@@ -66,37 +68,85 @@ Examples:
66
 
67
  ## API Endpoints
68
 
69
- ### Discovery Endpoints
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70
 
71
- 1. **search_piclet**: Find canonical or variation Piclets
72
- - Input: `object_name`, `attributes[]`
73
- - Returns: `status` (new/existing/variation), `piclet` data
74
 
75
- 2. **create_canonical**: Register first discovery of an object
76
- - Input: `object_name`, `piclet_data`, `username`
77
- - Returns: Created canonical Piclet
 
 
 
 
 
 
 
 
 
78
 
79
- 3. **create_variation**: Add variation to existing canonical
80
- - Input: `canonical_id`, `attributes[]`, `piclet_data`, `username`, `object_name`
81
- - Returns: Created variation
82
 
83
- 4. **increment_scan_count**: Track popularity
84
- - Input: `piclet_id`, `object_name`
85
- - Returns: Updated scan count
86
 
87
- ### Social Endpoints
 
88
 
89
- 5. **get_recent_activity**: Global discovery feed
90
- - Input: `limit` (default 20)
91
- - Returns: Recent discoveries with metadata
92
 
93
- 6. **get_leaderboard**: Top discoverers
94
- - Input: `limit` (default 10)
95
- - Returns: Ranked users by rarity score
96
 
97
- 7. **get_user_profile**: Individual stats
98
- - Input: `username`
99
- - Returns: User's discoveries and statistics
100
 
101
  ## Rarity System
102
 
@@ -128,26 +178,49 @@ Rarity scoring for leaderboard:
128
 
129
  ## Integration with Frontend
130
 
131
- The frontend (`../piclets/`) connects using Gradio Client:
132
 
133
  ```javascript
134
- // Frontend connection
135
  const client = await window.gradioClient.Client.connect("Fraser/piclets-server");
136
 
137
- // Search for Piclet
138
- const result = await client.predict("/search_piclet", {
139
- object_name: "pillow",
140
- attributes: ["velvet", "blue"]
 
 
 
 
 
 
 
 
 
 
 
 
141
  });
 
142
 
143
- // Create canonical
144
- const created = await client.predict("/create_canonical", {
145
- object_name: "pillow",
146
- piclet_data: JSON.stringify(picletData),
147
- username: "player123"
 
 
 
148
  });
149
  ```
150
 
 
 
 
 
 
 
 
151
  ## Development
152
 
153
  ### Local Testing
@@ -164,12 +237,35 @@ git add -A && git commit -m "Update" && git push
164
  ```
165
 
166
  ### Environment Variables
167
- - `HF_TOKEN`: **Required** - HuggingFace write token (set in Space Secrets)
168
- - `ADMIN_PASSWORD`: **Required** - Password for web UI access (set in Space Secrets)
169
  - `DATASET_REPO`: Target dataset (default: "Fraser/piclets")
170
 
 
 
171
  ## Key Implementation Details
172
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
173
  ### Variation Matching
174
  - Uses set intersection to find attribute overlap
175
  - 50% match threshold for variations
@@ -181,23 +277,30 @@ git add -A && git commit -m "Update" && git push
181
  - Temporary files for uploads
182
 
183
  ### Error Handling
 
184
  - Graceful fallbacks for missing data
185
  - Default user profiles for new users
186
- - Try-catch blocks around all dataset operations
 
187
 
188
  ## Future Enhancements
189
 
190
- 1. **Activity Log**: Separate timeline file for better performance
191
- 2. **Image Storage**: Store Piclet images in dataset
192
- 3. **Badges/Achievements**: Track discovery milestones
193
- 4. **Trading System**: Allow users to trade variations
194
- 5. **Seasonal Events**: Time-limited discoveries
195
- 6. **OAuth Integration**: Verified HuggingFace accounts
 
 
196
 
197
  ## Security Considerations
198
 
199
- - All data is public by design
200
- - No sensitive information stored
201
- - Username-only system (no passwords)
202
- - Input validation on all endpoints
203
- - Rate limiting should be added for production
 
 
 
 
4
 
5
  ## Project Overview
6
 
7
+ This is a Hugging Face Space that serves as the **complete backend** for the Piclets Discovery game. It orchestrates AI services, handles Piclet generation, and manages persistent storage.
8
 
9
+ **Core Concept**: Each real-world object has ONE canonical Piclet! Players scan objects with photos, and the server generates Pokemon-style creatures using AI, tracking canonical discoveries and variations (e.g., "velvet pillow" is a variation of the canonical "pillow").
10
+
11
+ **Architecture Philosophy**: The server handles ALL AI orchestration securely. The frontend is a pure UI that makes a single API call. This prevents client-side manipulation and ensures fair play.
12
 
13
  ## Architecture
14
 
 
68
 
69
  ## API Endpoints
70
 
71
+ The frontend only needs these **5 public endpoints**:
72
+
73
+ ### 1. **generate_piclet** (Scanner)
74
+ Complete Piclet generation workflow - the main endpoint.
75
+
76
+ - **Input**:
77
+ - `image`: User's photo (File)
78
+ - `hf_token`: User's HuggingFace OAuth token (string)
79
+ - **Process**:
80
+ 1. Verifies `hf_token` โ†’ gets user info
81
+ 2. Uses token to connect to **JoyCaption** โ†’ generates detailed image description
82
+ 3. Uses token to call **GPT-OSS-120B** โ†’ generates Pokemon concept (object, variation, stats, description)
83
+ 4. Parses concept to extract structured data
84
+ 5. Uses token to call **Flux-Schnell** โ†’ generates Piclet image
85
+ 6. Checks dataset for canonical/variation match
86
+ 7. Saves to dataset with user attribution
87
+ 8. Updates user profile (discoveries, rarity score)
88
+ - **Returns**:
89
+ ```json
90
+ {
91
+ "success": true,
92
+ "piclet": {/* complete Piclet data */},
93
+ "discoveryStatus": "new" | "variation" | "existing",
94
+ "canonicalId": "pillow_canonical",
95
+ "message": "Congratulations! You discovered the first pillow Piclet!"
96
+ }
97
+ ```
98
+ - **Security**: Uses user's token to call AI services, consuming THEIR GPU quota (not the server's)
99
+
100
+ ### 2. **get_user_piclets** (User Collection)
101
+ Get user's discovered Piclets and stats.
102
+
103
+ - **Input**: `hf_token` (string)
104
+ - **Returns**:
105
+ ```json
106
+ {
107
+ "success": true,
108
+ "piclets": [{/* list of discoveries */}],
109
+ "stats": {
110
+ "username": "...",
111
+ "totalFinds": 42,
112
+ "uniqueFinds": 15,
113
+ "rarityScore": 1250
114
+ }
115
+ }
116
+ ```
117
 
118
+ ### 3. **get_object_details** (Object Data)
119
+ Get complete object information (canonical + all variations).
 
120
 
121
+ - **Input**: `object_name` (string, e.g., "pillow", "macbook")
122
+ - **Returns**:
123
+ ```json
124
+ {
125
+ "success": true,
126
+ "objectName": "pillow",
127
+ "canonical": {/* canonical data */},
128
+ "variations": [{/* variation 1 */}, {/* variation 2 */}],
129
+ "totalScans": 157,
130
+ "variationCount": 8
131
+ }
132
+ ```
133
 
134
+ ### 4. **get_recent_activity** (Activity Feed)
135
+ Recent discoveries across all users.
 
136
 
137
+ - **Input**: `limit` (int, default 20)
138
+ - **Returns**: List of recent discoveries with timestamps
 
139
 
140
+ ### 5. **get_leaderboard** (Top Users)
141
+ Top discoverers by rarity score.
142
 
143
+ - **Input**: `limit` (int, default 10)
144
+ - **Returns**: Ranked users with stats
 
145
 
146
+ ---
 
 
147
 
148
+ **Internal Functions** (not exposed to frontend):
149
+ - `search_piclet()`, `create_canonical()`, `create_variation()`, `increment_scan_count()` - Used internally by `generate_piclet()`
 
150
 
151
  ## Rarity System
152
 
 
178
 
179
  ## Integration with Frontend
180
 
181
+ The frontend (`../piclets/`) uses these **5 simple API calls**:
182
 
183
  ```javascript
184
+ // Connect to server
185
  const client = await window.gradioClient.Client.connect("Fraser/piclets-server");
186
 
187
+ // 1. Scanner - Generate complete Piclet (ONE CALL - server does everything!)
188
+ const scanResult = await client.predict("/generate_piclet", {
189
+ image: imageFile,
190
+ hf_token: userToken
191
+ });
192
+ const { success, piclet, discoveryStatus, message } = scanResult.data[0];
193
+
194
+ // 2. User Collection - Get user's Piclets + stats
195
+ const myPiclets = await client.predict("/get_user_piclets", {
196
+ hf_token: userToken
197
+ });
198
+ const { piclets, stats } = myPiclets.data[0];
199
+
200
+ // 3. Object Details - Get object info (canonical + variations)
201
+ const objectInfo = await client.predict("/get_object_details", {
202
+ object_name: "pillow"
203
  });
204
+ const { canonical, variations, totalScans } = objectInfo.data[0];
205
 
206
+ // 4. Activity Feed - Get recent discoveries
207
+ const activity = await client.predict("/get_recent_activity", {
208
+ limit: 20
209
+ });
210
+
211
+ // 5. Leaderboard - Get top users
212
+ const leaders = await client.predict("/get_leaderboard", {
213
+ limit: 10
214
  });
215
  ```
216
 
217
+ **Why This Design?**
218
+ - **Clean API**: Only 5 endpoints, each with a clear purpose
219
+ - **Security**: All AI orchestration happens server-side (can't be manipulated)
220
+ - **Simplicity**: Frontend is pure UI, no complex orchestration logic
221
+ - **Fairness**: Uses user's GPU quota, not server's
222
+ - **Reliability**: Server handles retries and error recovery
223
+
224
  ## Development
225
 
226
  ### Local Testing
 
237
  ```
238
 
239
  ### Environment Variables
240
+ - `HF_TOKEN`: **Required** - HuggingFace write token for dataset operations (set in Space Secrets)
241
+ - `ADMIN_PASSWORD`: Optional - Password for web UI access (set in Space Secrets)
242
  - `DATASET_REPO`: Target dataset (default: "Fraser/piclets")
243
 
244
+ Note: Users' `hf_token` (passed in API calls) is separate from server's `HF_TOKEN` (for dataset writes).
245
+
246
  ## Key Implementation Details
247
 
248
+ ### AI Service Integration
249
+ The server uses `gradio_client` to call external AI services with the user's token:
250
+
251
+ - **JoyCaption** (`fancyfeast/joy-caption-alpha-two`): Detailed image captioning with brand/model recognition
252
+ - **GPT-OSS-120B** (`amd/gpt-oss-120b-chatbot`): Concept generation and parsing
253
+ - **Flux-Schnell** (`black-forest-labs/FLUX.1-schnell`): Anime-style Piclet image generation
254
+
255
+ Each service is called with the user's `hf_token`, consuming their GPU quota.
256
+
257
+ ### Concept Parsing
258
+ GPT-OSS generates structured markdown with sections:
259
+ - Canonical Object (specific brand/model, not generic)
260
+ - Variation (distinctive attribute or "canonical")
261
+ - Object Rarity (determines tier)
262
+ - Monster Name, Type, Stats
263
+ - Physical Stats (height, weight)
264
+ - Personality, Description
265
+ - Monster Image Prompt
266
+
267
+ The parser uses regex to extract each section and clean the data.
268
+
269
  ### Variation Matching
270
  - Uses set intersection to find attribute overlap
271
  - 50% match threshold for variations
 
277
  - Temporary files for uploads
278
 
279
  ### Error Handling
280
+ - Token verification before any operations
281
  - Graceful fallbacks for missing data
282
  - Default user profiles for new users
283
+ - Try-catch blocks around all operations
284
+ - Detailed logging for debugging
285
 
286
  ## Future Enhancements
287
 
288
+ 1. **Background Removal**: Add server-side background removal (currently done on frontend)
289
+ 2. **Activity Log**: Separate timeline file for better performance
290
+ 3. **Image Storage**: Store Piclet images directly in dataset (currently stores URLs)
291
+ 4. **Badges/Achievements**: Track discovery milestones
292
+ 5. **Trading System**: Allow users to trade variations
293
+ 6. **Seasonal Events**: Time-limited discoveries
294
+ 7. **Rate Limiting**: Per-user rate limits to prevent abuse
295
+ 8. **Caching**: Cache AI responses for identical images
296
 
297
  ## Security Considerations
298
 
299
+ - **Token Verification**: All operations verify HF OAuth tokens via `https://huggingface.co/oauth/userinfo`
300
+ - **User Attribution**: Discoveries tracked by stable HF `sub` (user ID), not username
301
+ - **Fair GPU Usage**: Users consume their own GPU quota, not server's
302
+ - **Public Data**: All discovery data is public by design (embracing open discovery)
303
+ - **No Client Manipulation**: AI orchestration happens server-side only
304
+ - **Input Validation**: File uploads and token formats validated
305
+ - **No Sensitive Data**: No passwords or private info stored
306
+ - **Future**: Rate limiting per user to prevent abuse
app.py CHANGED
@@ -1,4 +1,5 @@
1
  import gradio as gr
 
2
  import json
3
  import os
4
  import re
@@ -243,6 +244,279 @@ class PicletDiscoveryService:
243
  print(f"Failed to update global stats: {e}")
244
  return {}
245
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
246
  # API Endpoints
247
 
248
  def search_piclet(object_name: str, attributes: List[str]) -> dict:
@@ -502,6 +776,357 @@ def increment_scan_count(piclet_id: str, object_name: str) -> dict:
502
  "error": str(e)
503
  }
504
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
505
  def get_recent_activity(limit: int = 20) -> dict:
506
  """
507
  Get recent discoveries across all users
@@ -617,23 +1242,6 @@ def get_leaderboard(limit: int = 10) -> dict:
617
  "leaderboard": []
618
  }
619
 
620
- def get_user_profile(username: str) -> dict:
621
- """
622
- Get user's discovery profile
623
- """
624
- try:
625
- user_data = PicletDiscoveryService.load_user_data(username)
626
- return {
627
- "success": True,
628
- "profile": user_data
629
- }
630
- except Exception as e:
631
- return {
632
- "success": False,
633
- "error": str(e),
634
- "profile": None
635
- }
636
-
637
  # Create Gradio interface
638
  with gr.Blocks(title="Piclets Discovery Server") as app:
639
  gr.Markdown("""
@@ -642,58 +1250,63 @@ with gr.Blocks(title="Piclets Discovery Server") as app:
642
  Backend service for the Piclets discovery game. Each real-world object has ONE canonical Piclet!
643
  """)
644
 
645
- with gr.Tab("Search Piclet"):
 
 
 
 
 
646
  with gr.Row():
647
  with gr.Column():
648
- search_object = gr.Textbox(label="Object Name", placeholder="e.g., pillow")
649
- search_attrs = gr.Textbox(label="Attributes (comma-separated)", placeholder="e.g., velvet, blue")
650
- search_btn = gr.Button("Search", variant="primary")
651
  with gr.Column():
652
- search_result = gr.JSON(label="Search Result")
653
 
654
- search_btn.click(
655
- fn=lambda obj, attrs: search_piclet(obj, [a.strip() for a in attrs.split(",")] if attrs else []),
656
- inputs=[search_object, search_attrs],
657
- outputs=search_result
658
  )
659
 
660
- with gr.Tab("Create Canonical"):
 
 
 
 
661
  with gr.Row():
662
  with gr.Column():
663
- canonical_object = gr.Textbox(label="Object Name")
664
- canonical_data = gr.Textbox(label="Piclet Data (JSON)", lines=10)
665
- canonical_user = gr.Textbox(label="Username")
666
- canonical_btn = gr.Button("Create Canonical", variant="primary")
667
  with gr.Column():
668
- canonical_result = gr.JSON(label="Creation Result")
669
 
670
- canonical_btn.click(
671
- fn=create_canonical,
672
- inputs=[canonical_object, canonical_data, canonical_user],
673
- outputs=canonical_result
674
  )
675
 
676
- with gr.Tab("Create Variation"):
 
 
 
 
677
  with gr.Row():
678
  with gr.Column():
679
- var_object = gr.Textbox(label="Object Name")
680
- var_canonical = gr.Textbox(label="Canonical ID")
681
- var_attrs = gr.Textbox(label="Variation Attributes (comma-separated)")
682
- var_data = gr.Textbox(label="Piclet Data (JSON)", lines=10)
683
- var_user = gr.Textbox(label="Username")
684
- var_btn = gr.Button("Create Variation", variant="primary")
685
  with gr.Column():
686
- var_result = gr.JSON(label="Creation Result")
687
-
688
- var_btn.click(
689
- fn=lambda obj, cid, attrs, data, user: create_variation(
690
- cid, [a.strip() for a in attrs.split(",")] if attrs else [], data, user, obj
691
- ),
692
- inputs=[var_object, var_canonical, var_attrs, var_data, var_user],
693
- outputs=var_result
694
  )
695
 
696
- with gr.Tab("Activity Feed"):
697
  activity_limit = gr.Slider(5, 50, value=20, label="Number of Activities")
698
  activity_btn = gr.Button("Get Recent Activity")
699
  activity_result = gr.JSON(label="Recent Discoveries")
@@ -715,32 +1328,39 @@ with gr.Blocks(title="Piclets Discovery Server") as app:
715
  outputs=leader_result
716
  )
717
 
718
- with gr.Tab("User Profile"):
719
- profile_user = gr.Textbox(label="Username")
720
- profile_btn = gr.Button("Get Profile")
721
- profile_result = gr.JSON(label="User Profile")
722
-
723
- profile_btn.click(
724
- fn=get_user_profile,
725
- inputs=profile_user,
726
- outputs=profile_result
727
- )
728
-
729
  # API Documentation
730
  gr.Markdown("""
731
- ## API Endpoints
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
732
 
733
- All endpoints accept JSON and return JSON responses.
 
 
 
734
 
735
- - **search_piclet**: Search for canonical or variation Piclets
736
- - **create_canonical**: Register a new canonical Piclet
737
- - **create_variation**: Add a variation to existing canonical
738
- - **increment_scan_count**: Track discovery popularity
739
- - **get_recent_activity**: Global discovery feed
740
- - **get_leaderboard**: Top discoverers
741
- - **get_user_profile**: Individual discovery stats
742
 
743
- See API_DOCUMENTATION.md for detailed usage.
 
744
  """)
745
 
746
  if __name__ == "__main__":
 
1
  import gradio as gr
2
+ from gradio_client import Client
3
  import json
4
  import os
5
  import re
 
244
  print(f"Failed to update global stats: {e}")
245
  return {}
246
 
247
+ class PicletGeneratorService:
248
+ """
249
+ Orchestrates Piclet generation by calling external AI services
250
+ Uses user's hf_token to consume their GPU quota
251
+ """
252
+
253
+ # Space endpoints
254
+ JOY_CAPTION_SPACE = "fancyfeast/joy-caption-alpha-two"
255
+ GPT_OSS_SPACE = "amd/gpt-oss-120b-chatbot"
256
+ FLUX_SPACE = "black-forest-labs/FLUX.1-schnell"
257
+
258
+ @staticmethod
259
+ async def generate_enhanced_caption(image_path: str, hf_token: str) -> str:
260
+ """Generate detailed image description using JoyCaption"""
261
+ try:
262
+ print(f"Connecting to JoyCaption space with user token...")
263
+ client = await Client.connect(
264
+ PicletGeneratorService.JOY_CAPTION_SPACE,
265
+ hf_token=hf_token
266
+ )
267
+
268
+ print(f"Generating caption for image...")
269
+ result = await client.predict(
270
+ image=image_path,
271
+ caption_type="Descriptive",
272
+ caption_length="medium-length",
273
+ extra_options=[],
274
+ name_input="",
275
+ custom_prompt="Describe this image in detail, identifying any recognizable objects, brands, logos, or specific models. Be specific about product names and types.",
276
+ api_name="/stream_chat"
277
+ )
278
+
279
+ # JoyCaption returns tuple: (image, caption_text)
280
+ caption = result[1] if isinstance(result, (list, tuple)) and len(result) > 1 else str(result)
281
+ print(f"Caption generated: {caption[:100]}...")
282
+ return caption
283
+
284
+ except Exception as e:
285
+ print(f"Failed to generate caption: {e}")
286
+ raise Exception(f"Caption generation failed: {str(e)}")
287
+
288
+ @staticmethod
289
+ async def generate_text_with_gpt(prompt: str, hf_token: str) -> str:
290
+ """Generate text using GPT-OSS-120B"""
291
+ try:
292
+ print(f"Connecting to GPT-OSS space...")
293
+ client = await Client.connect(
294
+ PicletGeneratorService.GPT_OSS_SPACE,
295
+ hf_token=hf_token
296
+ )
297
+
298
+ print(f"Generating text...")
299
+ result = await client.predict(
300
+ message=prompt,
301
+ history=[],
302
+ system_prompt="You are a helpful assistant that creates Pokemon-style monster concepts based on real-world objects.",
303
+ temperature=0.7,
304
+ api_name="/chat"
305
+ )
306
+
307
+ # Extract response text (GPT-OSS formats with Analysis and Response)
308
+ response_text = result[0] if isinstance(result, (list, tuple)) else str(result)
309
+
310
+ # Try to extract Response section
311
+ response_match = re.search(r'\*\*๐Ÿ’ฌ Response:\*\*\s*\n\n([\s\S]*)', response_text)
312
+ if response_match:
313
+ return response_match.group(1).strip()
314
+
315
+ # Fallback: extract after "assistantfinal"
316
+ final_match = re.search(r'assistantfinal\s*([\s\S]*)', response_text)
317
+ if final_match:
318
+ return final_match.group(1).strip()
319
+
320
+ return response_text
321
+
322
+ except Exception as e:
323
+ print(f"Failed to generate text: {e}")
324
+ raise Exception(f"Text generation failed: {str(e)}")
325
+
326
+ @staticmethod
327
+ async def generate_piclet_concept(caption: str, hf_token: str) -> dict:
328
+ """
329
+ Generate complete Piclet concept from image caption
330
+ Returns parsed concept with object name, variation, stats, etc.
331
+ """
332
+ concept_prompt = f"""You are analyzing an image to create a Pokemon-style creature. Here's the image description:
333
+
334
+ "{caption}"
335
+
336
+ Your task:
337
+ 1. Identify the PRIMARY PHYSICAL OBJECT with SPECIFICITY (e.g., "macbook" not "laptop", "eiffel tower" not "tower", "iphone" not "phone", "starbucks mug" not "mug")
338
+ 2. Determine if there's a meaningful VARIATION (e.g., "silver", "pro", "night", "gaming", "vintage")
339
+ 3. Assess rarity based on uniqueness
340
+ 4. Create a complete Pokemon-style monster concept
341
+
342
+ Format your response EXACTLY as follows:
343
+ ```md
344
+ # Canonical Object
345
+ {{Specific object name: "macbook", "eiffel tower", "iphone", "tesla", "le creuset mug", "nintendo switch"}}
346
+ {{NOT generic terms like: "laptop", "tower", "phone", "car", "mug", "console"}}
347
+ {{Include brand/model/landmark name when identifiable}}
348
+
349
+ # Variation
350
+ {{OPTIONAL: one distinctive attribute like "silver", "pro", "night", "gaming", OR use "canonical" if this is the standard/default version with no special variation}}
351
+
352
+ # Object Rarity
353
+ {{common, uncommon, rare, epic, or legendary based on object uniqueness}}
354
+
355
+ # Monster Name
356
+ {{Creative 8-11 letter name based on the SPECIFIC object, e.g., "Macbyte" for MacBook, "Towerfell" for Eiffel Tower}}
357
+
358
+ # Primary Type
359
+ {{beast, bug, aquatic, flora, mineral, space, machina, structure, culture, or cuisine}}
360
+
361
+ # Physical Stats
362
+ Height: {{e.g., "1.2m" or "3'5\\""}}
363
+ Weight: {{e.g., "15kg" or "33 lbs"}}
364
+
365
+ # Personality
366
+ {{1-2 sentences describing personality traits}}
367
+
368
+ # Monster Description
369
+ {{2-3 paragraphs describing how the SPECIFIC object's features translate into monster features. Reference the actual object by name. This is the creature's bio.}}
370
+
371
+ # Monster Image Prompt
372
+ {{Concise visual description for anime-style image generation focusing on colors, shapes, and key features inspired by the specific object}}
373
+ ```
374
+
375
+ CRITICAL RULES:
376
+ - Canonical Object MUST be SPECIFIC: "macbook" not "laptop", "big ben" not "clock tower", "coca cola" not "soda"
377
+ - If you can identify a brand, model, or proper name from the description, USE IT
378
+ - Variation should be meaningful and distinctive (material, style, color, context, or model variant)
379
+ - Monster Description must describe the CREATURE with references to the specific object's features
380
+ - Primary Type must match the object category (machina for electronics, structure for buildings, etc.)"""
381
+
382
+ response_text = await PicletGeneratorService.generate_text_with_gpt(concept_prompt, hf_token)
383
+
384
+ # Parse the concept
385
+ return PicletGeneratorService.parse_concept(response_text)
386
+
387
+ @staticmethod
388
+ def parse_concept(concept_text: str) -> dict:
389
+ """Parse structured concept text into dict"""
390
+ # Remove code block markers if present
391
+ if '```' in concept_text:
392
+ code_block_match = re.search(r'```(?:md|markdown)?\s*\n([\s\S]*?)```', concept_text)
393
+ if code_block_match:
394
+ concept_text = code_block_match.group(1).strip()
395
+
396
+ def extract_section(text: str, section: str) -> str:
397
+ """Extract content of a markdown section"""
398
+ pattern = rf'\*{{0,2}}#\s*{re.escape(section)}\s*\*{{0,2}}\s*\n([\s\S]*?)(?=^\*{{0,2}}#|$)'
399
+ match = re.search(pattern, text, re.MULTILINE)
400
+ if match:
401
+ content = match.group(1).strip()
402
+ # Remove curly braces and quotes that GPT sometimes adds
403
+ content = re.sub(r'^[{"]|["}]$', '', content)
404
+ content = re.sub(r'^.*:\s*["\']|["\']$', '', content)
405
+ return content.strip()
406
+ return ''
407
+
408
+ # Extract all sections
409
+ object_name = extract_section(concept_text, 'Canonical Object').lower()
410
+ variation_text = extract_section(concept_text, 'Variation')
411
+ rarity_text = extract_section(concept_text, 'Object Rarity').lower()
412
+ monster_name = extract_section(concept_text, 'Monster Name')
413
+ primary_type = extract_section(concept_text, 'Primary Type').lower()
414
+ description = extract_section(concept_text, 'Monster Description')
415
+ image_prompt = extract_section(concept_text, 'Monster Image Prompt')
416
+
417
+ # Parse physical stats
418
+ physical_stats_text = extract_section(concept_text, 'Physical Stats')
419
+ height_match = re.search(r'Height:\s*(.+)', physical_stats_text, re.IGNORECASE)
420
+ weight_match = re.search(r'Weight:\s*(.+)', physical_stats_text, re.IGNORECASE)
421
+ height = height_match.group(1).strip() if height_match else None
422
+ weight = weight_match.group(1).strip() if weight_match else None
423
+
424
+ personality = extract_section(concept_text, 'Personality')
425
+
426
+ # Clean monster name
427
+ if monster_name:
428
+ monster_name = re.sub(r'\*+', '', monster_name) # Remove asterisks
429
+ if ',' in monster_name:
430
+ monster_name = monster_name.split(',')[0]
431
+ if len(monster_name) > 12:
432
+ monster_name = monster_name[:12]
433
+
434
+ # Parse variation
435
+ attributes = []
436
+ if variation_text and variation_text.lower() not in ['none', 'canonical', '']:
437
+ attributes = [variation_text.lower()]
438
+
439
+ # Map rarity to tier
440
+ tier = 'medium'
441
+ if 'common' in rarity_text:
442
+ tier = 'low'
443
+ elif 'uncommon' in rarity_text:
444
+ tier = 'medium'
445
+ elif 'rare' in rarity_text and 'epic' not in rarity_text:
446
+ tier = 'high'
447
+ elif 'legendary' in rarity_text or 'epic' in rarity_text or 'mythical' in rarity_text:
448
+ tier = 'legendary'
449
+
450
+ return {
451
+ 'objectName': object_name,
452
+ 'attributes': attributes,
453
+ 'concept': concept_text,
454
+ 'stats': {
455
+ 'name': monster_name or 'Unknown',
456
+ 'description': description,
457
+ 'tier': tier,
458
+ 'primaryType': primary_type or 'beast',
459
+ 'height': height,
460
+ 'weight': weight,
461
+ 'personality': personality
462
+ },
463
+ 'imagePrompt': image_prompt
464
+ }
465
+
466
+ @staticmethod
467
+ async def generate_piclet_image(image_prompt: str, tier: str, hf_token: str) -> dict:
468
+ """Generate Piclet image using Flux"""
469
+ try:
470
+ print(f"Connecting to Flux space...")
471
+ client = await Client.connect(
472
+ PicletGeneratorService.FLUX_SPACE,
473
+ hf_token=hf_token
474
+ )
475
+
476
+ tier_descriptions = {
477
+ 'low': 'simple and iconic design',
478
+ 'medium': 'detailed and well-crafted design',
479
+ 'high': 'highly detailed and impressive design with special effects',
480
+ 'legendary': 'highly detailed and majestic design with dramatic lighting and aura effects'
481
+ }
482
+
483
+ full_prompt = f"{image_prompt}\nNow generate an Pokรฉmon Anime image of the monster in an idle pose with a plain dark-grey background. This is a {tier} tier monster with a {tier_descriptions.get(tier, tier_descriptions['medium'])}. The monster should not be attacking or in motion. The full monster must be visible within the frame."
484
+
485
+ print(f"Generating image with prompt: {full_prompt[:100]}...")
486
+ result = await client.predict(
487
+ prompt=full_prompt,
488
+ seed=0,
489
+ randomize_seed=True,
490
+ width=1024,
491
+ height=1024,
492
+ num_inference_steps=4,
493
+ api_name="/infer"
494
+ )
495
+
496
+ # Extract image URL and seed
497
+ image_data = result[0] if isinstance(result, (list, tuple)) else result
498
+ seed = result[1] if isinstance(result, (list, tuple)) and len(result) > 1 else 0
499
+
500
+ # Handle different return formats
501
+ image_url = None
502
+ if isinstance(image_data, str):
503
+ image_url = image_data
504
+ elif isinstance(image_data, dict):
505
+ image_url = image_data.get('url') or image_data.get('path')
506
+
507
+ if not image_url:
508
+ raise Exception("Failed to extract image URL from Flux response")
509
+
510
+ return {
511
+ 'imageUrl': image_url,
512
+ 'seed': seed,
513
+ 'prompt': image_prompt
514
+ }
515
+
516
+ except Exception as e:
517
+ print(f"Failed to generate image: {e}")
518
+ raise Exception(f"Image generation failed: {str(e)}")
519
+
520
  # API Endpoints
521
 
522
  def search_piclet(object_name: str, attributes: List[str]) -> dict:
 
776
  "error": str(e)
777
  }
778
 
779
+ async def generate_piclet(image, hf_token: str) -> dict:
780
+ """
781
+ Complete Piclet generation workflow - single endpoint
782
+ Takes user's image and hf_token, returns generated Piclet with discovery status
783
+
784
+ Args:
785
+ image: Uploaded image file (Gradio file input)
786
+ hf_token: User's HuggingFace OAuth token
787
+
788
+ Returns:
789
+ {
790
+ "success": bool,
791
+ "piclet": {complete piclet data},
792
+ "discoveryStatus": "new" | "variation" | "existing",
793
+ "canonicalId": str (if variation/existing),
794
+ "message": str
795
+ }
796
+ """
797
+ try:
798
+ # Validate token and get user info
799
+ user_info = verify_hf_token(hf_token)
800
+ if not user_info:
801
+ return {
802
+ "success": False,
803
+ "error": "Invalid HuggingFace token"
804
+ }
805
+
806
+ print(f"Generating Piclet for user: {user_info.get('preferred_username', 'unknown')}")
807
+
808
+ # Get user profile (creates if doesn't exist)
809
+ user_profile = PicletDiscoveryService.get_or_create_user_profile(user_info)
810
+
811
+ # Extract image path from Gradio file input
812
+ image_path = image if isinstance(image, str) else image.name if hasattr(image, 'name') else str(image)
813
+
814
+ # Step 1: Generate caption
815
+ print("Step 1/5: Generating image caption...")
816
+ caption = await PicletGeneratorService.generate_enhanced_caption(image_path, hf_token)
817
+
818
+ # Step 2: Generate concept
819
+ print("Step 2/5: Generating Piclet concept...")
820
+ concept_data = await PicletGeneratorService.generate_piclet_concept(caption, hf_token)
821
+
822
+ object_name = concept_data['objectName']
823
+ attributes = concept_data['attributes']
824
+ stats = concept_data['stats']
825
+ image_prompt = concept_data['imagePrompt']
826
+ concept_text = concept_data['concept']
827
+
828
+ # Step 3: Generate image
829
+ print("Step 3/5: Generating Piclet image...")
830
+ image_result = await PicletGeneratorService.generate_piclet_image(
831
+ image_prompt,
832
+ stats['tier'],
833
+ hf_token
834
+ )
835
+
836
+ # Step 4: Check for canonical/variation
837
+ print("Step 4/5: Checking for existing canonical...")
838
+ existing_data = PicletDiscoveryService.load_piclet_data(object_name)
839
+
840
+ discovery_status = 'new'
841
+ canonical_id = None
842
+ scan_count = 1
843
+
844
+ if existing_data:
845
+ # Check if this is an exact canonical match (no attributes)
846
+ if not attributes or len(attributes) == 0:
847
+ discovery_status = 'existing'
848
+ canonical_id = existing_data['canonical']['typeId']
849
+ # Increment scan count
850
+ existing_data['canonical']['scanCount'] = existing_data['canonical'].get('scanCount', 0) + 1
851
+ scan_count = existing_data['canonical']['scanCount']
852
+ PicletDiscoveryService.save_piclet_data(object_name, existing_data)
853
+ else:
854
+ # Check for matching variation
855
+ variations = existing_data.get('variations', [])
856
+ matched_variation = None
857
+
858
+ for variation in variations:
859
+ var_attrs = set(variation.get('attributes', []))
860
+ search_attrs = set(attributes)
861
+ overlap = len(var_attrs.intersection(search_attrs))
862
+
863
+ if overlap >= len(search_attrs) * 0.5:
864
+ matched_variation = variation
865
+ discovery_status = 'existing'
866
+ canonical_id = existing_data['canonical']['typeId']
867
+ # Increment variation scan count
868
+ variation['scanCount'] = variation.get('scanCount', 0) + 1
869
+ scan_count = variation['scanCount']
870
+ PicletDiscoveryService.save_piclet_data(object_name, existing_data)
871
+ break
872
+
873
+ if not matched_variation:
874
+ discovery_status = 'variation'
875
+ canonical_id = existing_data['canonical']['typeId']
876
+
877
+ # Step 5: Save new discovery if needed
878
+ print("Step 5/5: Saving to dataset...")
879
+ if discovery_status == 'new':
880
+ # Create new canonical
881
+ type_id = f"{PicletDiscoveryService.normalize_object_name(object_name)}_canonical"
882
+ canonical_data = {
883
+ "canonical": {
884
+ "objectName": object_name,
885
+ "typeId": type_id,
886
+ "discoveredBy": user_info['preferred_username'],
887
+ "discovererSub": user_info['sub'],
888
+ "discovererUsername": user_info['preferred_username'],
889
+ "discovererName": user_info.get('name'),
890
+ "discovererPicture": user_info.get('picture'),
891
+ "discoveredAt": datetime.now().isoformat(),
892
+ "scanCount": scan_count,
893
+ "picletData": {
894
+ "typeId": type_id,
895
+ "nickname": stats['name'],
896
+ "stats": stats,
897
+ "imageUrl": image_result['imageUrl'],
898
+ "imageCaption": caption,
899
+ "concept": concept_text,
900
+ "imagePrompt": image_prompt,
901
+ "createdAt": datetime.now().isoformat()
902
+ }
903
+ },
904
+ "variations": []
905
+ }
906
+ canonical_id = type_id
907
+
908
+ PicletDiscoveryService.save_piclet_data(object_name, canonical_data)
909
+
910
+ # Update user profile
911
+ user_profile["discoveries"].append(type_id)
912
+ user_profile["uniqueFinds"] = user_profile.get("uniqueFinds", 0) + 1
913
+ user_profile["totalFinds"] = user_profile.get("totalFinds", 0) + 1
914
+ user_profile["rarityScore"] = user_profile.get("rarityScore", 0) + 100
915
+ PicletDiscoveryService.save_user_data(user_info['sub'], user_profile)
916
+
917
+ elif discovery_status == 'variation':
918
+ # Create new variation
919
+ existing_data = PicletDiscoveryService.load_piclet_data(object_name)
920
+ variation_id = f"{PicletDiscoveryService.normalize_object_name(object_name)}_{len(existing_data['variations']) + 1:03d}"
921
+
922
+ variation_data = {
923
+ "typeId": variation_id,
924
+ "attributes": attributes,
925
+ "discoveredBy": user_info['preferred_username'],
926
+ "discovererSub": user_info['sub'],
927
+ "discovererUsername": user_info['preferred_username'],
928
+ "discovererName": user_info.get('name'),
929
+ "discovererPicture": user_info.get('picture'),
930
+ "discoveredAt": datetime.now().isoformat(),
931
+ "scanCount": scan_count,
932
+ "picletData": {
933
+ "typeId": variation_id,
934
+ "nickname": stats['name'],
935
+ "stats": stats,
936
+ "imageUrl": image_result['imageUrl'],
937
+ "imageCaption": caption,
938
+ "concept": concept_text,
939
+ "imagePrompt": image_prompt,
940
+ "createdAt": datetime.now().isoformat()
941
+ }
942
+ }
943
+
944
+ existing_data['variations'].append(variation_data)
945
+ PicletDiscoveryService.save_piclet_data(object_name, existing_data)
946
+
947
+ # Update user profile
948
+ user_profile["discoveries"].append(variation_id)
949
+ user_profile["totalFinds"] = user_profile.get("totalFinds", 0) + 1
950
+ user_profile["rarityScore"] = user_profile.get("rarityScore", 0) + 50
951
+ PicletDiscoveryService.save_user_data(user_info['sub'], user_profile)
952
+
953
+ # Build complete response
954
+ piclet_data = {
955
+ "typeId": canonical_id,
956
+ "nickname": stats['name'],
957
+ "stats": stats,
958
+ "imageUrl": image_result['imageUrl'],
959
+ "imageCaption": caption,
960
+ "concept": concept_text,
961
+ "imagePrompt": image_prompt,
962
+ "objectName": object_name,
963
+ "attributes": attributes,
964
+ "discoveryStatus": discovery_status,
965
+ "scanCount": scan_count,
966
+ "createdAt": datetime.now().isoformat()
967
+ }
968
+
969
+ messages = {
970
+ 'new': f"Congratulations! You discovered the first {object_name} Piclet!",
971
+ 'variation': f"You found a new variation of {object_name}!",
972
+ 'existing': f"You encountered a known {object_name} Piclet."
973
+ }
974
+
975
+ return {
976
+ "success": True,
977
+ "piclet": piclet_data,
978
+ "discoveryStatus": discovery_status,
979
+ "canonicalId": canonical_id,
980
+ "message": messages.get(discovery_status, "Piclet generated!")
981
+ }
982
+
983
+ except Exception as e:
984
+ print(f"Failed to generate Piclet: {e}")
985
+ import traceback
986
+ traceback.print_exc()
987
+ return {
988
+ "success": False,
989
+ "error": str(e)
990
+ }
991
+
992
+ def get_object_details(object_name: str) -> dict:
993
+ """
994
+ Get complete details for an object (canonical + all variations)
995
+
996
+ Args:
997
+ object_name: The object name (e.g., "pillow", "macbook")
998
+
999
+ Returns:
1000
+ {
1001
+ "success": bool,
1002
+ "objectName": str,
1003
+ "canonical": {canonical data},
1004
+ "variations": [list of variations],
1005
+ "totalScans": int
1006
+ }
1007
+ """
1008
+ try:
1009
+ # Load the object data
1010
+ piclet_data = PicletDiscoveryService.load_piclet_data(object_name)
1011
+
1012
+ if not piclet_data:
1013
+ return {
1014
+ "success": False,
1015
+ "error": f"No piclet found for object '{object_name}'",
1016
+ "objectName": object_name
1017
+ }
1018
+
1019
+ # Calculate total scans across canonical and variations
1020
+ total_scans = piclet_data['canonical'].get('scanCount', 0)
1021
+ for variation in piclet_data.get('variations', []):
1022
+ total_scans += variation.get('scanCount', 0)
1023
+
1024
+ return {
1025
+ "success": True,
1026
+ "objectName": object_name,
1027
+ "canonical": piclet_data['canonical'],
1028
+ "variations": piclet_data.get('variations', []),
1029
+ "totalScans": total_scans,
1030
+ "variationCount": len(piclet_data.get('variations', []))
1031
+ }
1032
+
1033
+ except Exception as e:
1034
+ print(f"Failed to get object details: {e}")
1035
+ return {
1036
+ "success": False,
1037
+ "error": str(e),
1038
+ "objectName": object_name
1039
+ }
1040
+
1041
+ def get_user_piclets(hf_token: str) -> dict:
1042
+ """
1043
+ Get all Piclets discovered by a specific user
1044
+
1045
+ Args:
1046
+ hf_token: User's HuggingFace OAuth token
1047
+
1048
+ Returns:
1049
+ {
1050
+ "success": bool,
1051
+ "piclets": [list of piclet discoveries],
1052
+ "stats": {user stats}
1053
+ }
1054
+ """
1055
+ try:
1056
+ # Verify token and get user info
1057
+ user_info = verify_hf_token(hf_token)
1058
+ if not user_info:
1059
+ return {
1060
+ "success": False,
1061
+ "error": "Invalid HuggingFace token",
1062
+ "piclets": []
1063
+ }
1064
+
1065
+ # Load user profile
1066
+ user_profile = PicletDiscoveryService.load_user_data(user_info['sub'])
1067
+
1068
+ # Get list of discoveries
1069
+ discoveries = user_profile.get('discoveries', [])
1070
+ piclets = []
1071
+
1072
+ # Load each discovered piclet
1073
+ for type_id in discoveries:
1074
+ # Extract object name from type_id (e.g., "pillow_canonical" -> "pillow")
1075
+ object_name = type_id.rsplit('_', 1)[0]
1076
+
1077
+ # Load the piclet data
1078
+ piclet_data = PicletDiscoveryService.load_piclet_data(object_name)
1079
+ if piclet_data:
1080
+ # Check if it's canonical or variation
1081
+ if piclet_data['canonical']['typeId'] == type_id:
1082
+ piclets.append({
1083
+ 'type': 'canonical',
1084
+ 'typeId': type_id,
1085
+ 'objectName': object_name,
1086
+ 'discoveredAt': piclet_data['canonical']['discoveredAt'],
1087
+ 'scanCount': piclet_data['canonical'].get('scanCount', 1),
1088
+ 'picletData': piclet_data['canonical'].get('picletData', {})
1089
+ })
1090
+ else:
1091
+ # Find matching variation
1092
+ for variation in piclet_data.get('variations', []):
1093
+ if variation['typeId'] == type_id:
1094
+ piclets.append({
1095
+ 'type': 'variation',
1096
+ 'typeId': type_id,
1097
+ 'objectName': object_name,
1098
+ 'attributes': variation.get('attributes', []),
1099
+ 'discoveredAt': variation['discoveredAt'],
1100
+ 'scanCount': variation.get('scanCount', 1),
1101
+ 'picletData': variation.get('picletData', {})
1102
+ })
1103
+ break
1104
+
1105
+ # Sort by discovery date (most recent first)
1106
+ piclets.sort(key=lambda x: x.get('discoveredAt', ''), reverse=True)
1107
+
1108
+ return {
1109
+ "success": True,
1110
+ "piclets": piclets,
1111
+ "stats": {
1112
+ "username": user_info.get('preferred_username'),
1113
+ "name": user_info.get('name'),
1114
+ "picture": user_info.get('picture'),
1115
+ "totalFinds": user_profile.get('totalFinds', 0),
1116
+ "uniqueFinds": user_profile.get('uniqueFinds', 0),
1117
+ "rarityScore": user_profile.get('rarityScore', 0),
1118
+ "joinedAt": user_profile.get('joinedAt')
1119
+ }
1120
+ }
1121
+
1122
+ except Exception as e:
1123
+ print(f"Failed to get user piclets: {e}")
1124
+ return {
1125
+ "success": False,
1126
+ "error": str(e),
1127
+ "piclets": []
1128
+ }
1129
+
1130
  def get_recent_activity(limit: int = 20) -> dict:
1131
  """
1132
  Get recent discoveries across all users
 
1242
  "leaderboard": []
1243
  }
1244
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1245
  # Create Gradio interface
1246
  with gr.Blocks(title="Piclets Discovery Server") as app:
1247
  gr.Markdown("""
 
1250
  Backend service for the Piclets discovery game. Each real-world object has ONE canonical Piclet!
1251
  """)
1252
 
1253
+ with gr.Tab("Generate Piclet"):
1254
+ gr.Markdown("""
1255
+ ## ๐ŸŽฎ Complete Piclet Generator
1256
+ Upload an image and provide your HuggingFace token to generate a complete Piclet.
1257
+ This endpoint handles the entire workflow: captioning, concept generation, image creation, and dataset storage.
1258
+ """)
1259
  with gr.Row():
1260
  with gr.Column():
1261
+ gen_image = gr.Image(label="Upload Image", type="filepath")
1262
+ gen_token = gr.Textbox(label="HuggingFace Token", placeholder="hf_...", type="password")
1263
+ gen_btn = gr.Button("Generate Piclet", variant="primary")
1264
  with gr.Column():
1265
+ gen_result = gr.JSON(label="Generated Piclet Result")
1266
 
1267
+ gen_btn.click(
1268
+ fn=generate_piclet,
1269
+ inputs=[gen_image, gen_token],
1270
+ outputs=gen_result
1271
  )
1272
 
1273
+ with gr.Tab("My Piclets"):
1274
+ gr.Markdown("""
1275
+ ## ๐Ÿ“š Your Discovery Collection
1276
+ View all Piclets you've discovered (includes your stats).
1277
+ """)
1278
  with gr.Row():
1279
  with gr.Column():
1280
+ my_token = gr.Textbox(label="HuggingFace Token", placeholder="hf_...", type="password")
1281
+ my_btn = gr.Button("Get My Piclets", variant="primary")
 
 
1282
  with gr.Column():
1283
+ my_result = gr.JSON(label="My Piclets")
1284
 
1285
+ my_btn.click(
1286
+ fn=get_user_piclets,
1287
+ inputs=my_token,
1288
+ outputs=my_result
1289
  )
1290
 
1291
+ with gr.Tab("Object Details"):
1292
+ gr.Markdown("""
1293
+ ## ๐Ÿ” View Object Details
1294
+ Get complete information about an object (canonical + all variations).
1295
+ """)
1296
  with gr.Row():
1297
  with gr.Column():
1298
+ obj_name = gr.Textbox(label="Object Name", placeholder="e.g., pillow, macbook")
1299
+ obj_btn = gr.Button("Get Details", variant="primary")
 
 
 
 
1300
  with gr.Column():
1301
+ obj_result = gr.JSON(label="Object Details")
1302
+
1303
+ obj_btn.click(
1304
+ fn=get_object_details,
1305
+ inputs=obj_name,
1306
+ outputs=obj_result
 
 
1307
  )
1308
 
1309
+ with gr.Tab("Recent Activity"):
1310
  activity_limit = gr.Slider(5, 50, value=20, label="Number of Activities")
1311
  activity_btn = gr.Button("Get Recent Activity")
1312
  activity_result = gr.JSON(label="Recent Discoveries")
 
1328
  outputs=leader_result
1329
  )
1330
 
 
 
 
 
 
 
 
 
 
 
 
1331
  # API Documentation
1332
  gr.Markdown("""
1333
+ ## ๐Ÿ”Œ Public API Endpoints
1334
+
1335
+ All endpoints return JSON responses. The frontend only needs these 5 endpoints:
1336
+
1337
+ ### 1. **generate_piclet** (Scanner)
1338
+ Complete Piclet generation workflow.
1339
+ - Input: `image` (File), `hf_token` (string)
1340
+ - Output: Generated Piclet with discovery status
1341
+
1342
+ ### 2. **get_user_piclets** (User Collection)
1343
+ Get user's discovered Piclets and stats.
1344
+ - Input: `hf_token` (string)
1345
+ - Output: List of Piclets + user stats (total/unique finds, rarity score)
1346
+
1347
+ ### 3. **get_object_details** (Object Data)
1348
+ Get complete object info (canonical + all variations).
1349
+ - Input: `object_name` (string)
1350
+ - Output: Canonical + variations + total scans
1351
 
1352
+ ### 4. **get_recent_activity** (Activity Feed)
1353
+ Recent discoveries across all users.
1354
+ - Input: `limit` (int, default 20)
1355
+ - Output: Recent discoveries with timestamps
1356
 
1357
+ ### 5. **get_leaderboard** (Top Users)
1358
+ Top discoverers by rarity score.
1359
+ - Input: `limit` (int, default 10)
1360
+ - Output: Ranked users with stats
 
 
 
1361
 
1362
+ ---
1363
+ *Note: Internal helper functions (search_piclet, create_canonical, etc.) are used by generate_piclet but not exposed to frontend.*
1364
  """)
1365
 
1366
  if __name__ == "__main__":
requirements.txt CHANGED
@@ -1,4 +1,5 @@
1
  gradio==5.38.2
 
2
  Pillow>=9.0.0
3
  huggingface_hub>=0.20.0
4
  datasets>=2.15.0
 
1
  gradio==5.38.2
2
+ gradio_client>=1.0.0
3
  Pillow>=9.0.0
4
  huggingface_hub>=0.20.0
5
  datasets>=2.15.0