-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmemecoin_routes.py
More file actions
1119 lines (921 loc) · 38 KB
/
memecoin_routes.py
File metadata and controls
1119 lines (921 loc) · 38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Memecoin Routes for File-Based Operations
FastAPI routes for memecoin CRUD operations that integrate with the
MemeStorageOrchestrator to provide API-first access to filesystem-based
memecoin data without direct file mounts.
"""
import logging
import time
from datetime import datetime
from typing import Any, Dict, List, Optional, Tuple
from fastapi import APIRouter, Depends, HTTPException, Query, Response
from pydantic import BaseModel, Field
from src.orchestrators.meme_storage import MemeStorageOrchestrator
from src.util.error_sanitizer import sanitize_error_message
from src.web_ui.api_models.base import APIResponse
from src.web_ui.api_models.memecoin import (
GeneratedMemecoinDetailResponse,
GeneratedMemecoinListResponse,
MemecoinDatabaseStats,
MemecoinDetailResponse,
MemecoinListResponse,
MemecoinResponse,
MemecoinStatsData,
MemecoinStatsItem,
MemecoinStatsResponse,
MemecoinUpdateRequest,
MemecoinUpdateResponse,
)
from src.web_ui.dependencies import get_meme_storage_orchestrator, get_generation_orchestrator
# Configure logging with explicit level
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
# Add handler if no handlers exist (uvicorn compatibility)
if not logger.handlers:
handler = logging.StreamHandler()
handler.setLevel(logging.INFO)
formatter = logging.Formatter('%(levelname)s: %(name)s - %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
# Test log to verify logging works
logger.info("🔧 Memecoin routes module loaded - logging is active")
# Create router
router = APIRouter(prefix="/api/memecoins", tags=["memecoin_operations"])
# Stats cache: (stats_data, timestamp)
_stats_cache: Optional[Tuple[MemecoinStatsData, float]] = None
STATS_CACHE_TIMEOUT = 30 # seconds
# ================================================================================
# PYDANTIC MODELS FOR GENERATED MEMECOIN EDITING
# ================================================================================
class GeneratedEditFeedbackRequest(BaseModel):
"""Request model for generated memecoin edit feedback with optional current metadata
Supports two workflows:
1. User provides only AI feedback → Uses stored metadata as baseline
2. User edits fields + provides AI feedback → Uses current_metadata as baseline
"""
feedback: str = Field(
...,
min_length=1,
max_length=2000,
description="User feedback about what to edit"
)
current_metadata: Optional[Dict[str, Any]] = Field(
default=None,
description="Current token metadata from UI (name, ticker, description, tags). "
"If provided, used as baseline for AI edits. If None, loads from storage."
)
class GeneratedEditProposalResponse(BaseModel):
"""Response model for generated memecoin edit proposal generation"""
status: int = Field(default=200, description="HTTP status code")
success: bool = Field(..., description="Whether operation succeeded")
message: str = Field(..., description="Human-readable message")
proposal_uuid: Optional[str] = Field(
None, description="UUID for the cached proposal"
)
proposal: Optional[Dict] = Field(None, description="The edit proposal data")
class GeneratedAcceptProposalRequest(BaseModel):
"""Request model for accepting a generated memecoin edit proposal"""
proposal_uuid: str = Field(
..., min_length=1, description="UUID of the cached proposal"
)
edited_proposal: Optional[Dict] = Field(
None,
description="Optional manually edited proposal (overrides cached version)"
)
class GeneratedAcceptProposalResponse(BaseModel):
"""Response model for accepting a generated memecoin edit proposal"""
status: int = Field(default=200, description="HTTP status code")
success: bool = Field(..., description="Whether operation succeeded")
message: str = Field(..., description="Human-readable message")
@router.get(
"/stats",
response_model=MemecoinStatsResponse,
summary="Get memecoin knowledge base statistics",
description="""Get aggregated statistics for the entire memecoin knowledge base.
**Statistics Included:**
- Pending memecoins count (from filesystem)
- Approved memecoins count (from filesystem)
- Vector database count (from ChromaDB)
- Total count across all categories
**Caching:**
- Stats are cached for 30 seconds for optimal performance
- Automatic refresh on cache expiration
**Use Cases:**
- Dashboard statistics display
- Homepage stats summary
- System health monitoring
- Data completeness validation
""",
response_description="Aggregated memecoin statistics with counts and timestamps",
)
async def get_memecoin_stats(
orchestrator: MemeStorageOrchestrator = Depends(get_meme_storage_orchestrator),
) -> MemecoinStatsResponse:
"""
Get aggregated statistics for memecoin knowledge base
Aggregates counts from:
- Pending directory (filesystem via orchestrator)
- Approved directory (filesystem via orchestrator)
- Vector database (ChromaDB via database interface)
Returns:
MemecoinStatsResponse with counts and timestamps
"""
global _stats_cache
try:
# Check cache validity
current_time = time.time()
if _stats_cache is not None:
cached_data, cache_timestamp = _stats_cache
if current_time - cache_timestamp < STATS_CACHE_TIMEOUT:
logger.info(
f"📊 Returning cached stats (age: {current_time - cache_timestamp:.1f}s)"
)
return MemecoinStatsResponse(
status=200,
success=True,
message="Stats retrieved from cache",
stats=cached_data,
)
logger.info("📊 Fetching fresh memecoin stats...")
# Get pending count from orchestrator
pending_result = await orchestrator.get_pending_memecoins(page=1, limit=1)
pending_count = pending_result.total
pending_timestamp = datetime.utcnow().isoformat() + "Z"
logger.info(f" • Pending: {pending_count}")
# Get approved count from orchestrator
approved_result = await orchestrator.get_approved_memecoins(page=1, limit=1)
approved_count = approved_result.total
approved_timestamp = datetime.utcnow().isoformat() + "Z"
logger.info(f" • Approved: {approved_count}")
# Get database stats from orchestrator
db_stats = await orchestrator.get_database_stats()
logger.debug(f"Raw db_stats from vector store: {db_stats}")
db_count = db_stats.get("total_examples", 0)
# Database interface may provide separate counts for text/image embeddings
db_text_count = db_stats.get("text_embeddings", db_count)
db_image_count = db_stats.get("image_embeddings", db_count)
db_timestamp = datetime.utcnow().isoformat() + "Z"
logger.info(
f" • Database: {db_count} (text: {db_text_count}, images: {db_image_count})"
)
# Calculate total
total_count = pending_count + approved_count + db_count
# Build response
stats_data = MemecoinStatsData(
pending=MemecoinStatsItem(
count=pending_count, last_updated=pending_timestamp
),
approved=MemecoinStatsItem(
count=approved_count, last_updated=approved_timestamp
),
database=MemecoinDatabaseStats(
count=db_count,
text_embeddings=db_text_count,
image_embeddings=db_image_count,
last_updated=db_timestamp,
),
total=total_count,
)
# Update cache
_stats_cache = (stats_data, current_time)
logger.info(f"✅ Stats cached: Total {total_count} memecoins")
return MemecoinStatsResponse(
status=200,
success=True,
message="Stats retrieved successfully",
stats=stats_data,
)
except Exception as e:
logger.error(f"❌ Error getting memecoin stats: {e}")
sanitized_error = sanitize_error_message(e)
raise HTTPException(status_code=500, detail=sanitized_error)
@router.get("/pending", response_model=MemecoinListResponse)
async def get_pending_memecoins(
response: Response,
page: int = Query(1, ge=1, description="Page number (1-based)"),
limit: int = Query(
100, ge=1, le=500, description="Number of memecoins per page (max 500)"
),
search: Optional[str] = Query(
None, description="Search query for tags, name, ticker, or description"
),
orchestrator: MemeStorageOrchestrator = Depends(get_meme_storage_orchestrator),
) -> MemecoinListResponse:
"""
Get paginated list of pending memecoins from filesystem
Args:
page: Page number (1-based)
limit: Number of memecoins per page (max 500)
search: Search query for filtering
Returns:
MemecoinListResponse with pending memecoins (Base64 images)
"""
try:
logger.info(
f"📄 Getting pending memecoins (page={page}, limit={limit}, search={search})"
)
result = await orchestrator.get_pending_memecoins(
page=page, limit=limit, search=search
)
logger.info(
f"✅ Retrieved {len(result.memecoins)} pending memecoins from filesystem"
)
# Set cache-control headers
response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
response.headers["Pragma"] = "no-cache"
response.headers["Expires"] = "0"
return result
except Exception as e:
logger.error(f"❌ Error getting pending memecoins: {e}")
sanitized_error = sanitize_error_message(e)
raise HTTPException(status_code=500, detail=sanitized_error)
@router.get("/approved", response_model=MemecoinListResponse)
async def get_approved_memecoins(
response: Response,
page: int = Query(1, ge=1, description="Page number (1-based)"),
limit: int = Query(
100, ge=1, le=500, description="Number of memecoins per page (max 500)"
),
search: Optional[str] = Query(
None, description="Search query for tags, name, ticker, or description"
),
orchestrator: MemeStorageOrchestrator = Depends(get_meme_storage_orchestrator),
) -> MemecoinListResponse:
"""
Get paginated list of approved memecoins from filesystem
Args:
page: Page number (1-based)
limit: Number of memecoins per page (max 500)
search: Search query for filtering
Returns:
MemecoinListResponse with approved memecoins (Base64 images)
"""
try:
logger.info(
f"📄 Getting approved memecoins (page={page}, limit={limit}, search={search})"
)
result = await orchestrator.get_approved_memecoins(
page=page, limit=limit, search=search
)
logger.info(
f"✅ Retrieved {len(result.memecoins)} approved memecoins from filesystem"
)
# Set cache-control headers
response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
response.headers["Pragma"] = "no-cache"
response.headers["Expires"] = "0"
return result
except Exception as e:
logger.error(f"❌ Error getting approved memecoins: {e}")
sanitized_error = sanitize_error_message(e)
raise HTTPException(status_code=500, detail=sanitized_error)
@router.post("/approve/{token_address}", response_model=APIResponse)
async def approve_memecoin(
token_address: str,
orchestrator: MemeStorageOrchestrator = Depends(get_meme_storage_orchestrator),
) -> APIResponse:
"""
Approve a pending memecoin (move from pending to approved directory)
Args:
token_address: Token address of memecoin to approve
Returns:
APIResponse with operation results
"""
try:
logger.info(f"✅ Approving memecoin: {token_address}")
success, message, memecoin_data = await orchestrator.approve_memecoin(
token_address
)
if success:
logger.info(f"✅ Successfully approved memecoin: {token_address}")
return APIResponse(status=200, success=True, message=message)
else:
logger.error(f"❌ Failed to approve memecoin: {token_address} - {message}")
return APIResponse(
status=400, success=False, message=message, error=message
)
except Exception as e:
logger.error(f"❌ Error approving memecoin {token_address}: {e}")
sanitized_error = sanitize_error_message(e)
raise HTTPException(status_code=500, detail=sanitized_error)
@router.delete("/pending/{token_address}", response_model=APIResponse)
async def delete_pending_memecoin(
token_address: str,
orchestrator: MemeStorageOrchestrator = Depends(get_meme_storage_orchestrator),
) -> APIResponse:
"""
Delete a pending memecoin permanently
Args:
token_address: Token address of memecoin to delete
Returns:
APIResponse confirming deletion
"""
try:
logger.info(f"🗑️ Deleting pending memecoin: {token_address}")
success, message, memecoin_data = await orchestrator.delete_memecoin(
token_address, source="pending"
)
if success:
logger.info(f"✅ Successfully deleted pending memecoin: {token_address}")
return APIResponse(status=200, success=True, message=message)
else:
logger.error(
f"❌ Failed to delete pending memecoin: {token_address} - {message}"
)
return APIResponse(
status=400, success=False, message=message, error=message
)
except Exception as e:
logger.error(f"❌ Error deleting pending memecoin {token_address}: {e}")
raise HTTPException(
status_code=500, detail=f"Failed to delete pending memecoin: {e}"
)
@router.delete("/approved/{token_address}", response_model=APIResponse)
async def delete_approved_memecoin(
token_address: str,
orchestrator: MemeStorageOrchestrator = Depends(get_meme_storage_orchestrator),
) -> APIResponse:
"""
Delete an approved memecoin permanently
Args:
token_address: Token address of memecoin to delete
Returns:
APIResponse confirming deletion
"""
try:
logger.info(f"🗑️ Deleting approved memecoin: {token_address}")
success, message, memecoin_data = await orchestrator.delete_memecoin(
token_address, source="approved"
)
if success:
logger.info(f"✅ Successfully deleted approved memecoin: {token_address}")
return APIResponse(status=200, success=True, message=message)
else:
logger.error(
f"❌ Failed to delete approved memecoin: {token_address} - {message}"
)
return APIResponse(
status=400, success=False, message=message, error=message
)
except Exception as e:
logger.error(f"❌ Error deleting approved memecoin {token_address}: {e}")
raise HTTPException(
status_code=500, detail=f"Failed to delete approved memecoin: {e}"
)
@router.delete("/database/{token_address}", response_model=APIResponse)
async def delete_database_memecoin(
token_address: str,
orchestrator: MemeStorageOrchestrator = Depends(get_meme_storage_orchestrator),
) -> APIResponse:
"""
Delete a memecoin from the vector database permanently
This deletes from ChromaDB collections (text + image embeddings),
associated image files, and caption files.
Args:
token_address: Token address of memecoin to delete
orchestrator: MemeStorageOrchestrator for database operations
Returns:
APIResponse confirming deletion
"""
try:
logger.info(f"🗑️ Deleting memecoin from vector database: {token_address}")
success = await orchestrator.delete_database_memecoin(token_address)
if success:
logger.info(
f"✅ Successfully deleted memecoin from vector database: {token_address}"
)
return APIResponse(
status=200,
success=True,
message=f"Memecoin {token_address} deleted from vector database",
)
else:
logger.warning(f"⚠️ Memecoin not found in vector database: {token_address}")
return APIResponse(
status=404,
success=False,
message=f"Memecoin {token_address} not found in vector database",
)
except Exception as e:
logger.error(
f"❌ Error deleting memecoin from vector database {token_address}: {e}"
)
raise HTTPException(
status_code=500,
detail=f"Failed to delete memecoin from vector database: {e}",
)
@router.post("/degrade/{token_address}", response_model=APIResponse)
async def degrade_database_memecoin(
token_address: str,
orchestrator: MemeStorageOrchestrator = Depends(get_meme_storage_orchestrator),
) -> APIResponse:
"""
Degrade a memecoin from vector database back to approved collection
This operation:
1. Deletes memecoin from all 5 ChromaDB collections
2. Deletes associated image and caption files from rag_db
3. Moves metadata JSON to approved collection (strips caption field)
4. Moves image JPG to approved collection
5. Invalidates stats cache
Use case: Fix incorrect tags/captions and reprocess through workflow
Args:
token_address: Token address of memecoin to degrade
orchestrator: MemeStorageOrchestrator for database and file operations
Returns:
APIResponse with operation results
"""
try:
logger.info(
f"⬇️ Degrading memecoin from vector database to approved: {token_address}"
)
success, message = await orchestrator.degrade_database_memecoin(token_address)
if success:
logger.info(f"✅ Successfully degraded memecoin: {token_address}")
return APIResponse(status=200, success=True, message=message)
else:
logger.warning(f"⚠️ Failed to degrade memecoin: {token_address} - {message}")
return APIResponse(
status=400, success=False, message=message, error=message
)
except Exception as e:
logger.error(f"❌ Error degrading memecoin {token_address}: {e}")
sanitized_error = sanitize_error_message(e)
raise HTTPException(
status_code=500, detail=f"Failed to degrade memecoin: {sanitized_error}"
)
@router.get("/pending/{token_address}", response_model=MemecoinDetailResponse)
async def get_pending_memecoin(
token_address: str,
orchestrator: MemeStorageOrchestrator = Depends(get_meme_storage_orchestrator),
) -> MemecoinDetailResponse:
"""
Get a specific pending memecoin by token address
Args:
token_address: Token address to search for
Returns:
MemecoinDetailResponse with memecoin data and Base64 image
"""
try:
logger.info(f"📄 Getting pending memecoin: {token_address}")
result = await orchestrator.get_pending_memecoin(token_address)
if result["found"]:
logger.info(f"✅ Found pending memecoin: {token_address}")
return MemecoinDetailResponse(
status=200,
success=True,
message="Pending memecoin retrieved successfully",
memecoin=result["memecoin"],
)
else:
logger.warning(f"❌ Pending memecoin not found: {token_address}")
raise HTTPException(
status_code=404, detail=f"Pending memecoin '{token_address}' not found"
)
except HTTPException:
raise
except Exception as e:
logger.error(f"❌ Error getting pending memecoin {token_address}: {e}")
raise HTTPException(
status_code=500, detail=f"Failed to retrieve pending memecoin: {e}"
)
@router.get("/approved/{token_address}", response_model=MemecoinDetailResponse)
async def get_approved_memecoin(
token_address: str,
orchestrator: MemeStorageOrchestrator = Depends(get_meme_storage_orchestrator),
) -> MemecoinDetailResponse:
"""
Get a specific approved memecoin by token address
Args:
token_address: Token address to search for
Returns:
MemecoinDetailResponse with memecoin data and Base64 image
"""
try:
logger.info(f"📄 Getting approved memecoin: {token_address}")
result = await orchestrator.get_approved_memecoin(token_address)
if result["found"]:
logger.info(f"✅ Found approved memecoin: {token_address}")
return MemecoinDetailResponse(
status=200,
success=True,
message="Approved memecoin retrieved successfully",
memecoin=result["memecoin"],
)
else:
logger.warning(f"❌ Approved memecoin not found: {token_address}")
raise HTTPException(
status_code=404, detail=f"Approved memecoin '{token_address}' not found"
)
except HTTPException:
raise
except Exception as e:
logger.error(f"❌ Error getting approved memecoin {token_address}: {e}")
raise HTTPException(
status_code=500, detail=f"Failed to retrieve approved memecoin: {e}"
)
@router.get("/image/{token_address}")
async def get_memecoin_image(
token_address: str,
source: str = Query(
"approved", description="Source directory: 'pending', 'approved', or 'database'"
),
orchestrator: MemeStorageOrchestrator = Depends(get_meme_storage_orchestrator),
) -> Response:
"""
Get memecoin image as direct binary response
Args:
token_address: Token address to search for
source: Source directory ('pending', 'approved', or 'database')
'database' loads from vector DB images (res/memecoins/rag_db/images/)
Returns:
Image binary data with proper Content-Type
"""
try:
logger.info(f"🖼️ Image API request: token={token_address}, source={source}")
result = await orchestrator.get_memecoin_image(token_address, source=source)
if result["found"]:
logger.info(f"✅ Image found: {token_address} from {source} ({len(result['image_data'])} bytes)")
# Return binary image with proper content type
return Response(
content=result["image_data"],
media_type=result["content_type"],
headers={
"Cache-Control": "no-cache, no-store, must-revalidate", # Prevent caching
"Pragma": "no-cache",
"Expires": "0",
"Content-Disposition": f'inline; filename="{token_address}.jpg"',
},
)
else:
logger.warning(f"❌ Image not found: {token_address} in {source}")
raise HTTPException(
status_code=404,
detail=f"Image for memecoin '{token_address}' not found in {source}",
)
except HTTPException:
raise
except Exception as e:
import traceback
logger.error(f"❌ Error loading image {token_address} from {source}: {e}")
logger.error(f"Stack trace: {traceback.format_exc()}")
raise HTTPException(
status_code=500, detail=f"Failed to retrieve memecoin image: {e}"
)
@router.post("/refresh-cache", response_model=APIResponse)
async def refresh_memecoin_cache(
orchestrator: MemeStorageOrchestrator = Depends(get_meme_storage_orchestrator),
) -> APIResponse:
"""
Force refresh of all cached memecoin data
Returns:
APIResponse confirming cache refresh
"""
try:
logger.info("🔄 Refreshing memecoin cache...")
await orchestrator.refresh_cache()
logger.info("✅ Memecoin cache refreshed successfully")
return APIResponse(
status=200, success=True, message="Memecoin cache refreshed successfully"
)
except Exception as e:
logger.error(f"❌ Error refreshing memecoin cache: {e}")
raise HTTPException(
status_code=500, detail=f"Failed to refresh memecoin cache: {e}"
)
# Generated Memecoins API Endpoints
@router.get("/generated", response_model=GeneratedMemecoinListResponse)
async def list_generated_memecoins(
page: int = Query(1, ge=1, description="Page number (1-based)"),
limit: int = Query(20, ge=1, le=100, description="Items per page"),
orchestrator: MemeStorageOrchestrator = Depends(get_meme_storage_orchestrator),
) -> GeneratedMemecoinListResponse:
"""
List generated memecoins with pagination
Args:
page: Page number (1-based)
limit: Items per page (max 100)
orchestrator: MemeStorageOrchestrator for storage operations
Returns:
Paginated list of generated memecoins
"""
try:
logger.info(f"📋 Listing generated memecoins: page={page}, limit={limit}")
# Get paginated list from orchestrator
result = await orchestrator.list_generated_memecoins(page=page, limit=limit)
# Convert to response format
memecoins_data = []
for memecoin in result.memecoins:
# Only include fields needed by frontend
# Exclude: token_address (not launched), image_caption (unused),
# tags/tags_categories (removed from generated memes), generation_info (internal metadata)
memecoin_data = {
"uuid": memecoin.uuid,
"token_name": memecoin.name,
"ticker": memecoin.ticker,
"description": memecoin.description,
"image_data": memecoin.image_data,
"creation_date": memecoin.created_at, # ISO timestamp for display
"has_image": bool(memecoin.image_data),
}
memecoins_data.append(memecoin_data)
logger.info(f"✅ Listed {len(memecoins_data)} generated memecoins")
return GeneratedMemecoinListResponse(
status=200,
success=True,
message="Generated memecoins retrieved successfully",
memecoins=memecoins_data,
total=result.total,
page=result.page,
limit=result.limit,
total_pages=result.total_pages,
has_next=result.has_next,
has_prev=result.has_prev,
)
except HTTPException:
raise
except Exception as e:
logger.error(f"❌ Error listing generated memecoins: {e}")
raise HTTPException(
status_code=500, detail=f"Failed to list generated memecoins: {e}"
)
@router.get("/generated/{uuid}", response_model=GeneratedMemecoinDetailResponse)
async def get_generated_memecoin(
uuid: str,
orchestrator: MemeStorageOrchestrator = Depends(get_meme_storage_orchestrator),
) -> GeneratedMemecoinDetailResponse:
"""
Get a specific generated memecoin by UUID
Args:
uuid: UUID of the generated memecoin
orchestrator: MemeStorageOrchestrator for storage operations
Returns:
Generated memecoin data
"""
try:
logger.info(f"🔍 Getting generated memecoin: {uuid[:8]}")
# Load memecoin from orchestrator
memecoin = await orchestrator.get_generated_memecoin(uuid)
if not memecoin:
logger.warning(f"❌ Generated memecoin not found: {uuid[:8]}")
raise HTTPException(
status_code=404,
detail=f"Generated memecoin '{uuid}' not found",
)
# Convert to response format
memecoin_data = {
"uuid": memecoin.uuid,
"token_name": memecoin.name,
"ticker": memecoin.ticker,
"token_address": "",
"description": memecoin.description,
"image_data": memecoin.image_data,
"creation_date": memecoin.created_at,
"has_image": bool(memecoin.image_data),
"image_caption": "",
"generation_info": memecoin.generation_info,
}
logger.info(f"✅ Found generated memecoin: {uuid[:8]}")
return GeneratedMemecoinDetailResponse(
status=200,
success=True,
message="Generated memecoin retrieved successfully",
memecoin=memecoin_data,
)
except HTTPException:
raise
except Exception as e:
logger.error(f"❌ Error getting generated memecoin {uuid[:8]}: {e}")
raise HTTPException(
status_code=500, detail=f"Failed to retrieve generated memecoin: {e}"
)
@router.put("/generated/{uuid}", response_model=MemecoinUpdateResponse)
async def update_generated_memecoin(
uuid: str,
update_data: MemecoinUpdateRequest,
orchestrator: MemeStorageOrchestrator = Depends(get_meme_storage_orchestrator),
) -> MemecoinUpdateResponse:
"""
Update a generated memecoin's metadata
Args:
uuid: UUID of the generated memecoin
update_data: Updated memecoin fields (name, symbol, description, tags)
orchestrator: MemeStorageOrchestrator for storage operations
Returns:
Updated memecoin data
"""
try:
logger.info(f"🔍 Updating generated memecoin: {uuid[:8]}")
# Load existing memecoin from orchestrator
memecoin = await orchestrator.get_generated_memecoin(uuid)
if not memecoin:
logger.warning(f"❌ Generated memecoin not found: {uuid[:8]}")
raise HTTPException(
status_code=404,
detail=f"Generated memecoin '{uuid}' not found",
)
# Apply updates (only update fields that were provided)
if update_data.name is not None:
memecoin.name = update_data.name
logger.info(f" → Updated name: {update_data.name}")
if update_data.ticker is not None:
memecoin.ticker = update_data.ticker
logger.info(f" → Updated ticker: {update_data.ticker}")
if update_data.description is not None:
memecoin.description = update_data.description
logger.info(
f" → Updated description (length: {len(update_data.description)})"
)
# Save updated memecoin via orchestrator
success = await orchestrator.save_generated_memecoin(memecoin)
if not success:
logger.error(f"❌ Failed to save updated memecoin {uuid[:8]}")
raise HTTPException(
status_code=500,
detail="Failed to save updated memecoin",
)
# Convert to response format
memecoin_data = {
"uuid": memecoin.uuid,
"name": memecoin.name,
"ticker": memecoin.ticker,
"description": memecoin.description,
"tags": memecoin.tags,
"image_data": memecoin.image_data,
"created_at": memecoin.created_at,
"generation_info": memecoin.generation_info,
}
logger.info(f"✅ Successfully updated memecoin: {uuid[:8]}")
return MemecoinUpdateResponse(
status=200,
success=True,
message="Memecoin updated successfully",
memecoin=memecoin_data,
)
except HTTPException:
raise
except Exception as e:
logger.error(f"❌ Error updating generated memecoin {uuid[:8]}: {e}")
raise HTTPException(
status_code=500, detail=f"Failed to update generated memecoin: {e}"
)
@router.delete("/generated/{uuid}", response_model=APIResponse)
async def delete_generated_memecoin(
uuid: str,
orchestrator: MemeStorageOrchestrator = Depends(get_meme_storage_orchestrator),
) -> APIResponse:
"""
Delete a generated memecoin
Args:
uuid: UUID of the memecoin to delete
orchestrator: MemeStorageOrchestrator for storage operations
Returns:
Success confirmation
"""
try:
logger.info(f"🗑️ Deleting generated memecoin: {uuid[:8]}")
# Delete memecoin via orchestrator
success = await orchestrator.delete_generated_memecoin(uuid)
if not success:
logger.warning(f"❌ Generated memecoin not found for deletion: {uuid[:8]}")
raise HTTPException(
status_code=404,
detail=f"Generated memecoin '{uuid}' not found",
)
logger.info(f"✅ Deleted generated memecoin: {uuid[:8]}")
return APIResponse(
status=200,
success=True,
message=f"Generated memecoin '{uuid}' deleted successfully",
)
except HTTPException:
raise
except Exception as e:
logger.error(f"❌ Error deleting generated memecoin {uuid[:8]}: {e}")
raise HTTPException(
status_code=500, detail=f"Failed to delete generated memecoin: {e}"
)
# ================================================================================
# GENERATED MEMECOIN EDITING ENDPOINTS
# ================================================================================
@router.post(
"/generated/{uuid}/ai-edit",
response_model=GeneratedEditProposalResponse,
summary="Generate edit proposal for generated memecoin",
description="""Generate an AI-powered edit proposal based on user feedback.
**Flow:**
1. User provides feedback about what to change
2. AI analyzes feedback and determines affected parts
3. Retrieves context from vector DB if needed (for logos, entities)
4. Regenerates affected metadata and/or image
5. Returns proposal with UUID for review
6. Proposal cached for 5 minutes
**Intelligent Features:**
- Automatic decision of what needs regeneration
- Context retrieval for accurate entity representation
- Conditional image regeneration with visual references
- Targeted metadata updates (only affected fields)
**Feedback Examples:**
- "Make the dog blue instead of brown"
- "Fix the BNB logo - it should be the official one"
- "Change name to something with wordplay"
- "Wrong art style - should be pixel art"
""",