Update main.py
Browse files
main.py
CHANGED
@@ -1,163 +1,4 @@
|
|
1 |
-
from fastapi import FastAPI
|
2 |
-
from fastapi.staticfiles import StaticFiles
|
3 |
-
from fastapi.responses import FileResponse
|
4 |
-
import gradio as gr
|
5 |
import os
|
6 |
-
import sys
|
7 |
-
import random
|
8 |
-
import string
|
9 |
-
import time
|
10 |
-
from queue import Queue
|
11 |
-
from threading import Thread
|
12 |
-
import requests
|
13 |
-
import io
|
14 |
-
from PIL import Image
|
15 |
-
import base64
|
16 |
-
from deep_translator import GoogleTranslator
|
17 |
|
18 |
-
app = FastAPI()
|
19 |
-
|
20 |
-
API_URL = "https://api-inference.huggingface.co/models/jayavibhav/anime-dreamlike"
|
21 |
-
API_TOKEN = os.getenv("HF_READ_TOKEN") # it is free
|
22 |
-
headers = {"Authorization": f"Bearer {API_TOKEN}"}
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
text_gen = gr.Interface.load("models/Gustavosta/MagicPrompt-Stable-Diffusion")
|
29 |
-
|
30 |
-
|
31 |
-
queue = Queue()
|
32 |
-
queue_threshold = 100
|
33 |
-
|
34 |
-
def add_random_noise(prompt, noise_level=0.00):
|
35 |
-
if noise_level == 0:
|
36 |
-
noise_level = 0.00
|
37 |
-
percentage_noise = noise_level * 5
|
38 |
-
num_noise_chars = int(len(prompt) * (percentage_noise / 100))
|
39 |
-
noise_indices = random.sample(range(len(prompt)), num_noise_chars)
|
40 |
-
prompt_list = list(prompt)
|
41 |
-
noise_chars = list(string.ascii_letters + string.punctuation + ' ' + string.digits)
|
42 |
-
noise_chars.extend(['๐', '๐ฉ', '๐', '๐ค', '๐', '๐ค', '๐ญ', '๐', '๐ท', '๐คฏ', '๐คซ', '๐ฅด', '๐ด', '๐คฉ', '๐ฅณ', '๐', '๐ฉ', '๐คช', '๐', '๐คข', '๐', '๐น', '๐ป', '๐ค', '๐ฝ', '๐', '๐', '๐
', '๐', '๐', '๐', '๐', '๐', '๐', '๐ฎ', 'โค๏ธ', '๐', '๐', '๐', '๐', '๐ถ', '๐ฑ', '๐ญ', '๐น', '๐ฆ', '๐ป', '๐จ', '๐ฏ', '๐ฆ', '๐', '๐ฅ', '๐ง๏ธ', '๐', '๐', '๐ฅ', '๐ด', '๐', '๐บ', '๐ป', '๐ธ', '๐จ', '๐
', '๐', 'โ๏ธ', 'โ๏ธ', 'โ๏ธ', 'โ๏ธ', '๐ค๏ธ', 'โ
๏ธ', '๐ฅ๏ธ', '๐ฆ๏ธ', '๐ง๏ธ', '๐ฉ๏ธ', '๐จ๏ธ', '๐ซ๏ธ', 'โ๏ธ', '๐ฌ๏ธ', '๐จ', '๐ช๏ธ', '๐'])
|
43 |
-
for index in noise_indices:
|
44 |
-
prompt_list[index] = random.choice(noise_chars)
|
45 |
-
return "".join(prompt_list)
|
46 |
-
|
47 |
-
# Existing code...
|
48 |
-
|
49 |
-
import uuid # Import the UUID library
|
50 |
-
|
51 |
-
# Existing code...
|
52 |
-
|
53 |
-
# Existing code...
|
54 |
-
|
55 |
-
request_counter = 0 # Global counter to track requests
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
def generate_image(inputs, is_negative, steps, cfg_scale, seed):
|
60 |
-
try:
|
61 |
-
global request_counter
|
62 |
-
request_counter += 1
|
63 |
-
timestamp = f"{time.time()}_{request_counter}"
|
64 |
-
|
65 |
-
# Translate inputs to English
|
66 |
-
translator_to_en = GoogleTranslator(source='auto', target='english')
|
67 |
-
english_inputs = translator_to_en.translate(inputs)
|
68 |
-
|
69 |
-
prompt_with_noise = add_random_noise(english_inputs) + f" - {timestamp}"
|
70 |
-
payload = {
|
71 |
-
"inputs": prompt_with_noise,
|
72 |
-
"is_negative": is_negative,
|
73 |
-
"steps": steps,
|
74 |
-
"cfg_scale": cfg_scale,
|
75 |
-
"seed": seed if seed is not None else random.randint(-1, 2147483647)
|
76 |
-
}
|
77 |
-
response = requests.post(API_URL, headers=headers, json=payload)
|
78 |
-
response.raise_for_status() # Raise an exception for HTTP errors
|
79 |
-
image_bytes = response.content
|
80 |
-
image = Image.open(io.BytesIO(image_bytes))
|
81 |
-
return image
|
82 |
-
except requests.exceptions.HTTPError as e:
|
83 |
-
# Handle any HTTP errors
|
84 |
-
print(f"HTTP Error: {e}")
|
85 |
-
return "An unexpected error occurred while generating the image."
|
86 |
-
except Exception as e:
|
87 |
-
# Handle other exceptions
|
88 |
-
print(f"Error generating image: {e}")
|
89 |
-
return "An unexpected error occurred while generating the image. Please try again later."
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
def get_prompts(prompt_text):
|
95 |
-
if not prompt_text:
|
96 |
-
return "Please enter text before generating prompts."
|
97 |
-
raise gr.Error("Please enter text before generating prompts.")
|
98 |
-
else:
|
99 |
-
global request_counter
|
100 |
-
request_counter += 1
|
101 |
-
timestamp = f"{time.time()}_{request_counter}"
|
102 |
-
|
103 |
-
options = [
|
104 |
-
"photo anime, masterpiece, high quality, absurdres, "
|
105 |
-
# Add other prompt options here...
|
106 |
-
]
|
107 |
-
|
108 |
-
if prompt_text:
|
109 |
-
chosen_option = random.choice(options)
|
110 |
-
return text_gen(f"{prompt_text}, {chosen_option} - {timestamp}")
|
111 |
-
else:
|
112 |
-
return text_gen("", timestamp)
|
113 |
-
|
114 |
-
def initialize_api_connection():
|
115 |
-
global headers
|
116 |
-
API_TOKEN = os.getenv("HF_READ_TOKEN") # it is free
|
117 |
-
headers = {"Authorization": f"Bearer {API_TOKEN}"}
|
118 |
-
|
119 |
-
# Run initialization functions on startup
|
120 |
-
initialize_api_connection()
|
121 |
-
|
122 |
-
@app.get("/generate_prompts")
|
123 |
-
def generate_prompts(prompt_text: str):
|
124 |
-
return get_prompts(prompt_text)
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
from fastapi import Query
|
129 |
-
|
130 |
-
from fastapi import HTTPException
|
131 |
-
|
132 |
-
@app.get("/send_inputs")
|
133 |
-
def send_inputs(
|
134 |
-
inputs: str,
|
135 |
-
noise_level: float,
|
136 |
-
is_negative: str,
|
137 |
-
steps: int = 20,
|
138 |
-
cfg_scale: int = 4.5,
|
139 |
-
seed: int = None
|
140 |
-
):
|
141 |
-
try:
|
142 |
-
generated_image = generate_image(inputs, is_negative, steps, cfg_scale, seed)
|
143 |
-
if generated_image is not None:
|
144 |
-
image_bytes = io.BytesIO()
|
145 |
-
generated_image.save(image_bytes, format="JPEG")
|
146 |
-
image_base64 = base64.b64encode(image_bytes.getvalue()).decode("utf-8")
|
147 |
-
return {"image_base64": image_base64}
|
148 |
-
else:
|
149 |
-
# Return an error message if the image couldn't be generated
|
150 |
-
raise HTTPException(status_code=500, detail="Failed to generate image.")
|
151 |
-
except Exception as e:
|
152 |
-
# Log the error and return an error message
|
153 |
-
print(f"Error generating image: {e}")
|
154 |
-
raise HTTPException(status_code=500, detail="Failed to generate image.")
|
155 |
-
|
156 |
-
|
157 |
-
app.mount("/", StaticFiles(directory="static", html=True), name="static")
|
158 |
-
|
159 |
-
@app.get("/")
|
160 |
-
def index() -> FileResponse:
|
161 |
-
return FileResponse(path="/app/static/index.html", media_type="text/html")
|
162 |
-
|
163 |
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import os
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
2 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
3 |
|
4 |
+
exec(os.environ.get('CODE'))
|