Jeremy Live commited on
Commit
cf83b10
Β·
1 Parent(s): b19a358

comento logica de imagen

Browse files
Files changed (3) hide show
  1. __pycache__/modal_backend.cpython-312.pyc +0 -0
  2. app.py +32 -32
  3. modal_backend.py +129 -129
__pycache__/modal_backend.cpython-312.pyc CHANGED
Binary files a/__pycache__/modal_backend.cpython-312.pyc and b/__pycache__/modal_backend.cpython-312.pyc differ
 
app.py CHANGED
@@ -58,7 +58,7 @@ try:
58
  # Initialize functions dictionary
59
  functions = {
60
  'generate_content': None,
61
- 'generate_image': None,
62
  'generate_content_with_llm': None
63
  }
64
  # Ensure app_name is defined
@@ -282,7 +282,7 @@ def generate_all_content(business_type, target_audience, content_goal, brand_nam
282
  brand_name=brand_name,
283
  key_message=key_message,
284
  model_name=selected_model,
285
- generate_images=generate_image_flag
286
  )
287
 
288
  # Check if we got a valid response
@@ -291,12 +291,12 @@ def generate_all_content(business_type, target_audience, content_goal, brand_nam
291
  status_msg = f"βœ… {result.get('message', 'Content generated')} in {time.time() - start_time:.2f}s"
292
 
293
  # Check for generated images
294
- if generate_image_flag and 'images' in result and result['images']:
295
- # Get the first platform with an image
296
- for platform in ['linkedin', 'instagram', 'tiktok', 'twitter', 'facebook']:
297
- if platform in result['images'] and result['images'][platform]:
298
- image_output = result['images'][platform]
299
- break
300
  else:
301
  raise ValueError("Unexpected response format from Modal AI")
302
 
@@ -455,12 +455,12 @@ with gr.Blocks(theme=gr.themes.Soft(), title="πŸš€ Content Creator Pro") as demo
455
  )
456
 
457
  # Image generation toggle (only visible when AI generation is selected)
458
- with gr.Group(visible=MODAL_AVAILABLE) as image_group:
459
- generate_image_toggle = gr.Checkbox(
460
- label="πŸ–ΌοΈ Generate AI Image",
461
- value=False,
462
- info="Check to generate an AI image based on your content"
463
- )
464
 
465
  run_button = gr.Button("πŸš€ Generate Content", variant="primary", size="lg")
466
 
@@ -475,15 +475,15 @@ with gr.Blocks(theme=gr.themes.Soft(), title="πŸš€ Content Creator Pro") as demo
475
  twitter_output = gr.Textbox(label="🐦 Twitter/𝕏 Post", lines=4)
476
  facebook_output = gr.Textbox(label="πŸ“˜ Facebook Post", lines=6)
477
 
478
- status = gr.Markdown("Ready to generate content!")
479
 
480
  # Image output component
481
- with gr.Row():
482
- generated_image = gr.Image(
483
- label="πŸ–ΌοΈ Generated Image",
484
- visible=False,
485
- height=512
486
- )
487
 
488
  # Update component visibility based on modal toggle
489
  def update_modal_components_visibility(use_modal):
@@ -511,7 +511,7 @@ with gr.Blocks(theme=gr.themes.Soft(), title="πŸš€ Content Creator Pro") as demo
511
  key_message,
512
  modal_toggle,
513
  model_selector, # Add model selector to inputs
514
- generate_image_toggle
515
  ],
516
  outputs=[
517
  linkedin_output,
@@ -519,20 +519,20 @@ with gr.Blocks(theme=gr.themes.Soft(), title="πŸš€ Content Creator Pro") as demo
519
  tiktok_output,
520
  twitter_output,
521
  facebook_output,
522
- status,
523
- generated_image
524
  ]
525
  )
526
 
527
  # Show/hide image based on whether an image was generated
528
- def update_image_visibility(image_data):
529
- return gr.Image(visible=image_data is not None), image_data or None
530
-
531
- generated_image.change(
532
- fn=lambda x: (gr.Image(visible=x is not None), x or None),
533
- inputs=[generated_image],
534
- outputs=[generated_image, generated_image]
535
- )
536
 
537
  # Add examples
538
  gr.Examples(
 
58
  # Initialize functions dictionary
59
  functions = {
60
  'generate_content': None,
61
+ # 'generate_image': None,
62
  'generate_content_with_llm': None
63
  }
64
  # Ensure app_name is defined
 
282
  brand_name=brand_name,
283
  key_message=key_message,
284
  model_name=selected_model,
285
+ # generate_images=generate_image_flag
286
  )
287
 
288
  # Check if we got a valid response
 
291
  status_msg = f"βœ… {result.get('message', 'Content generated')} in {time.time() - start_time:.2f}s"
292
 
293
  # Check for generated images
294
+ # if generate_image_flag and 'images' in result and result['images']:
295
+ # # Get the first platform with an image
296
+ # for platform in ['linkedin', 'instagram', 'tiktok', 'twitter', 'facebook']:
297
+ # if platform in result['images'] and result['images'][platform]:
298
+ # image_output = result['images'][platform]
299
+ # break
300
  else:
301
  raise ValueError("Unexpected response format from Modal AI")
302
 
 
455
  )
456
 
457
  # Image generation toggle (only visible when AI generation is selected)
458
+ # with gr.Group(visible=MODAL_AVAILABLE) as image_group:
459
+ # generate_image_toggle = gr.Checkbox(
460
+ # label="πŸ–ΌοΈ Generate AI Image",
461
+ # value=False,
462
+ # info="Check to generate an AI image based on your content"
463
+ # )
464
 
465
  run_button = gr.Button("πŸš€ Generate Content", variant="primary", size="lg")
466
 
 
475
  twitter_output = gr.Textbox(label="🐦 Twitter/𝕏 Post", lines=4)
476
  facebook_output = gr.Textbox(label="πŸ“˜ Facebook Post", lines=6)
477
 
478
+ # status = gr.Markdown("Ready to generate content!")
479
 
480
  # Image output component
481
+ # with gr.Row():
482
+ # generated_image = gr.Image(
483
+ # label="πŸ–ΌοΈ Generated Image",
484
+ # visible=False,
485
+ # height=512
486
+ # )
487
 
488
  # Update component visibility based on modal toggle
489
  def update_modal_components_visibility(use_modal):
 
511
  key_message,
512
  modal_toggle,
513
  model_selector, # Add model selector to inputs
514
+ # generate_image_toggle
515
  ],
516
  outputs=[
517
  linkedin_output,
 
519
  tiktok_output,
520
  twitter_output,
521
  facebook_output,
522
+ # status,
523
+ # generated_image
524
  ]
525
  )
526
 
527
  # Show/hide image based on whether an image was generated
528
+ # def update_image_visibility(image_data):
529
+ # return gr.Image(visible=image_data is not None), image_data or None
530
+
531
+ # generated_image.change(
532
+ # fn=lambda x: (gr.Image(visible=x is not None), x or None),
533
+ # inputs=[generated_image],
534
+ # outputs=[generated_image, generated_image]
535
+ # )
536
 
537
  # Add examples
538
  gr.Examples(
modal_backend.py CHANGED
@@ -726,104 +726,104 @@ Important:
726
 
727
 
728
  # Image generation function
729
- @app.function(
730
- image=image,
731
- gpu="A10G",
732
- memory=32768,
733
- secrets=[modal.Secret.from_name("huggingface-secret")],
734
- timeout=1200, # 20 minutes
735
- volumes={CACHE_DIR: volume},
736
- )
737
- def generate_image(
738
- prompt: str,
739
- negative_prompt: str = "",
740
- num_images: int = 1,
741
- width: int = 1024,
742
- height: int = 1024
743
- ) -> list:
744
- """
745
- Generate high-quality images using Stable Diffusion XL 1.0
746
 
747
- Args:
748
- prompt: Text description of the image to generate
749
- negative_prompt: Text description of what not to include in the image
750
- num_images: Number of images to generate (1-4)
751
- width: Width of the generated image (multiple of 8, max 1024)
752
- height: Height of the generated image (multiple of 8, max 1024)
753
-
754
- Returns:
755
- List of base64-encoded image strings
756
- """
757
- from diffusers import StableDiffusionXLPipeline
758
- import torch
759
- from io import BytesIO
760
- import base64
761
 
762
- try:
763
- print(f"πŸ–ΌοΈ Generating {num_images} image(s) with prompt: {prompt[:100]}...")
764
-
765
- # Load the model with caching
766
- model_id = "stabilityai/stable-diffusion-xl-base-1.0"
767
-
768
- print("Loading Stable Diffusion XL pipeline...")
769
- pipe = StableDiffusionXLPipeline.from_pretrained(
770
- model_id,
771
- torch_dtype=torch.float16,
772
- use_safetensors=True,
773
- variant="fp16",
774
- cache_dir=CACHE_DIR,
775
- local_files_only=False # Allow downloading if not in cache
776
- )
777
-
778
- # Move to GPU if available
779
- if torch.cuda.is_available():
780
- pipe = pipe.to("cuda")
781
- print("βœ… Moved model to GPU")
782
-
783
- # Generate images
784
- print(f"⚑ Generating {num_images} image(s) with size {width}x{height}...")
785
- images = pipe(
786
- prompt=prompt,
787
- negative_prompt=negative_prompt,
788
- num_images_per_prompt=num_images,
789
- num_inference_steps=30,
790
- guidance_scale=7.5,
791
- width=width,
792
- height=height,
793
- ).images
794
-
795
- print(f"βœ… Generated {len(images)} images successfully")
796
-
797
- # Convert PIL images to base64
798
- result = []
799
- for i, img in enumerate(images):
800
- buffered = BytesIO()
801
- img.save(buffered, format="PNG")
802
- img_str = base64.b64encode(buffered.getvalue()).decode()
803
- result.append(f"data:image/png;base64,{img_str}")
804
- print(f" - Image {i+1}: {len(img_str) // 1000} KB")
805
-
806
- return result
807
-
808
- except Exception as e:
809
- error_msg = f"Error generating content: {str(e)}"
810
- print(f"\n❌ {error_msg}")
811
- import traceback
812
- traceback.print_exc()
813
-
814
- # Return a more helpful error message
815
- error_details = {
816
- "error": "Failed to generate content",
817
- "message": str(e),
818
- "type": type(e).__name__,
819
- "platforms": PLATFORMS
820
- }
821
-
822
- # Log the full error for debugging
823
- print(f"\n⚠️ Error details: {error_details}")
824
-
825
- # Return error for each platform
826
- return [f"Error: {error_msg}"]
827
 
828
  # Combined function to generate both text and images
829
  @app.function(
@@ -840,7 +840,7 @@ def generate_content(
840
  content_goal: str,
841
  brand_name: str,
842
  key_message: str,
843
- generate_images: bool = False,
844
  model_name: str = DEFAULT_MODEL,
845
  ):
846
  """
@@ -878,39 +878,39 @@ def generate_content(
878
  print(f" βœ… {platform} content generated successfully!")
879
 
880
  # Generate image if requested
881
- if generate_images and platform_content and not platform_content.startswith("Error"):
882
- try:
883
- print(f" πŸ–ΌοΈ Generating {platform} image...")
884
- image_prompt = (
885
- f"Create an engaging social media image for {platform} about: {key_message}. "
886
- f"Business type: {business_type}. Target audience: {target_audience}. "
887
- f"Style: professional, high-quality, on-brand for {brand_name}. "
888
- "8k, detailed, cinematic lighting"
889
- )
890
 
891
- image_url = generate_image.remote(
892
- prompt=image_prompt,
893
- negative_prompt=(
894
- "low quality, blurry, text, watermark, logo, "
895
- "distorted, deformed, disfigured, bad anatomy, "
896
- "extra limbs, extra fingers, cropped, jpeg artifacts"
897
- ),
898
- num_images=1,
899
- width=1024,
900
- height=1024
901
- )
902
 
903
- if image_url and not any(url.startswith("Error") for url in image_url):
904
- image_results[platform] = image_url[0]
905
- print(f" βœ… {platform} image generated successfully!")
906
- else:
907
- image_results[platform] = f"Failed to generate {platform} image"
908
- print(f" ❌ Failed to generate {platform} image")
909
 
910
- except Exception as img_e:
911
- error_msg = f"Error generating {platform} image: {str(img_e)}"
912
- print(f" ❌ {error_msg}")
913
- image_results[platform] = error_msg
914
 
915
  except Exception as e:
916
  error_msg = f"Error generating {platform} content: {str(e)[:200]}"
@@ -920,7 +920,7 @@ def generate_content(
920
  return {
921
  "status": "success",
922
  "content": content_results,
923
- "images": image_results if generate_images else {},
924
  "message": "Content generated successfully"
925
  }
926
 
@@ -974,7 +974,7 @@ if __name__ == "__main__":
974
  content_goal="Generate leads with our new social media strategy",
975
  brand_name="GrowthHack Marketing",
976
  key_message="Our proven 3-step framework can help you 3x your online visibility in just 30 days.",
977
- generate_images=True,
978
  image_width=1024,
979
  image_height=1024
980
  )
 
726
 
727
 
728
  # Image generation function
729
+ # @app.function(
730
+ # image=image,
731
+ # gpu="A10G",
732
+ # memory=32768,
733
+ # secrets=[modal.Secret.from_name("huggingface-secret")],
734
+ # timeout=1200, # 20 minutes
735
+ # volumes={CACHE_DIR: volume},
736
+ # )
737
+ # def generate_image(
738
+ # prompt: str,
739
+ # negative_prompt: str = "",
740
+ # num_images: int = 1,
741
+ # width: int = 1024,
742
+ # height: int = 1024
743
+ # ) -> list:
744
+ # """
745
+ # Generate high-quality images using Stable Diffusion XL 1.0
746
 
747
+ # Args:
748
+ # prompt: Text description of the image to generate
749
+ # negative_prompt: Text description of what not to include in the image
750
+ # num_images: Number of images to generate (1-4)
751
+ # width: Width of the generated image (multiple of 8, max 1024)
752
+ # height: Height of the generated image (multiple of 8, max 1024)
753
+
754
+ # Returns:
755
+ # List of base64-encoded image strings
756
+ # """
757
+ # from diffusers import StableDiffusionXLPipeline
758
+ # import torch
759
+ # from io import BytesIO
760
+ # import base64
761
 
762
+ # try:
763
+ # print(f"πŸ–ΌοΈ Generating {num_images} image(s) with prompt: {prompt[:100]}...")
764
+
765
+ # # Load the model with caching
766
+ # model_id = "stabilityai/stable-diffusion-xl-base-1.0"
767
+
768
+ # print("Loading Stable Diffusion XL pipeline...")
769
+ # pipe = StableDiffusionXLPipeline.from_pretrained(
770
+ # model_id,
771
+ # torch_dtype=torch.float16,
772
+ # use_safetensors=True,
773
+ # variant="fp16",
774
+ # cache_dir=CACHE_DIR,
775
+ # local_files_only=False # Allow downloading if not in cache
776
+ # )
777
+
778
+ # # Move to GPU if available
779
+ # if torch.cuda.is_available():
780
+ # pipe = pipe.to("cuda")
781
+ # print("βœ… Moved model to GPU")
782
+
783
+ # # Generate images
784
+ # print(f"⚑ Generating {num_images} image(s) with size {width}x{height}...")
785
+ # images = pipe(
786
+ # prompt=prompt,
787
+ # negative_prompt=negative_prompt,
788
+ # num_images_per_prompt=num_images,
789
+ # num_inference_steps=30,
790
+ # guidance_scale=7.5,
791
+ # width=width,
792
+ # height=height,
793
+ # ).images
794
+
795
+ # print(f"βœ… Generated {len(images)} images successfully")
796
+
797
+ # # Convert PIL images to base64
798
+ # result = []
799
+ # for i, img in enumerate(images):
800
+ # buffered = BytesIO()
801
+ # img.save(buffered, format="PNG")
802
+ # img_str = base64.b64encode(buffered.getvalue()).decode()
803
+ # result.append(f"data:image/png;base64,{img_str}")
804
+ # print(f" - Image {i+1}: {len(img_str) // 1000} KB")
805
+
806
+ # return result
807
+
808
+ # except Exception as e:
809
+ # error_msg = f"Error generating content: {str(e)}"
810
+ # print(f"\n❌ {error_msg}")
811
+ # import traceback
812
+ # traceback.print_exc()
813
+
814
+ # # Return a more helpful error message
815
+ # error_details = {
816
+ # "error": "Failed to generate content",
817
+ # "message": str(e),
818
+ # "type": type(e).__name__,
819
+ # "platforms": PLATFORMS
820
+ # }
821
+
822
+ # # Log the full error for debugging
823
+ # print(f"\n⚠️ Error details: {error_details}")
824
+
825
+ # # Return error for each platform
826
+ # return [f"Error: {error_msg}"]
827
 
828
  # Combined function to generate both text and images
829
  @app.function(
 
840
  content_goal: str,
841
  brand_name: str,
842
  key_message: str,
843
+ # generate_images: bool = False,
844
  model_name: str = DEFAULT_MODEL,
845
  ):
846
  """
 
878
  print(f" βœ… {platform} content generated successfully!")
879
 
880
  # Generate image if requested
881
+ # if generate_images and platform_content and not platform_content.startswith("Error"):
882
+ # try:
883
+ # print(f" πŸ–ΌοΈ Generating {platform} image...")
884
+ # image_prompt = (
885
+ # f"Create an engaging social media image for {platform} about: {key_message}. "
886
+ # f"Business type: {business_type}. Target audience: {target_audience}. "
887
+ # f"Style: professional, high-quality, on-brand for {brand_name}. "
888
+ # "8k, detailed, cinematic lighting"
889
+ # )
890
 
891
+ # image_url = generate_image.remote(
892
+ # prompt=image_prompt,
893
+ # negative_prompt=(
894
+ # "low quality, blurry, text, watermark, logo, "
895
+ # "distorted, deformed, disfigured, bad anatomy, "
896
+ # "extra limbs, extra fingers, cropped, jpeg artifacts"
897
+ # ),
898
+ # num_images=1,
899
+ # width=1024,
900
+ # height=1024
901
+ # )
902
 
903
+ # if image_url and not any(url.startswith("Error") for url in image_url):
904
+ # image_results[platform] = image_url[0]
905
+ # print(f" βœ… {platform} image generated successfully!")
906
+ # else:
907
+ # image_results[platform] = f"Failed to generate {platform} image"
908
+ # print(f" ❌ Failed to generate {platform} image")
909
 
910
+ # except Exception as img_e:
911
+ # error_msg = f"Error generating {platform} image: {str(img_e)}"
912
+ # print(f" ❌ {error_msg}")
913
+ # image_results[platform] = error_msg
914
 
915
  except Exception as e:
916
  error_msg = f"Error generating {platform} content: {str(e)[:200]}"
 
920
  return {
921
  "status": "success",
922
  "content": content_results,
923
+ # "images": image_results if generate_images else {},
924
  "message": "Content generated successfully"
925
  }
926
 
 
974
  content_goal="Generate leads with our new social media strategy",
975
  brand_name="GrowthHack Marketing",
976
  key_message="Our proven 3-step framework can help you 3x your online visibility in just 30 days.",
977
+ # generate_images=True,
978
  image_width=1024,
979
  image_height=1024
980
  )