Spaces:
Running
Running
import os | |
import requests | |
from flask import Flask, request, send_file | |
from selenium import webdriver | |
from selenium.common.exceptions import WebDriverException | |
from PIL import Image | |
from io import BytesIO | |
# フォントをダウンロードする関数 | |
def download_noto_sans_cjk(): | |
url = "https://noto-website-2.storage.googleapis.com/pkgs/NotoSansCJKjp-hinted.zip" | |
response = requests.get(url) | |
# フォントディレクトリを作成 | |
font_dir = "/usr/share/fonts/truetype/noto" | |
os.makedirs(font_dir, exist_ok=True) | |
# ダウンロードしたフォントを展開 | |
with open("/tmp/NotoSansCJKjp.zip", "wb") as f: | |
f.write(response.content) | |
os.system("unzip /tmp/NotoSansCJKjp.zip -d " + font_dir) | |
os.system("fc-cache -fv") # フォントキャッシュを更新 | |
# フォントのダウンロードとインストールを実行 | |
download_noto_sans_cjk() | |
app = Flask(__name__) | |
def take_screenshot(url, width=1080, height=720): | |
options = webdriver.ChromeOptions() | |
options.add_argument('--headless') | |
options.add_argument('--no-sandbox') | |
options.add_argument('--disable-dev-shm-usage') | |
try: | |
wd = webdriver.Chrome(options=options) | |
wd.set_window_size(width, height) | |
wd.get(url) | |
wd.implicitly_wait(10) | |
screenshot = wd.get_screenshot_as_png() | |
except WebDriverException: | |
# エラーが発生した場合、空の画像を返す | |
return Image.new('RGB', (1, 1)) | |
finally: | |
if wd: | |
wd.quit() | |
return Image.open(BytesIO(screenshot)) | |
def screenshot(): | |
url = request.args.get('url') | |
if not url: | |
return "URL parameter is required.", 400 | |
# パラメーターを取得 | |
screenw = request.args.get('screenw', default=None, type=int) | |
screenh = request.args.get('screenh', default=None, type=int) | |
# スクリーンショットを撮影 | |
original_image = take_screenshot(url) | |
# リサイズ処理 | |
if screenw and screenh: | |
# 両方のパラメーターが指定されている場合 | |
resized_image = original_image.resize((screenw, screenh)) | |
elif screenw: | |
# width のみが指定されている場合、高さを比率に基づいて自動計算 | |
aspect_ratio = original_image.height / original_image.width | |
resized_height = int(screenw * aspect_ratio) | |
resized_image = original_image.resize((screenw, resized_height)) | |
elif screenh: | |
# height のみが指定されている場合、幅を比率に基づいて自動計算 | |
aspect_ratio = original_image.width / original_image.height | |
resized_width = int(screenh * aspect_ratio) | |
resized_image = original_image.resize((resized_width, screenh)) | |
else: | |
# 両方のパラメーターが指定されていない場合 | |
resized_image = original_image | |
# 画像をメモリ上に保存してレスポンスとして返す | |
img_io = BytesIO() | |
resized_image.save(img_io, 'PNG') | |
img_io.seek(0) | |
return send_file(img_io, mimetype='image/png') | |
if __name__ == "__main__": | |
app.run(host="0.0.0.0", port=7860) | |