Untitled

mail@pastecode.io avatar
unknown
python
a year ago
13 kB
12
Indexable
Never
import os
import shutil
import time
import tempfile
import base64
import requests
from PIL import Image
import openai

# Set up the OpenAI API client
openai.api_key = "7ot let api key mta3 dirrabek"

IMAGE_FOLDER = "seq"
PROCESSED_IMAGE_FOLDER = "newcn"
from datetime import datetime

old_ins = """

You can include only one word from the following words in the generated prompt: realistic, modern, intricate, elegant, highly detailed, digital painting, artstation, concept art, addiction, chains, smooth, sharp focus, illustration, art by ilja repin
digital art, trending on artstation, hyperdetailed, matte painting, CGSociety

Add these to the generated negative prompt:
poorly Rendered face
poorly drawn face
poor facial details
poorly drawn hands
poorly rendered hands
low resolution
Images cut out at the top, left, right, bottom.
bad composition
mutated body parts
blurry image
disfigured
oversaturated
bad anatomy
deformed body features

"""


def generate_prompt():
    instruction = """
Generate a new positive and negative artistic and visually descriptive prompt. The prompts should be inspired by the following examples, but should not use these examples directly. Describe the texture and style of the art, always include 30 relevant artist names for that style of art in the positive prompt, and make the prompts 80 words long.

example prompts:

Positive example 1: cyborg woman| with a visible detailed brain| muscles cable wires| biopunk| cybernetic| cyberpunk| white marble bust| canon m50| 100mm| sharp focus| smooth| hyperrealism| highly detailed| intricate details| carved by michelangelo, H.R. Giger, Hajime Sorayama
Negative example 1: cgi| octane| render| digital art| digital painting| concept art| 3d| blurry| fuzzy| disfigured| misshaped| mutant| deformed| bad art| out of frame

Positive example 2: surreal landscape| floating islands| dreamy| glowing crystals| cascading waterfalls| vibrant colors| rich foliage| thick mist| mysterious| ethereal| Salvador Dalí, Yerka Jacek, Vladimir Kush
Negative example 2: flat colors| dull| boring| monochromatic| low contrast| washed out| uninspired| simplistic| lacking depth| sparse detail

Positive example 3: steampunk| mechanical dragon| intricate gears| brass| copper| steam engine| smoke| fire| ornate design| elegant craftsmanship| realistic textures| H.G. Wells, Brian Kesinger, James Ng
Negative example 3: plastic look| cheap materials| unrealistic| cartoonish| toy-like| low-quality| poorly executed| lacking authenticity| unconvincing

Positive example 4: futuristic cityscape| neon lights| bustling streets| skyscrapers| holographic advertisements| flying cars| advanced technology| reflections| rain-soaked pavement| Syd Mead, Masashi Wakui, Liam Wong
Negative example 4: repetitive buildings| poor lighting| empty streets| uninteresting| lack of atmosphere| generic| lifeless| unoriginal

Positive example 5: magical forest| ancient trees| glowing mushrooms| enchanted creatures| sparkling lights| lush vegetation| soft mist| whimsical| fairytale atmosphere| Thomas Kinkade, Andy Kehoe, Kinuko Y. Craft
Negative example 5: sparse trees| uninteresting flora| bland| unimaginative| lack of detail| unengaging| monotonous| mundane


append the following to the negative prompt only after you generate it:
EasyNegative
poorly Rendered face
poorly drawn face
poor facial details
poorly drawn hands
poorly rendered hands
low resolution
bad face
bad eyes
poorly drawn eyes
ugly eyes
Images cut out at the top left, right, bottom.
bad composition
mutated body parts
blurry image
disfigured
oversaturated
bad anatomy
deformed body features
poorly drawn finger
bad drawing
bad art
cropped



Make the generated negative and positive prompts exactly 150 words long, with the words in the generated prompts separated by " | " (with a space before and after the "|" character). The goal is to generate stunning and detailed art to sell online. Respond in the following format:
+ : words_min_positive_prompt
- : words_min_negative_prompt
do not give me one from the example prompts.
if the generated prompt includes a human body, include words to descripe the perfection of the anatomy
the generated positive prompt should be no less than 4000 character long.
include descriptions of color, texture and lighting of the art idea in the positive prompt.
Include 'in the style of <lora:howllatentDADAP4:1>' in positive prompt. also Include words like: masterpiece, 8k 
Make the prompts very  very detailed, describe every element of the image very very well.
put the most important words  that you want the viewer of the generated image to focus on between (( ))
always  only one \n  between the postive and negative prompt.

    """

    # Send the request to the OpenAI API
    response = openai.Completion.create(
        engine="text-davinci-003",
        prompt=instruction,
        temperature=1.2,
        max_tokens=3097 ,
        top_p=0.9,
        frequency_penalty=0,
        presence_penalty=0
    )
    print(response.choices[0].text.strip())
    # Extract and return the generated prompts
    return response.choices[0].text.strip()


generated_prompts = generate_prompt()
print(generate_prompt)
positive_prompt, negative_prompt = generated_prompts.split('\n')

print("\n \n \n \nGenerated Prompt: \n")
print(f"Generated positive prompt: {positive_prompt} \n")
print(f"Generated negative prompt: {negative_prompt}")

# ... (rest of the code remains the same)



DEFAULT_PARAMS =  {
            "prompt": positive_prompt.replace("Positive example 1", "").replace("+ :","")
,
            "negative_prompt": negative_prompt.replace("Negative example 1", "").replace("- :","")
,
            "seed": -1,
            "subseed": -1,
            "subseed_strength": 0,
            "batch_size": 1,
            "n_iter": 1,
            "steps": 40,
            "cfg_scale": 7,
            "width": 800,
            "denoising_strength": 0.45,
            "height": 600,
            "restore_faces": True,
            "eta": 0,
            "controlnet_enabled": False,
            "sampler_index": "DPM++ SDE Karras",
            "guessmode" : "true",
         #   "lowvram" : "true",
           # "controlnet_module": 'openpose',
            #"controlnet_model": 'controlnetPreTrained_openposeV10 [9ca67cc5]',
            "controlnet_guidance": 0,
            "model" : "howlsMovingCastleInterior_v3",
        }

def mix_images(img1, img2, alpha=0.5):
    img1 = Image.open(img1)
    img2 = Image.open(img2)
    
    img1 = img1.resize(img2.size, Image.ANTIALIAS)
    mixed_img = Image.blend(img1, img2, alpha)
    
    mixed_img_file = tempfile.NamedTemporaryFile(suffix=".png", delete=False)
    mixed_img.save(mixed_img_file.name, "PNG")
    
    return mixed_img_file.name

def process_images():
    image_files = os.listdir(os.path.abspath(IMAGE_FOLDER))
    image_files = [file for file in image_files if file.lower().endswith(('.png', '.jpg', '.jpeg'))]
  #  prompt_five_words = '-'.join(DEFAULT_PARAMS['prompt'].split()[:1]).replace(' ', '-')
    folder_name = f"{DEFAULT_PARAMS['model']}-{DEFAULT_PARAMS['denoising_strength']}-{DEFAULT_PARAMS['cfg_scale']}-{datetime.now().strftime('%Y%m%d-%H%M%S')}"
    global PROCESSED_IMAGE_FOLDER
    PROCESSED_IMAGE_FOLDER = os.path.join(os.getcwd(), folder_name)
    os.makedirs(PROCESSED_IMAGE_FOLDER, exist_ok=True)

    if len(image_files) > 0:
        image_path = os.path.join(os.path.abspath(IMAGE_FOLDER), image_files[0])
        last_output_file = process_image(image_path)

        if last_output_file:  # Check if the output file path is not False
            for image_file in image_files[1:]:
                image_path = os.path.join(os.path.abspath(IMAGE_FOLDER), image_file)
                mixed_image = mix_images(image_path, last_output_file)
                new_output_file = process_image(mixed_image)
                if new_output_file:  # Update last_output_file only if the new output file is valid
                    last_output_file = new_output_file


def process_image(image_path):
    timestamp = int(time.time())
    before_output_filename_prefix = f"{timestamp}-1-before"
    after_output_filename_prefix = f"{timestamp}-2-after"

    # Load the image
    try:
        img_file = open(image_path, 'rb')
        b64img = base64.b64encode(img_file.read()).decode()
        img_file.seek(0)  # Reset file pointer after reading
    except:
        return print(f"Couldn't open the image file: {image_path}")

    # Save the before image
    save_before_image(image_path, before_output_filename_prefix)

    # Prepare data for API
    params = DEFAULT_PARAMS

    params["controlnet_input_image"] = [b64img]
    params["init_images"] = [b64img]

    # Send to API
    output_file = actually_send_to_api(params, after_output_filename_prefix)

    # If we got a successful image created, save it to the processed folder
    if output_file:
        new_output_file = None

        # Save the after image
        new_output_file = save_after_image(
            after_output_filename_prefix, output_file)

        return new_output_file  # Return the output file path instead of True
    else:
        return False


def actually_send_to_api(params, filename_prefix):
    # create headers
    headers = {
        "User-Agent": "Yakdhane/",
        "Accept": "*/*",
        "Accept-Encoding": "gzip, deflate, br",
    }

    # prepare server url
    server_url = "http://localhost:9999" + "/controlnet/txt2img"

    # send API request
    try:
        response = requests.post(
            server_url, json=params, headers=headers, timeout=1000)
    except requests.exceptions.ConnectionError:
        return print(f"The Automatic1111 server couldn't be found.")
    except requests.exceptions.MissingSchema:
        return print(f"The url for your Automatic1111 server is invalid.")
    except requests.exceptions.ReadTimeout:
        return print("The Automatic1111 server timed out.")

    # Print HTTP request and response details
    print(f"HTTP Request URL: {response.request.url}")
    print(f"HTTP Request Method: {response.request.method}")
    print(f"HTTP Request Headers: {response.request.headers}")
    print(f"HTTP Request Body: {response.request.body}")
    print(f"HTTP Response Status Code: {response.status_code}")
    print(f"HTTP Response JSON: {response.json()}")


    # handle the response
    if response.status_code == 200:
        return handle_api_success(response, filename_prefix)
    else:
        return handle_api_error(response)

def handle_api_success(response, filename_prefix):
    try:
        response_obj = response.json()
        base64_img = response_obj["images"][0]
    except:
        print("Automatic1111 response content: ")
        print(response.content)
        return print("Received an unexpected response from the Automatic1111 server.")

    # create a temp file
    try:
        output_file = create_temp_file(filename_prefix + "-")
    except:
        return print("Couldn't create a temp file to save image.")

    # decode base64 image
    try:
        img_binary = base64.b64decode(
            base64_img.replace("data:image/png;base64,", ""))
    except:
        return print("Couldn't decode base64 image.")

    # save the image to the temp file
    try:
        with open(output_file, 'wb') as file:
            file.write(img_binary)
    except:
        return print("Couldn't write to temp file.")

    # return the temp file
    return output_file


def handle_api_error(response):
    if response.status_code == 404:
        import json
        try:
            response_obj = response.json()
            if response_obj.get('detail') and response_obj['detail'] == "Not Found":
                return print("It looks like the Automatic1111 server is running, but it's not in API mode.")
            elif response_obj.get('detail') and response_obj['detail'] == "Sampler not found":
                return print("The sampler you selected is not available.")
            else:
                return print(f"An error occurred in the Automatic1111 server. Full server response: {json.dumps(response_obj)}")
        except:
            return print("It looks like the Automatic1111 server is running, but it's not in API mode.")
    else:
        return print("An error occurred in the Automatic1111 server.")


def create_temp_file(prefix, suffix=".png"):
    return tempfile.NamedTemporaryFile(prefix=prefix, suffix=suffix).name

def save_before_image(image_path, filename_prefix):
    pass


def save_after_image(filename_prefix, img_file):
    filename = f"{filename_prefix}.png"
    full_path_and_filename = os.path.join(os.path.abspath(
        PROCESSED_IMAGE_FOLDER), filename)
    try:
        copy_file(img_file, full_path_and_filename)
        return full_path_and_filename
    except:
        return print(f"Couldn't save 'after' image to {full_path_and_filename}")

def copy_file(src, dest):
    shutil.copy2(src, dest)

# Call process_images to process the sequence of images
process_images()