File size: 6,273 Bytes
47bcb45
 
dca1837
 
 
 
4adf9d5
 
6b1a63d
4adf9d5
 
 
 
 
 
6b1a63d
4adf9d5
bce356e
4adf9d5
 
 
 
 
 
 
 
 
 
 
bce356e
4adf9d5
 
bce356e
4adf9d5
 
 
 
 
47bcb45
bce356e
dca1837
bce356e
4adf9d5
47bcb45
dca1837
36655d1
510fed1
36655d1
 
47bcb45
 
dca1837
47bcb45
 
 
 
 
 
 
 
 
 
 
 
 
 
dca1837
 
47bcb45
 
 
 
2db96fd
47bcb45
f869178
dca1837
 
6e387a5
 
2db96fd
 
 
 
 
dca1837
 
 
 
 
4adf9d5
dca1837
 
 
 
 
 
c683ec1
dca1837
c683ec1
dca1837
47bcb45
 
 
 
 
 
 
 
2db96fd
 
c683ec1
584268b
6e387a5
 
47bcb45
 
 
36655d1
2db96fd
c8c9b1c
901923c
f655b8c
493188c
47bcb45
c8c9b1c
47bcb45
901923c
47bcb45
6e387a5
2db96fd
584268b
47bcb45
6b1a63d
89897ec
 
 
 
 
 
 
 
 
584268b
ac5f7f1
 
 
38e2c92
dfa35d0
f869178
dfa35d0
493188c
dfa35d0
 
901923c
ac5f7f1
4adf9d5
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
import gradio as gr
from huggingface_hub import InferenceClient
from gradio_client import Client
from PIL import Image
import requests
from io import BytesIO
import re

# Function to fetch the API endpoint from the URL using regular expressions
def fetch_api_endpoint(url):
    try:
        headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
        response = requests.get(url, headers=headers)
        response.raise_for_status()  # Raise exception for HTTP errors
        
        # Use regular expressions to find the endpoint URL in the script content
        endpoint_match = re.search(r'root":"(https://[^"]+)', response.text)
        if endpoint_match:
            endpoint_url = endpoint_match.group(1)
            return endpoint_url
        else:
            return None
    except requests.RequestException as e:
        print("Error fetching URL:", e)
        return None
    except Exception as e:
        print("An unexpected error occurred:", e)
        return None

# Define the URL to fetch the API endpoint from
url = "https://playgroundai-playground-v2-5.hf.space/"

# Fetch the API endpoint
endpoint = fetch_api_endpoint(url)

if endpoint is None:
    print("Failed to fetch the API endpoint.")
    exit(1)

# Initialize the HuggingFace Inference Client with the specified model
client_mistral = InferenceClient("mistralai/Mistral-7B-Instruct-v0.2")
# Initialize the Playground AI client with the fetched endpoint
client_playground = Client(endpoint)

def format_prompt(logo_request):
    system_prompt = """
    You are an advanced language model designed to create detailed and creative image prompts for logo generation. Based on the user's input, generate an elaborate and descriptive image prompt that can be used to create a high-quality icon logo. Ensure that the prompt is clear, imaginative, and provides specific details that will guide the logo creation process effectively. The logo should be a simple, stylized, and abstract icon without any text, focusing solely on graphical elements suitable for a logo.
    """
    prompt = f"<s>[SYS] {system_prompt} [/SYS][INST] {logo_request} [/INST]</s>"
    return prompt

def generate_improved_prompt(logo_request, temperature=0.9, max_new_tokens=512, top_p=0.95, repetition_penalty=1.0):
    temperature = float(temperature)
    if temperature < 1e-2:
        temperature = 1e-2
    top_p = float(top_p)

    generate_kwargs = {
        "temperature": temperature,
        "max_new_tokens": max_new_tokens,
        "top_p": top_p,
        "repetition_penalty": repetition_penalty,
        "do_sample": True,
        "seed": 42,
    }

    formatted_prompt = format_prompt(logo_request)
    stream = client_mistral.text_generation(formatted_prompt, **generate_kwargs, stream=True, details=True, return_full_text=False)
    output = ""

    for response in stream:
        output += response.token.text
    return output

def generate_image(prompt, width=1024, height=1024, guidance_scale=3):
    result = client_playground.predict(
        prompt,
        "",  # negative prompt
        False,  # use negative prompt
        0,  # seed
        width,  # width
        height,  # height
        guidance_scale,  # guidance scale
        True,  # randomize seed
        api_name="/run"
    )

    # Extract the image URL from the result
    image_path = result[0][0]["image"]
    image_url = endpoint + "/file=" + image_path
    
    # Fetch and display the result image
    response = requests.get(image_url)
    
    if response.headers['Content-Type'].startswith('image'):
        img = Image.open(BytesIO(response.content))
        return img, image_url
    else:
        return None, None

css = """
#mkd {
    height: 500px; 
    overflow: auto; 
    border: 1px solid #ccc; 
}
"""

def process_request(logo_request, width, height, guidance_scale):
    improved_prompt = generate_improved_prompt(logo_request)
    image, image_url = generate_image(improved_prompt, width, height, guidance_scale)
    return image

with gr.Blocks(css=css) as app:
    with gr.Row():
        with gr.Column(scale=2):
            gr.HTML("<h1>Settings</h1>")
            logo_input = gr.Textbox(label="Input your logo request", placeholder="Describe the logo you want...")
            width = gr.Slider(label="Width", minimum=256, maximum=1536, value=1024)
            height = gr.Slider(label="Height", minimum=256, maximum=1536, value=1024)
            guidance_scale = gr.Slider(label="Guidance Scale", minimum=0.1, maximum=20, value=3)
            examples = gr.Examples(examples=["coffeeshop website logo", "bio food website logo", "car Selling website logo"], inputs=logo_input)
        
        with gr.Column(scale=3):
            gr.HTML("<h1><center>Magical AI Logo Generator</h1><center>")
            generate_button = gr.Button("Generate")
            image_output = gr.Image(label="Generated Logo")
            generate_button.click(
                fn=process_request,
                inputs=[logo_input, width, height, guidance_scale],
                outputs=[image_output]
            )

    with gr.Row():
        gr.HTML("<h2>Generated Examples</h2>")
        gr.Markdown("""
        | **Preview Image** | **Used Prompt**                | **Width**  | **Height**  | **Guidance Scale** | **Seed** |
        |-------------------|--------------------------------|------------|-------------|--------------------|----------|
        | ![Preview](https://i.imgur.com/CBvJ3sy.png) | Coffeeshop website logo  | 1024 | 1024 | 3 | 0 |
        | ![Preview](https://i.imgur.com/i2XpinX.png) | Bio food website logo   | 1024 | 1024 | 3  | 0 |
        | ![Preview](https://i.imgur.com/HeEjh4T.png) | Car Selling website logo | 1024 | 1024 | 3  | 0 |
        """)

    gr.Markdown("""
    ---
    ### Meta Information
    **Project Title**: Magical AI Logo Generator
    
    **Github**: [https://github.com/pacnimo/](https://github.com/pacnimo/)
    
    **Description**: Magical AI Logo Generator is Free and Easy to Use. Create an AI Website Logo for any Niche. 1 Click Logo Generator.
    
    **Footer**: © 2024 by [pacnimo](https://github.com/pacnimo/). All rights reserved.
    """)

app.launch(debug=True)