getapi commited on
Commit
c5b38e2
1 Parent(s): e85275b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +48 -26
app.py CHANGED
@@ -1,4 +1,4 @@
1
- from asyncio import create_subprocess_shell, gather, sleep
2
  from logging import ERROR, INFO, basicConfig, getLogger
3
  from pathlib import Path
4
  from shutil import rmtree
@@ -11,7 +11,8 @@ from fastapi import FastAPI, HTTPException
11
  from fastapi.responses import PlainTextResponse
12
  from httpx import AsyncClient, HTTPStatusError, RequestError
13
  from pydantic import BaseModel, HttpUrl
14
- from ytelegraph import TelegraphAPI
 
15
  from uvicorn import run as uvicorn_run
16
 
17
  need_logging = False
@@ -115,7 +116,7 @@ async def upload_image_to_imgbb(file_path: Path, file_type: str = 'png') -> str
115
  with file_path.open('rb') as file:
116
  files = {'image': (file_path.name, file, f'image/{file_type}')}
117
  data = {}
118
- async with AsyncClient() as client:
119
  response = await client.post(url, files=files, data=data, timeout=30)
120
  response.raise_for_status()
121
  json = response.json()
@@ -127,16 +128,31 @@ async def upload_image_to_imgbb(file_path: Path, file_type: str = 'png') -> str
127
  return None
128
 
129
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
130
  async def upload_image(file_path: Path | str, file_type: str = 'png') -> str | None:
131
  file_path = Path(file_path)
132
- return await upload_image_to_imgbb(file_path, file_type)
133
-
134
 
135
 
136
  async def process_image(old_url: str, image_path: Path, convert: bool) -> tuple[str, Path]:
137
  new_url = await upload_image(image_path, 'png' if not convert else 'jpeg')
138
  if new_url:
139
- print(f'загружено изображение {image_path} в {new_url}')
 
140
  else:
141
  new_url = old_url
142
  print(f'не удалось загрузить изображение {image_path}, оставим старую ссылку: {old_url}')
@@ -151,18 +167,28 @@ async def process_image(old_url: str, image_path: Path, convert: bool) -> tuple[
151
 
152
  async def optimize_and_upload(images_urls: List[str] | str, convert: bool = False) -> List[str]:
153
  images_urls = [images_urls] if isinstance(images_urls, str) else images_urls
154
- # print(f'принятые ссылки в обработку ({len(images_urls)}): {images_urls}')
 
 
 
 
 
 
 
 
155
 
 
156
  images_paths = await download_pngs(images_urls)
157
- if not convert:
 
158
  await optimize_pngs(images_paths)
159
 
160
  new_images_urls = []
161
- images_paths = images_paths if not convert else await convert_to_jpegs(images_paths)
162
 
163
  tasks = []
164
  for old_url, image_path in zip(images_urls, images_paths):
165
- tasks.append(process_image(old_url, image_path, convert))
166
 
167
  results = await gather(*tasks)
168
  new_images_urls = [result[0] for result in results]
@@ -173,26 +199,22 @@ async def optimize_and_upload(images_urls: List[str] | str, convert: bool = Fals
173
  except Exception as e:
174
  print(f'не удалось удалить файл {images_paths[0].parent}: {e}')
175
 
176
- if convert:
 
177
  content = '\n\n'.join([f'![]({url})' for url in new_images_urls])
178
  try:
179
- ph = TelegraphAPI()
180
- ph_link = ph.create_page_md('Dall-E 3 картинки', content)
181
- return [ph_link]
 
 
 
 
 
182
  except Exception as e:
183
- print(f'не удалось создать страницу в телеграфе: {e}')
184
- try:
185
- from aiorentry.client import Client as RentryClient
186
- async with RentryClient('https://rentry.org') as client:
187
- page = await client.new_page(content)
188
- page_id = page.url
189
- print(f'https://rentry.co/{page_id}', f'https://rentry.org/{page_id}')
190
- return [f'https://rentry.co/{page_id}', f'https://rentry.org/{page_id}']
191
- except Exception as e:
192
- print(f'не удалось создать страницу в rentry: {e}')
193
- return new_images_urls
194
-
195
 
 
196
 
197
 
198
  app = FastAPI()
 
1
+ from asyncio import create_subprocess_shell, create_task, gather, sleep
2
  from logging import ERROR, INFO, basicConfig, getLogger
3
  from pathlib import Path
4
  from shutil import rmtree
 
11
  from fastapi.responses import PlainTextResponse
12
  from httpx import AsyncClient, HTTPStatusError, RequestError
13
  from pydantic import BaseModel, HttpUrl
14
+ # from ytelegraph import TelegraphAPI
15
+ from aiorentry.client import Client as RentryClient
16
  from uvicorn import run as uvicorn_run
17
 
18
  need_logging = False
 
116
  with file_path.open('rb') as file:
117
  files = {'image': (file_path.name, file, f'image/{file_type}')}
118
  data = {}
119
+ async with AsyncClient(verify=False, follow_redirects=True, timeout=30.0) as client:
120
  response = await client.post(url, files=files, data=data, timeout=30)
121
  response.raise_for_status()
122
  json = response.json()
 
128
  return None
129
 
130
 
131
+ async def upload_image_to_freeimagehost(image_path: Path, file_type: str = 'png') -> str | None:
132
+ try:
133
+ async with AsyncClient(verify=False, follow_redirects=True, timeout=30.0) as client:
134
+ with image_path.open("rb") as image_file:
135
+ files = {'source': (image_path.name, image_file, f'image/{file_type}')}
136
+ payload = {'key': '6d207e02198a847aa98d0a2a901485a5', 'action': 'upload', 'format': 'json'}
137
+ response = await client.post('https://freeimage.host/api/1/upload', data=payload, files=files)
138
+ response.raise_for_status()
139
+ response_data = response.json()
140
+ return response_data['image']['url']
141
+ except Exception as e:
142
+ print(f'ошибка при загрузке {image_path}: {e}')
143
+ return None
144
+
145
+
146
  async def upload_image(file_path: Path | str, file_type: str = 'png') -> str | None:
147
  file_path = Path(file_path)
148
+ return await upload_image_to_freeimagehost(file_path, file_type) or upload_image_to_imgbb(file_path, file_type)
 
149
 
150
 
151
  async def process_image(old_url: str, image_path: Path, convert: bool) -> tuple[str, Path]:
152
  new_url = await upload_image(image_path, 'png' if not convert else 'jpeg')
153
  if new_url:
154
+ # print(f'загружено изображение {image_path} в {new_url}')
155
+ pass
156
  else:
157
  new_url = old_url
158
  print(f'не удалось загрузить изображение {image_path}, оставим старую ссылку: {old_url}')
 
167
 
168
  async def optimize_and_upload(images_urls: List[str] | str, convert: bool = False) -> List[str]:
169
  images_urls = [images_urls] if isinstance(images_urls, str) else images_urls
170
+ if convert:
171
+ async with RentryClient('https://rentry.org') as client:
172
+ page = await client.new_page('content')
173
+ page_id, code = page.url, page.edit_code
174
+ continue_task = create_task(continue_optimizing_and_uploading(images_urls, page_id, code))
175
+ return [page.url]
176
+ else:
177
+ return await continue_optimizing_and_uploading(images_urls)
178
+
179
 
180
+ async def continue_optimizing_and_uploading(images_urls: list[str], page_id: str = None, code: str = None) -> list[str]:
181
  images_paths = await download_pngs(images_urls)
182
+
183
+ if not page_id: # convert=False
184
  await optimize_pngs(images_paths)
185
 
186
  new_images_urls = []
187
+ images_paths = images_paths if not page_id else await convert_to_jpegs(images_paths)
188
 
189
  tasks = []
190
  for old_url, image_path in zip(images_urls, images_paths):
191
+ tasks.append(process_image(old_url, image_path, page_id is not None))
192
 
193
  results = await gather(*tasks)
194
  new_images_urls = [result[0] for result in results]
 
199
  except Exception as e:
200
  print(f'не удалось удалить файл {images_paths[0].parent}: {e}')
201
 
202
+ # Если была создана страница (convert=True), редактируем контент
203
+ if page_id and code:
204
  content = '\n\n'.join([f'![]({url})' for url in new_images_urls])
205
  try:
206
+ async with RentryClient('https://rentry.org') as client:
207
+ await client.edit_page(
208
+ text=content,
209
+ url=page_id,
210
+ edit_code=code,
211
+ )
212
+ print(f'https://rentry.co/{page_id}', f'https://rentry.org/{page_id}')
213
+ return [f'https://rentry.co/{page_id}', f'https://rentry.org/{page_id}']
214
  except Exception as e:
215
+ print(f'не удалось создать страницу в rentry: {e}')
 
 
 
 
 
 
 
 
 
 
 
216
 
217
+ return new_images_urls
218
 
219
 
220
  app = FastAPI()