Fraser commited on
Commit
47285c1
·
1 Parent(s): 2ac757d
Files changed (2) hide show
  1. app.py +26 -75
  2. requirements.txt +1 -2
app.py CHANGED
@@ -8,8 +8,6 @@ from typing import List, Optional
8
  from huggingface_hub import HfApi, hf_hub_download, list_repo_files
9
  from pathlib import Path
10
  import tempfile
11
- import base64
12
- from rembg import remove
13
  from auth import verify_hf_token
14
 
15
  # HuggingFace configuration
@@ -489,7 +487,14 @@ CRITICAL RULES:
489
  'legendary': 'highly detailed and majestic design with dramatic lighting and aura effects'
490
  }
491
 
492
- 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."
 
 
 
 
 
 
 
493
 
494
  print(f"Generating image with prompt: {full_prompt[:100]}...")
495
  result = client.predict(
@@ -528,44 +533,12 @@ CRITICAL RULES:
528
  raise Exception(f"Image generation failed: {str(e)}")
529
 
530
  @staticmethod
531
- def remove_background(image_path: str) -> str:
532
- """
533
- Remove background from image using rembg
534
- Returns base64 encoded PNG with transparency
535
-
536
- Args:
537
- image_path: Path to the input image file
538
-
539
- Returns:
540
- Base64 encoded string of the image with transparent background
541
- """
542
- try:
543
- print(f"Removing background from image...")
544
-
545
- # Open the image
546
- with open(image_path, 'rb') as f:
547
- input_image = f.read()
548
-
549
- # Remove background using rembg
550
- output_image = remove(input_image)
551
-
552
- # Convert to base64
553
- base64_image = base64.b64encode(output_image).decode('utf-8')
554
-
555
- print(f"Background removal completed")
556
- return f"data:image/png;base64,{base64_image}"
557
-
558
- except Exception as e:
559
- print(f"Failed to remove background: {e}")
560
- raise Exception(f"Background removal failed: {str(e)}")
561
-
562
- @staticmethod
563
- def upload_image_to_dataset(image_data: str, file_name: str) -> str:
564
  """
565
  Upload image to HuggingFace dataset
566
 
567
  Args:
568
- image_data: Base64 encoded image data (with or without data URI prefix)
569
  file_name: Name for the file (e.g., "pillow_canonical.png")
570
 
571
  Returns:
@@ -574,17 +547,17 @@ CRITICAL RULES:
574
  try:
575
  print(f"Uploading image to dataset: {file_name}")
576
 
577
- # Remove data URI prefix if present
578
- if image_data.startswith('data:'):
579
- image_data = image_data.split(',', 1)[1]
580
-
581
- # Decode base64 to bytes
582
- image_bytes = base64.b64decode(image_data)
583
-
584
- # Create temporary file
585
- with tempfile.NamedTemporaryFile(mode='wb', suffix='.png', delete=False) as f:
586
- f.write(image_bytes)
587
- temp_path = f.name
588
 
589
  # Upload to HuggingFace dataset
590
  file_path = f"images/{file_name}"
@@ -596,8 +569,9 @@ CRITICAL RULES:
596
  commit_message=f"Add piclet image: {file_name}"
597
  )
598
 
599
- # Clean up temp file
600
- os.unlink(temp_path)
 
601
 
602
  # Return the dataset URL
603
  dataset_url = f"https://huggingface.co/datasets/{DATASET_REPO}/resolve/main/{file_path}"
@@ -924,25 +898,6 @@ def generate_piclet(image, hf_token: str) -> dict:
924
  hf_token
925
  )
926
 
927
- # Step 3.5: Remove background from generated image
928
- print("Step 3.5/5: Processing image (removing background)...")
929
- image_local_path = image_result['imageUrl']
930
-
931
- # Handle both local paths and URLs
932
- if image_local_path.startswith('http'):
933
- # If it's a URL, download it first
934
- import requests
935
- response = requests.get(image_local_path)
936
- with tempfile.NamedTemporaryFile(mode='wb', suffix='.png', delete=False) as f:
937
- f.write(response.content)
938
- image_local_path = f.name
939
-
940
- # Remove background
941
- transparent_image_base64 = PicletGeneratorService.remove_background(image_local_path)
942
-
943
- # Store the base64 data in image_result for later use
944
- image_result['imageData'] = transparent_image_base64
945
-
946
  # Step 4: Check for canonical/variation
947
  print("Step 4/5: Checking for existing canonical...")
948
  existing_data = PicletDiscoveryService.load_piclet_data(object_name)
@@ -994,7 +949,7 @@ def generate_piclet(image, hf_token: str) -> dict:
994
  normalized_name = PicletDiscoveryService.normalize_object_name(object_name)
995
  image_filename = f"{normalized_name}_canonical.png"
996
  dataset_image_url = PicletGeneratorService.upload_image_to_dataset(
997
- image_result['imageData'],
998
  image_filename
999
  )
1000
 
@@ -1014,7 +969,6 @@ def generate_piclet(image, hf_token: str) -> dict:
1014
  "nickname": stats['name'],
1015
  "stats": stats,
1016
  "imageUrl": dataset_image_url,
1017
- "imageData": image_result['imageData'],
1018
  "imageCaption": caption,
1019
  "concept": concept_text,
1020
  "imagePrompt": image_prompt,
@@ -1044,7 +998,7 @@ def generate_piclet(image, hf_token: str) -> dict:
1044
  # Upload image to dataset with variation filename
1045
  image_filename = f"{normalized_name}_{variation_num:03d}.png"
1046
  dataset_image_url = PicletGeneratorService.upload_image_to_dataset(
1047
- image_result['imageData'],
1048
  image_filename
1049
  )
1050
 
@@ -1063,7 +1017,6 @@ def generate_piclet(image, hf_token: str) -> dict:
1063
  "nickname": stats['name'],
1064
  "stats": stats,
1065
  "imageUrl": dataset_image_url,
1066
- "imageData": image_result['imageData'],
1067
  "imageCaption": caption,
1068
  "concept": concept_text,
1069
  "imagePrompt": image_prompt,
@@ -1097,7 +1050,6 @@ def generate_piclet(image, hf_token: str) -> dict:
1097
  "nickname": stats['name'],
1098
  "stats": stats,
1099
  "imageUrl": image_result.get('imageUrl', ''),
1100
- "imageData": image_result.get('imageData', ''),
1101
  "imageCaption": caption,
1102
  "concept": concept_text,
1103
  "imagePrompt": image_prompt,
@@ -1125,7 +1077,6 @@ def generate_piclet(image, hf_token: str) -> dict:
1125
  "nickname": stats['name'],
1126
  "stats": stats,
1127
  "imageUrl": dataset_image_url,
1128
- "imageData": image_result.get('imageData', ''),
1129
  "imageCaption": caption,
1130
  "concept": concept_text,
1131
  "imagePrompt": image_prompt,
 
8
  from huggingface_hub import HfApi, hf_hub_download, list_repo_files
9
  from pathlib import Path
10
  import tempfile
 
 
11
  from auth import verify_hf_token
12
 
13
  # HuggingFace configuration
 
487
  'legendary': 'highly detailed and majestic design with dramatic lighting and aura effects'
488
  }
489
 
490
+ background_styles = {
491
+ 'low': 'simple natural environment',
492
+ 'medium': 'detailed thematic natural environment',
493
+ 'high': 'atmospheric thematic environment with special lighting effects',
494
+ 'legendary': 'epic thematic environment with dramatic atmospheric lighting and mystical aura'
495
+ }
496
+
497
+ full_prompt = f"{image_prompt}\nNow generate a Pokémon Anime image of the monster in an idle pose with a {background_styles.get(tier, background_styles['medium'])} background that complements the creature's type and characteristics. 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 and centered in the frame."
498
 
499
  print(f"Generating image with prompt: {full_prompt[:100]}...")
500
  result = client.predict(
 
533
  raise Exception(f"Image generation failed: {str(e)}")
534
 
535
  @staticmethod
536
+ def upload_image_to_dataset(image_path: str, file_name: str) -> str:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
537
  """
538
  Upload image to HuggingFace dataset
539
 
540
  Args:
541
+ image_path: Local path to the image file (or URL to download from)
542
  file_name: Name for the file (e.g., "pillow_canonical.png")
543
 
544
  Returns:
 
547
  try:
548
  print(f"Uploading image to dataset: {file_name}")
549
 
550
+ # Handle both local paths and URLs
551
+ if image_path.startswith('http'):
552
+ # Download from URL first
553
+ import requests
554
+ response = requests.get(image_path)
555
+ with tempfile.NamedTemporaryFile(mode='wb', suffix='.png', delete=False) as f:
556
+ f.write(response.content)
557
+ temp_path = f.name
558
+ else:
559
+ # Use local path directly
560
+ temp_path = image_path
561
 
562
  # Upload to HuggingFace dataset
563
  file_path = f"images/{file_name}"
 
569
  commit_message=f"Add piclet image: {file_name}"
570
  )
571
 
572
+ # Clean up temp file if we downloaded it
573
+ if image_path.startswith('http'):
574
+ os.unlink(temp_path)
575
 
576
  # Return the dataset URL
577
  dataset_url = f"https://huggingface.co/datasets/{DATASET_REPO}/resolve/main/{file_path}"
 
898
  hf_token
899
  )
900
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
901
  # Step 4: Check for canonical/variation
902
  print("Step 4/5: Checking for existing canonical...")
903
  existing_data = PicletDiscoveryService.load_piclet_data(object_name)
 
949
  normalized_name = PicletDiscoveryService.normalize_object_name(object_name)
950
  image_filename = f"{normalized_name}_canonical.png"
951
  dataset_image_url = PicletGeneratorService.upload_image_to_dataset(
952
+ image_result['imageUrl'],
953
  image_filename
954
  )
955
 
 
969
  "nickname": stats['name'],
970
  "stats": stats,
971
  "imageUrl": dataset_image_url,
 
972
  "imageCaption": caption,
973
  "concept": concept_text,
974
  "imagePrompt": image_prompt,
 
998
  # Upload image to dataset with variation filename
999
  image_filename = f"{normalized_name}_{variation_num:03d}.png"
1000
  dataset_image_url = PicletGeneratorService.upload_image_to_dataset(
1001
+ image_result['imageUrl'],
1002
  image_filename
1003
  )
1004
 
 
1017
  "nickname": stats['name'],
1018
  "stats": stats,
1019
  "imageUrl": dataset_image_url,
 
1020
  "imageCaption": caption,
1021
  "concept": concept_text,
1022
  "imagePrompt": image_prompt,
 
1050
  "nickname": stats['name'],
1051
  "stats": stats,
1052
  "imageUrl": image_result.get('imageUrl', ''),
 
1053
  "imageCaption": caption,
1054
  "concept": concept_text,
1055
  "imagePrompt": image_prompt,
 
1077
  "nickname": stats['name'],
1078
  "stats": stats,
1079
  "imageUrl": dataset_image_url,
 
1080
  "imageCaption": caption,
1081
  "concept": concept_text,
1082
  "imagePrompt": image_prompt,
requirements.txt CHANGED
@@ -3,5 +3,4 @@ gradio_client==1.13.3
3
  Pillow>=9.0.0
4
  huggingface_hub>=0.20.0
5
  datasets>=2.15.0
6
- requests>=2.31.0
7
- rembg>=2.0.0
 
3
  Pillow>=9.0.0
4
  huggingface_hub>=0.20.0
5
  datasets>=2.15.0
6
+ requests>=2.31.0