Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -9,6 +9,8 @@ import logging
|
|
| 9 |
import threading
|
| 10 |
from PIL import Image
|
| 11 |
from io import BytesIO
|
|
|
|
|
|
|
| 12 |
|
| 13 |
odnapi = os.getenv("odnapi_url")
|
| 14 |
fetapi = os.getenv("fetapi_url")
|
|
@@ -18,14 +20,6 @@ auth_token = os.getenv("auth_token")
|
|
| 18 |
logging.basicConfig(level=logging.INFO)
|
| 19 |
logger = logging.getLogger(__name__)
|
| 20 |
|
| 21 |
-
def fetch_image(url):
|
| 22 |
-
try:
|
| 23 |
-
response = requests.get(url)
|
| 24 |
-
return Image.open(BytesIO(response.content))
|
| 25 |
-
except requests.exceptions.RequestException as e:
|
| 26 |
-
logger.error(f"Failed to fetch image")
|
| 27 |
-
raise
|
| 28 |
-
|
| 29 |
def split_image(img):
|
| 30 |
width, height = img.size
|
| 31 |
width_cut = width // 2
|
|
@@ -41,34 +35,67 @@ def save_image(img, suffix='.png'):
|
|
| 41 |
with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as tmp:
|
| 42 |
img.save(tmp, 'PNG')
|
| 43 |
return tmp.name
|
| 44 |
-
|
| 45 |
-
def
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
|
|
|
|
|
|
| 51 |
try:
|
| 52 |
-
response =
|
| 53 |
response.raise_for_status() # Check for HTTP errors.
|
| 54 |
except requests.exceptions.RequestException as e:
|
| 55 |
logger.error(f"Failed to make POST request")
|
| 56 |
raise ValueError("Invalid Response")
|
| 57 |
data = response.json()
|
| 58 |
message_id = data['messageId']
|
| 59 |
-
|
| 60 |
-
|
|
|
|
|
|
|
|
|
|
| 61 |
try:
|
| 62 |
-
response =
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
response.raise_for_status()
|
| 64 |
except requests.exceptions.RequestException as e:
|
| 65 |
logger.warning(f"Failure in getting message response")
|
| 66 |
continue
|
| 67 |
data = response.json()
|
| 68 |
-
|
| 69 |
-
if progress_image_url:= data.get('progressImageUrl'):
|
| 70 |
-
|
| 71 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
# Process the final image urls
|
| 73 |
image_url = data['response']['imageUrl']
|
| 74 |
yield [(img, f"image {idx+1}/4") for idx, img in enumerate(download_and_split_image(image_url))]
|
|
|
|
| 9 |
import threading
|
| 10 |
from PIL import Image
|
| 11 |
from io import BytesIO
|
| 12 |
+
from requests.adapters import HTTPAdapter
|
| 13 |
+
from urllib3.util import Retry
|
| 14 |
|
| 15 |
odnapi = os.getenv("odnapi_url")
|
| 16 |
fetapi = os.getenv("fetapi_url")
|
|
|
|
| 20 |
logging.basicConfig(level=logging.INFO)
|
| 21 |
logger = logging.getLogger(__name__)
|
| 22 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
def split_image(img):
|
| 24 |
width, height = img.size
|
| 25 |
width_cut = width // 2
|
|
|
|
| 35 |
with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as tmp:
|
| 36 |
img.save(tmp, 'PNG')
|
| 37 |
return tmp.name
|
| 38 |
+
|
| 39 |
+
async def niji_api(prompt, progress=gr.Progress(), max_retries=5, backoff_factor=0.1):
|
| 40 |
+
iters = 1
|
| 41 |
+
progress(iters/32, desc="Sending request to MidJourney Server")
|
| 42 |
+
session = requests.Session() # Using Session to reuse the underlying TCP connection
|
| 43 |
+
retries = Retry(total=max_retries, backoff_factor=backoff_factor, status_forcelist=[429, 500, 502, 503, 504])
|
| 44 |
+
adapter = HTTPAdapter(max_retries=retries)
|
| 45 |
+
session.mount("http://", adapter)
|
| 46 |
+
session.mount("https://", adapter)
|
| 47 |
try:
|
| 48 |
+
response = session.post(fetapi, headers={'Content-Type': 'application/json'}, data=json.dumps({'msg': prompt}))
|
| 49 |
response.raise_for_status() # Check for HTTP errors.
|
| 50 |
except requests.exceptions.RequestException as e:
|
| 51 |
logger.error(f"Failed to make POST request")
|
| 52 |
raise ValueError("Invalid Response")
|
| 53 |
data = response.json()
|
| 54 |
message_id = data['messageId']
|
| 55 |
+
prog = 0
|
| 56 |
+
iters += 5
|
| 57 |
+
progress(iters/48, desc="Waiting in the generate queue")
|
| 58 |
+
|
| 59 |
+
def fetch_image(url):
|
| 60 |
try:
|
| 61 |
+
response = session.get(url)
|
| 62 |
+
return Image.open(BytesIO(response.content))
|
| 63 |
+
except requests.exceptions.RequestException as e:
|
| 64 |
+
logger.error(f"Failed to fetch image")
|
| 65 |
+
raise
|
| 66 |
+
|
| 67 |
+
def download_and_split_image(url):
|
| 68 |
+
img = fetch_image(url)
|
| 69 |
+
images = split_image(img)
|
| 70 |
+
return [save_image(i) for i in images]
|
| 71 |
+
|
| 72 |
+
while prog < 100:
|
| 73 |
+
try:
|
| 74 |
+
response = session.get(f'{odnapi}/message/{message_id}?expireMins=2', headers={'Authorization': auth_token})
|
| 75 |
response.raise_for_status()
|
| 76 |
except requests.exceptions.RequestException as e:
|
| 77 |
logger.warning(f"Failure in getting message response")
|
| 78 |
continue
|
| 79 |
data = response.json()
|
| 80 |
+
prog = data.get('progress', 0)
|
| 81 |
+
if progress_image_url := data.get('progressImageUrl'):
|
| 82 |
+
iters = -100
|
| 83 |
+
yield [(img, f"{prog}% done") for img in download_and_split_image(progress_image_url)]
|
| 84 |
+
|
| 85 |
+
wait_time = random.uniform(1, 2)
|
| 86 |
+
await asyncio.sleep(wait_time)
|
| 87 |
+
|
| 88 |
+
r = iters/48
|
| 89 |
+
if r < 0.4:
|
| 90 |
+
desc = "Waiting in the generate queue"
|
| 91 |
+
elif r < 0.6:
|
| 92 |
+
desc = "Still queueing"
|
| 93 |
+
elif r < 0.8:
|
| 94 |
+
desc = "Almost done"
|
| 95 |
+
if iters > 0:
|
| 96 |
+
progress(r, desc=desc)
|
| 97 |
+
iters += random.uniform(1, 2)
|
| 98 |
+
|
| 99 |
# Process the final image urls
|
| 100 |
image_url = data['response']['imageUrl']
|
| 101 |
yield [(img, f"image {idx+1}/4") for idx, img in enumerate(download_and_split_image(image_url))]
|