Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -7,6 +7,7 @@ from subprocess import CalledProcessError, PIPE
|
|
7 |
from typing import Any, List
|
8 |
from uuid import uuid4
|
9 |
|
|
|
10 |
from fastapi import FastAPI, HTTPException
|
11 |
from fastapi.responses import PlainTextResponse
|
12 |
from httpx import AsyncClient, HTTPStatusError, RequestError
|
@@ -15,7 +16,7 @@ from uvicorn import run as uvicorn_run
|
|
15 |
|
16 |
need_logging = False
|
17 |
|
18 |
-
basicConfig(level
|
19 |
logger = getLogger(__name__)
|
20 |
|
21 |
oxipng_bin = Path(__file__).parent / 'oxipng'
|
@@ -80,6 +81,26 @@ async def optimize_png(image_path: Path, retries: int = 3) -> None:
|
|
80 |
raise e
|
81 |
|
82 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
83 |
async def optimize_pngs(image_paths: list[str | Path] | str | Path) -> None:
|
84 |
image_paths = [Path(image_file) for image_file in ([image_paths] if not isinstance(image_paths, list) else image_paths)]
|
85 |
logger.info(f'оптимизируется список список из {len(image_paths)}: {image_paths}')
|
@@ -87,32 +108,6 @@ async def optimize_pngs(image_paths: list[str | Path] | str | Path) -> None:
|
|
87 |
await gather(*tasks)
|
88 |
|
89 |
|
90 |
-
async def telegraph_upload_png(file_path: str | Path) -> str | None:
|
91 |
-
file_path = Path(file_path)
|
92 |
-
if not file_path.is_file() or file_path.stat().st_size > 5 * 1024 * 1024:
|
93 |
-
return None
|
94 |
-
url = 'https://telegra.ph/upload'
|
95 |
-
headers = {
|
96 |
-
'authority': url.rsplit('/')[2],
|
97 |
-
'accept': 'application/json, text/javascript, */*; q=0.01',
|
98 |
-
'origin': url.rsplit('/', 1)[0],
|
99 |
-
'referer': url.rsplit('/', 1)[0],
|
100 |
-
'x-requested-with': 'XMLHttpRequest',
|
101 |
-
}
|
102 |
-
async with AsyncClient() as client:
|
103 |
-
try:
|
104 |
-
response = await client.post(url, headers=headers, files={'file': ('blob', file_path.read_bytes(), 'image/png')})
|
105 |
-
response.raise_for_status()
|
106 |
-
result = response.json()
|
107 |
-
except:
|
108 |
-
return None
|
109 |
-
if response.is_success and 'error' not in result:
|
110 |
-
link = result[0]['src']
|
111 |
-
return url.rsplit('/', 1)[0] + link
|
112 |
-
else:
|
113 |
-
return None
|
114 |
-
|
115 |
-
|
116 |
async def upload_image_to_imgbb(file_path: Path) -> str | None:
|
117 |
url = f'https://api.imgbb.com/1/upload?key={choice(tokens)}'
|
118 |
try:
|
@@ -131,15 +126,17 @@ async def upload_image_to_imgbb(file_path: Path) -> str | None:
|
|
131 |
|
132 |
async def upload_image(file_path: Path | str) -> str | None:
|
133 |
file_path = Path(file_path)
|
134 |
-
return await
|
135 |
|
136 |
|
137 |
-
async def optimize_and_upload(images_urls: list[str] | str) -> list[str]:
|
138 |
images_urls = [images_urls] if isinstance(images_urls, str) else images_urls
|
139 |
logger.info(f'принятые ссылки в обработку ({len(images_urls)}): {images_urls}')
|
140 |
images_paths = await download_pngs(images_urls)
|
141 |
-
|
|
|
142 |
new_images_urls = []
|
|
|
143 |
for image_path in images_paths:
|
144 |
new_url = await upload_image(image_path)
|
145 |
if new_url:
|
@@ -178,5 +175,14 @@ async def optimize_images_endpoint(image_urls: ImageURLs):
|
|
178 |
raise HTTPException(status_code=500, detail=str(e))
|
179 |
|
180 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
181 |
if __name__ == "__main__":
|
182 |
uvicorn_run(app, host='0.0.0.0', port=7860, timeout_keep_alive=90)
|
|
|
7 |
from typing import Any, List
|
8 |
from uuid import uuid4
|
9 |
|
10 |
+
from PIL import Image
|
11 |
from fastapi import FastAPI, HTTPException
|
12 |
from fastapi.responses import PlainTextResponse
|
13 |
from httpx import AsyncClient, HTTPStatusError, RequestError
|
|
|
16 |
|
17 |
need_logging = False
|
18 |
|
19 |
+
basicConfig(level=INFO if need_logging else ERROR)
|
20 |
logger = getLogger(__name__)
|
21 |
|
22 |
oxipng_bin = Path(__file__).parent / 'oxipng'
|
|
|
81 |
raise e
|
82 |
|
83 |
|
84 |
+
async def convert_to_jpeg(image_path: Path) -> Path:
|
85 |
+
logger.info(f'конвертируется {image_path}')
|
86 |
+
try:
|
87 |
+
image = Image.open(image_path)
|
88 |
+
output_path = image_path.with_suffix('.jpg')
|
89 |
+
image.save(output_path, 'JPEG', quality=98, optimize=True)
|
90 |
+
image_path.unlink(missing_ok=True)
|
91 |
+
return output_path
|
92 |
+
except:
|
93 |
+
logger.error(f'ошибка при конвертации {image_path}')
|
94 |
+
return image_path
|
95 |
+
|
96 |
+
|
97 |
+
async def convert_to_jpegs(image_paths: list[str | Path] | str | Path) -> tuple[Path]:
|
98 |
+
image_paths = [Path(image_file) for image_file in ([image_paths] if not isinstance(image_paths, list) else image_paths)]
|
99 |
+
logger.info(f'оптимизируется список список из {len(image_paths)}: {image_paths}')
|
100 |
+
tasks = [convert_to_jpeg(image_path) for image_path in image_paths]
|
101 |
+
return await gather(*tasks)
|
102 |
+
|
103 |
+
|
104 |
async def optimize_pngs(image_paths: list[str | Path] | str | Path) -> None:
|
105 |
image_paths = [Path(image_file) for image_file in ([image_paths] if not isinstance(image_paths, list) else image_paths)]
|
106 |
logger.info(f'оптимизируется список список из {len(image_paths)}: {image_paths}')
|
|
|
108 |
await gather(*tasks)
|
109 |
|
110 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
111 |
async def upload_image_to_imgbb(file_path: Path) -> str | None:
|
112 |
url = f'https://api.imgbb.com/1/upload?key={choice(tokens)}'
|
113 |
try:
|
|
|
126 |
|
127 |
async def upload_image(file_path: Path | str) -> str | None:
|
128 |
file_path = Path(file_path)
|
129 |
+
return await upload_image_to_imgbb(file_path)
|
130 |
|
131 |
|
132 |
+
async def optimize_and_upload(images_urls: list[str] | str, convert: bool = False) -> list[str]:
|
133 |
images_urls = [images_urls] if isinstance(images_urls, str) else images_urls
|
134 |
logger.info(f'принятые ссылки в обработку ({len(images_urls)}): {images_urls}')
|
135 |
images_paths = await download_pngs(images_urls)
|
136 |
+
if not convert:
|
137 |
+
await optimize_pngs(images_paths)
|
138 |
new_images_urls = []
|
139 |
+
images_paths = images_paths if not convert else await convert_to_jpegs(images_paths)
|
140 |
for image_path in images_paths:
|
141 |
new_url = await upload_image(image_path)
|
142 |
if new_url:
|
|
|
175 |
raise HTTPException(status_code=500, detail=str(e))
|
176 |
|
177 |
|
178 |
+
@app.post('/jpegs_by_urls/')
|
179 |
+
async def optimize_images_endpoint(image_urls: ImageURLs):
|
180 |
+
try:
|
181 |
+
optimized_urls = await optimize_and_upload([str(url) for url in image_urls.urls])
|
182 |
+
return {"optimized_urls": optimized_urls}
|
183 |
+
except Exception as e:
|
184 |
+
raise HTTPException(status_code=500, detail=str(e))
|
185 |
+
|
186 |
+
|
187 |
if __name__ == "__main__":
|
188 |
uvicorn_run(app, host='0.0.0.0', port=7860, timeout_keep_alive=90)
|