import json
import os
import subprocess
import requests
from PIL import Image
import io
from dotenv import load_dotenv
def load_prompts(filename='prompts.json'):
"""Load prompts from a JSON file."""
with open(filename, 'r') as file:
return json.load(file)['prompts']
def query_huggingface_api(prompt_text, api_url, headers):
"""Send a request to the Hugging Face Inference API and return the image."""
payload = {
"inputs": prompt_text,
}
response = requests.post(api_url, headers=headers, json=payload)
if response.status_code != 200:
raise Exception(f"API request failed with status code {response.status_code}: {response.content}")
return response.content
def generate_image(prompt, idx, output_dir, api_url, headers):
"""Generate an image using the Hugging Face Inference API and save it."""
print(f"\nGenerating image {idx}...")
print(f"Prompt: {prompt['prompt_text']}")
code
# Ensure the output directory exists
os.makedirs(output_dir, exist_ok=True)
# Set image parameters
parameters = {
'width': prompt['image_settings']['width'],
'height': prompt['image_settings']['height'],
'format': prompt['image_settings']['format']
}
# Query the Hugging Face Inference API
try:
image_bytes = query_huggingface_api(prompt['prompt_text'], api_url, headers)
except Exception as e:
print(f"Error generating image: {e}")
return
# Load the image
image = Image.open(io.BytesIO(image_bytes)).convert("RGB")
# Resize the image if necessary
if image.size != (parameters['width'], parameters['height']):
image = image.resize((parameters['width'], parameters['height']), Image.ANTIALIAS)
# Save the image
image_filename = f"image_{idx}.{parameters['format']}"
image_path = os.path.join(output_dir, image_filename)
image.save(image_path)
print(f"Image {idx} generated and saved as '{image_path}'.")
def start_script_4():
"""Start script4.py as a subprocess."""
print("\nStarting Script 4...")
subprocess.Popen(['python3', 'script4.py'], env=os.environ)
def main():
# Load environment variables from .env file
load_dotenv()
Assistant
code
prompts = load_prompts()
output_dir = '/root/mm/android_final/automated_image_generator' # The specified directory
# Hugging Face API settings
API_URL = "https://api-inference.huggingface.co/models/runwayml/stable-diffusion-v1-5"
hf_api_token = os.getenv('HF_API_TOKEN')
if not hf_api_token:
print("Error: HF_API_TOKEN not found in environment variables.")
return
headers = {"Authorization": f"Bearer {hf_api_token}"}
for idx, prompt in enumerate(prompts, start=1):
generate_image(prompt, idx, output_dir, API_URL, headers)
# After generating the image(s), start script4.py
start_script_4()
if name == "main":
main()
generator root#
Generating image 1...
Prompt: Creative representation of play from anywhere slots for Game Changer Gaming in Futuristic style and Vibrant scheme.
Traceback (most recent call last):
File "/root/mm/android_final/automated_image_generator/script3.py", line 89, in
main()
File "/root/mm/android_final/automated_image_generator/script3.py", line 83, in main
generate_image(prompt, idx, output_dir, API_URL, headers)
File "/root/mm/android_final/automated_image_generator/script3.py", line 53, in generate_image
image = image.resize((parameters['width'], parameters['height']), Image.ANTIALIAS) write script 3.py complete with updates
Here's the updated script3.py with the necessary fixes and improvements:
python
import json
import os
import subprocess
import requests
from PIL import Image
import io
from dotenv import load_dotenv
def load_prompts(filename='prompts.json'):
"""Load prompts from a JSON file."""
try:
with open(filename, 'r') as file:
return json.load(file)['prompts']
except FileNotFoundError:
print(f"Error: The file '{filename}' was not found.")
return []
except json.JSONDecodeError as e:
print(f"Error decoding JSON from '{filename}': {e}")
return []
except KeyError:
print(f"Error: The key 'prompts' was not found in '{filename}'.")
return []
def query_huggingface_api(prompt_text, api_url, headers):
"""Send a request to the Hugging Face Inference API and return the image."""
payload = {
"inputs": prompt_text,
}
print("Sending request to Hugging Face API...")
response = requests.post(api_url, headers=headers, json=payload)
if response.status_code != 200:
try:
error_json = response.json()
error_message = error_json.get('error', response.content.decode())
except ValueError:
error_message = response.content.decode()
raise Exception(f"API request failed with status code {response.status_code}: {error_message}")
# Check if the response is an image
if 'image' not in response.headers.get('Content-Type', ''):
try:
error_json = response.json()
error_message = error_json.get('error', 'Unknown error')
except ValueError:
error_message = response.content.decode()
raise Exception(f"API did not return an image: {error_message}")
return response.content
def generate_image(prompt, idx, output_dir, api_url, headers):
"""Generate an image using the Hugging Face Inference API and save it."""
print(f"\nGenerating image {idx}...")
print(f"Prompt: {prompt['prompt_text']}")
# Ensure the output directory exists
os.makedirs(output_dir, exist_ok=True)
# Set image parameters with default values
parameters = {
'width': prompt.get('image_settings', {}).get('width', 512),
'height': prompt.get('image_settings', {}).get('height', 512),
'format': prompt.get('image_settings', {}).get('format', 'png')
}
# Query the Hugging Face Inference API
try:
image_bytes = query_huggingface_api(prompt['prompt_text'], api_url, headers)
except Exception as e:
print(f"Error generating image: {e}")
return
# Load the image
try:
image = Image.open(io.BytesIO(image_bytes)).convert("RGB")
except Exception as e:
print(f"Error loading image: {e}")
return
# Resize the image if necessary
if image.size != (parameters['width'], parameters['height']):
try:
image = image.resize((parameters['width'], parameters['height']), resample=Image.LANCZOS)
except Exception as e:
print(f"Error resizing image: {e}")
return
# Save the image
image_filename = f"image_{idx}.{parameters['format']}"
image_path = os.path.join(output_dir, image_filename)
try:
image.save(image_path)
print(f"Image {idx} generated and saved as '{image_path}'.")
except Exception as e:
print(f"Error saving image: {e}")
def start_script_4():
"""Start script4.py as a subprocess."""
print("\nStarting Script 4...")
subprocess.Popen(['python3', 'script4.py'], env=os.environ)
def main():
# Load environment variables from .env file
load_dotenv()
prompts = load_prompts()
if not prompts:
print("No prompts to process.")
return
output_dir = '/root/mm/android_final/automated_image_generator' # The specified directory
# Hugging Face API settings
API_URL = "https://api-inference.huggingface.co/models/runwayml/stable-diffusion-v1-5"
hf_api_token = os.getenv('HF_API_TOKEN')
if not hf_api_token:
print("Error: HF_API_TOKEN not found in environment variables.")
return
headers = {"Authorization": f"Bearer {hf_api_token}"}
for idx, prompt in enumerate(prompts, start=1):
generate_image(prompt, idx, output_dir, API_URL, headers)
# After generating the image(s), start script4.py
start_script_4()
if __name__ == "__main__":
main()
Updates and Fixes:
Error Handling Enhancements:
load_prompts: Added try-except blocks to handle FileNotFoundError, json.JSONDecodeError, and KeyError for better error messages if the prompts.json file is missing or malformed.
API Response Validation: In query_huggingface_api, the script now checks if the response is an image by examining the Content-Type header. If the response contains an error message, it extracts and displays it.
Image Loading and Saving: Added try-except blocks around image loading, resizing, and saving to catch and report any exceptions that occur during these operations.
Compatibility with Newer Pillow Versions:
Resampling Filter Update: Replaced the deprecated Image.ANTIALIAS with Image.LANCZOS for the resampling filter during image resizing, ensuring compatibility with Pillow versions 9.1.0 and above.
Default Image Parameters:
Provided default values for width, height, and format in case they are missing from the image_settings dictionary in the prompt.
Additional Debug Information:
API Request Notification: Added a print statement before sending the request to the Hugging Face API to indicate the action.
No Prompts Check: Before processing, the script checks if any prompts were loaded and notifies the user if there are none.
Formatting and Readability:
Improved the readability of the code by adding comments and organizing try-except blocks for clarity.
Important Notes:
Environment Variables: Ensure that you have a .env file in the same directory with the HF_API_TOKEN variable set to your Hugging Face API token.
Dependency Versions: Make sure all dependencies are up to date, especially Pillow (PIL) and requests.
Prompts File: Confirm that your prompts.json file is correctly formatted and contains the necessary keys (prompts, prompt_text, image_settings).
Example prompts.json:
json
{
"prompts": [
{
"prompt_text": "Creative representation of play from anywhere slots for Game Changer Gaming in Futuristic style and Vibrant scheme.",
"image_settings": {
"width": 512,
"height": 512,
"format": "png"
}
}
]
}
Running the Script:
Run the script using the command:
bash
python3 script3.py
Ensure script4.py exists in the same directory if you intend to run it after generating the images.
Troubleshooting Tips:
API Errors: If you encounter API errors, check your API token and ensure you have access to the specified Hugging Face model.
Network Issues: Verify that your system has internet access and can reach the Hugging Face API endpoint.
File Permissions: Ensure that the script has permission to write to the specified output directory.
Conclusion:
The updated script should now handle errors more gracefully and be compatible with the latest versions of its dependencies. If you encounter any further issues, consider checking the logs for detailed error messages and ensure all external resources and configurations are correctly set up.