Update app.py
Browse files
app.py
CHANGED
|
@@ -1,4 +1,5 @@
|
|
| 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
|
|
@@ -7,22 +8,16 @@ from typing import Any, List
|
|
| 7 |
from uuid import uuid4
|
| 8 |
|
| 9 |
from PIL import Image
|
|
|
|
| 10 |
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, TelegraphAccount
|
| 15 |
-
from aiorentry.client import Client as RentryClient
|
| 16 |
from uvicorn import run as uvicorn_run
|
| 17 |
|
| 18 |
-
|
| 19 |
-
environ['PH_TOKEN_PATH'] = (Path(__file__).parent / 'ph.txt').as_posix()
|
| 20 |
-
try:
|
| 21 |
-
ph = TelegraphAPI(access_token='886b4af0a626c532c0ea6e86cd3b362a32c09d6485cc8e2bccae956032cf')
|
| 22 |
-
ta = TelegraphAccount(access_token='886b4af0a626c532c0ea6e86cd3b362a32c09d6485cc8e2bccae956032cf')
|
| 23 |
-
except:
|
| 24 |
-
ph = TelegraphAPI()
|
| 25 |
-
ta = TelegraphAccount()
|
| 26 |
|
| 27 |
need_logging = False
|
| 28 |
|
|
@@ -43,6 +38,112 @@ tokens = [
|
|
| 43 |
]
|
| 44 |
|
| 45 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
async def download_png(url: str, folder: str, client: AsyncClient, retries: int = 5) -> Path:
|
| 47 |
# print(f'загрузка изображения: {url}')
|
| 48 |
for attempt in range(retries):
|
|
@@ -178,7 +279,7 @@ async def optimize_and_upload(images_urls: List[str] | str, convert: bool = Fals
|
|
| 178 |
images_urls = [images_urls] if isinstance(images_urls, str) else images_urls
|
| 179 |
if convert:
|
| 180 |
try:
|
| 181 |
-
ph_link =
|
| 182 |
except Exception as e:
|
| 183 |
print(f'не получилось создать страницу на телеграфе: {e}')
|
| 184 |
ph_link = None
|
|
@@ -186,8 +287,8 @@ async def optimize_and_upload(images_urls: List[str] | str, convert: bool = Fals
|
|
| 186 |
page = await client.new_page('изображения скоро появятся, обнови страницу...')
|
| 187 |
page_id, code = page.url, page.edit_code
|
| 188 |
continue_task = create_task(continue_optimizing_and_uploading(images_urls, page_id, code, ph_link))
|
| 189 |
-
print(f'https://rentry.co/{page_id}', f'https://rentry.org/{page_id}')
|
| 190 |
-
return [ph_link, f'https://rentry.co/{page_id}', f'https://rentry.org/{page_id}'] if ph_link else [f'https://rentry.co/{page_id}', f'https://rentry.org/{page_id}']
|
| 191 |
else:
|
| 192 |
return await continue_optimizing_and_uploading(images_urls)
|
| 193 |
|
|
@@ -217,17 +318,13 @@ async def continue_optimizing_and_uploading(images_urls: list[str], page_id: str
|
|
| 217 |
content = '\n\n'.join([f'' for url in new_images_urls])
|
| 218 |
if ph_link:
|
| 219 |
try:
|
| 220 |
-
|
| 221 |
except Exception as e:
|
| 222 |
-
print(f'не удалось создать
|
| 223 |
if page_id and code:
|
| 224 |
try:
|
| 225 |
async with RentryClient('https://rentry.org') as client:
|
| 226 |
-
await client.edit_page(
|
| 227 |
-
text=content,
|
| 228 |
-
url=page_id,
|
| 229 |
-
edit_code=code,
|
| 230 |
-
)
|
| 231 |
except Exception as e:
|
| 232 |
print(f'не удалось создать страницу в rentry: {e}')
|
| 233 |
|
|
@@ -266,4 +363,3 @@ async def optimize_images_endpoint(image_urls: ImageURLs):
|
|
| 266 |
|
| 267 |
if __name__ == "__main__":
|
| 268 |
uvicorn_run(app, host='0.0.0.0', port=7860, timeout_keep_alive=90, log_level='info', use_colors=False)
|
| 269 |
-
|
|
|
|
| 1 |
+
from asyncio import create_subprocess_shell, create_task, gather, run, sleep
|
| 2 |
+
from json import dumps
|
| 3 |
from logging import ERROR, INFO, basicConfig, getLogger
|
| 4 |
from pathlib import Path
|
| 5 |
from shutil import rmtree
|
|
|
|
| 8 |
from uuid import uuid4
|
| 9 |
|
| 10 |
from PIL import Image
|
| 11 |
+
from aiorentry.client import Client as RentryClient
|
| 12 |
from fastapi import FastAPI, HTTPException
|
| 13 |
from fastapi.responses import PlainTextResponse
|
| 14 |
from httpx import AsyncClient, HTTPStatusError, RequestError
|
| 15 |
+
from lxml import html
|
| 16 |
+
from markdown import markdown
|
| 17 |
from pydantic import BaseModel, HttpUrl
|
|
|
|
|
|
|
| 18 |
from uvicorn import run as uvicorn_run
|
| 19 |
|
| 20 |
+
proxy_endpoint = 'https://telegraphprxver.vercel.app'
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
|
| 22 |
need_logging = False
|
| 23 |
|
|
|
|
| 38 |
]
|
| 39 |
|
| 40 |
|
| 41 |
+
class UserInfo:
|
| 42 |
+
def __init__(self, token: str, short_name: str, author_name: str, author_url: str, auth_link: str):
|
| 43 |
+
self.token = token
|
| 44 |
+
self.short_name = short_name
|
| 45 |
+
self.author_name = author_name
|
| 46 |
+
self.author_url = author_url
|
| 47 |
+
self.auth_link = auth_link
|
| 48 |
+
|
| 49 |
+
def get_token(self) -> str:
|
| 50 |
+
return self.token
|
| 51 |
+
|
| 52 |
+
def get_short_name(self) -> str:
|
| 53 |
+
return self.short_name
|
| 54 |
+
|
| 55 |
+
def get_author_name(self) -> str:
|
| 56 |
+
return self.author_name
|
| 57 |
+
|
| 58 |
+
def get_author_url(self) -> str:
|
| 59 |
+
return self.author_url
|
| 60 |
+
|
| 61 |
+
def get_auth_link(self) -> str:
|
| 62 |
+
return self.auth_link
|
| 63 |
+
|
| 64 |
+
def __repr__(self):
|
| 65 |
+
return f'UserAuthInfo(token={self.token}, short_name={self.short_name}, author_name={self.author_name}, author_url={self.author_url}, auth_link={self.auth_link})'
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
async def create_account(short_name: str, author_name: str, author_url: str) -> UserInfo:
|
| 69 |
+
params = {
|
| 70 |
+
'short_name': short_name,
|
| 71 |
+
'author_name': author_name,
|
| 72 |
+
'author_url': author_url
|
| 73 |
+
}
|
| 74 |
+
async with AsyncClient(verify=False, follow_redirects=True, timeout=30.0) as client:
|
| 75 |
+
response = await client.get(f'{proxy_endpoint}/createAccount', params=params)
|
| 76 |
+
json_response: dict = response.json()
|
| 77 |
+
if json_response.get('ok'):
|
| 78 |
+
result = json_response.get('result', {})
|
| 79 |
+
return UserInfo(result['access_token'], result['short_name'], result['author_name'], result['author_url'], result['auth_url'])
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
tgph_acc = run(create_account('prolapse', 'prolapse', ''))
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def md_to_dom(markdown_text: str) -> list[dict[str, str | list | dict | None]]:
|
| 86 |
+
def handle_heading(element) -> dict[str, str | list | dict | None]:
|
| 87 |
+
if element.tag == 'h1':
|
| 88 |
+
return {'tag': 'h3', 'children': parse_children(element)}
|
| 89 |
+
elif element.tag == 'h2':
|
| 90 |
+
return {'tag': 'h4', 'children': parse_children(element)}
|
| 91 |
+
else:
|
| 92 |
+
return {'tag': 'p', 'children': [{'tag': 'strong', 'children': parse_children(element)}]}
|
| 93 |
+
|
| 94 |
+
def handle_list(element) -> dict[str, str | list | dict | None]:
|
| 95 |
+
return {'tag': element.tag, 'children': [{'tag': 'li', 'children': parse_children(li)} for li in element.xpath('./li')]}
|
| 96 |
+
|
| 97 |
+
def handle_link(element) -> dict[str, str | list | dict | None]:
|
| 98 |
+
return {'tag': 'a', 'attrs': {'href': element.get('href')}, 'children': parse_children(element)}
|
| 99 |
+
|
| 100 |
+
def handle_media(element) -> dict[str, str | list | dict | None]:
|
| 101 |
+
return {'tag': element.tag, 'attrs': {'src': element.get('src')}}
|
| 102 |
+
|
| 103 |
+
def parse_children(element) -> list[str | dict[str, str | list | dict | None]]:
|
| 104 |
+
return [parse_element(child) if child.tag else child.strip() for child in element.iterchildren() if child.tag or (isinstance(child, str) and child.strip())]
|
| 105 |
+
|
| 106 |
+
def parse_element(element) -> dict[str, str | list | dict | None]:
|
| 107 |
+
handlers = {'h1': handle_heading, 'h2': handle_heading, 'h3': handle_heading, 'h4': handle_heading, 'h5': handle_heading, 'h6': handle_heading, 'ul': handle_list, 'ol': handle_list, 'a': handle_link, 'img': handle_media, 'iframe': handle_media}
|
| 108 |
+
handler = handlers.get(element.tag, lambda e: {'tag': e.tag, 'children': parse_children(e)})
|
| 109 |
+
return handler(element)
|
| 110 |
+
|
| 111 |
+
html_content = markdown(markdown_text, extensions=['extra', 'sane_lists'])
|
| 112 |
+
tree = html.fromstring(html_content)
|
| 113 |
+
return [parse_element(element) for element in tree.body]
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
async def tgph_create_page(token: str, title: str, markdown_text: str) -> str:
|
| 117 |
+
params = {
|
| 118 |
+
'access_token': token,
|
| 119 |
+
'title': title,
|
| 120 |
+
'content': dumps(md_to_dom(markdown_text)),
|
| 121 |
+
'return_content': False
|
| 122 |
+
}
|
| 123 |
+
async with AsyncClient(verify=False, follow_redirects=True, timeout=30.0) as client:
|
| 124 |
+
response = await client.get(f'{proxy_endpoint}/createPage', params=params)
|
| 125 |
+
json_response: dict = response.json()
|
| 126 |
+
if json_response.get('ok'):
|
| 127 |
+
result = json_response.get('result', {})
|
| 128 |
+
return result.get('path')
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
async def tgph_edit_page(token: str, page: str, title: str, markdown_text: str) -> str:
|
| 132 |
+
params = {
|
| 133 |
+
'access_token': token,
|
| 134 |
+
'path': page,
|
| 135 |
+
'title': title,
|
| 136 |
+
'content': dumps(md_to_dom(markdown_text)),
|
| 137 |
+
'return_content': False
|
| 138 |
+
}
|
| 139 |
+
async with AsyncClient(verify=False, follow_redirects=True, timeout=30.0) as client:
|
| 140 |
+
response = await client.get(f'{proxy_endpoint}/editPage', params=params)
|
| 141 |
+
json_response = response.json()
|
| 142 |
+
if json_response.get('ok'):
|
| 143 |
+
result = json_response.get('result', {})
|
| 144 |
+
return result.get('path')
|
| 145 |
+
|
| 146 |
+
|
| 147 |
async def download_png(url: str, folder: str, client: AsyncClient, retries: int = 5) -> Path:
|
| 148 |
# print(f'загрузка изображения: {url}')
|
| 149 |
for attempt in range(retries):
|
|
|
|
| 279 |
images_urls = [images_urls] if isinstance(images_urls, str) else images_urls
|
| 280 |
if convert:
|
| 281 |
try:
|
| 282 |
+
ph_link = tgph_create_page(tgph_acc.get_token(), 'DAll-E v3', '*изображения скоро появятся, обнови страницу...*')
|
| 283 |
except Exception as e:
|
| 284 |
print(f'не получилось создать страницу на телеграфе: {e}')
|
| 285 |
ph_link = None
|
|
|
|
| 287 |
page = await client.new_page('изображения скоро появятся, обнови страницу...')
|
| 288 |
page_id, code = page.url, page.edit_code
|
| 289 |
continue_task = create_task(continue_optimizing_and_uploading(images_urls, page_id, code, ph_link))
|
| 290 |
+
print(f'https://telegra.ph/{ph_link}', f'https://rentry.co/{page_id}', f'https://rentry.org/{page_id}')
|
| 291 |
+
return [f'https://telegra.ph/{ph_link}', f'https://rentry.co/{page_id}', f'https://rentry.org/{page_id}'] if ph_link else [f'https://rentry.co/{page_id}', f'https://rentry.org/{page_id}']
|
| 292 |
else:
|
| 293 |
return await continue_optimizing_and_uploading(images_urls)
|
| 294 |
|
|
|
|
| 318 |
content = '\n\n'.join([f'' for url in new_images_urls])
|
| 319 |
if ph_link:
|
| 320 |
try:
|
| 321 |
+
await tgph_edit_page(tgph_acc.get_token(), ph_link, 'DAll-E v3', content)
|
| 322 |
except Exception as e:
|
| 323 |
+
print(f'не удалось создать отредактировать на телеграфе: {e}')
|
| 324 |
if page_id and code:
|
| 325 |
try:
|
| 326 |
async with RentryClient('https://rentry.org') as client:
|
| 327 |
+
await client.edit_page(text=content, url=page_id, edit_code=code)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 328 |
except Exception as e:
|
| 329 |
print(f'не удалось создать страницу в rentry: {e}')
|
| 330 |
|
|
|
|
| 363 |
|
| 364 |
if __name__ == "__main__":
|
| 365 |
uvicorn_run(app, host='0.0.0.0', port=7860, timeout_keep_alive=90, log_level='info', use_colors=False)
|
|
|