よみの暇つぶしブログ

話を始める前にFlaskとは? WSGI(Web Server Gateway Interface)というインターフェイスを使い、WEBアプリを柔軟に実装することを可能にするフレームワークです なぜ作ったのか 今まで、FastAPIなどでローカル環境でAPIを実装したり、Djangoで個人用のWEBアプリを実装したり、はあったのだが、外部に公開したサーバーサイドがきちんと組まれたWEBアプリはあまりなかった。 インターンに行きたいということもあり、実績として形に残したいので、今回デプロイすることにした。 また、今まで作っていたものは、自分向けに作っていたので、そのままでは公開はできない。せっかくなので、新規に作ることにした。 |
開発開始まずは、pipenvの構築。 これは言わずもがな、余計なトラブルは減らしたい。 コーディング サーバー側
from flask import Flask, request, render_template
import cv2
import numpy as np
from PIL import Image
import PIL
import os,uuid
from markupsafe import Markup
app = Flask(__name__)
def resize_aspect_ratio(image_path, horizontal_size):
# Open the image file
image = Image.open(image_path)
# Get the current width and height of the image
width, height = image.size
# Calculate the new height while maintaining the aspect ratio
new_height = int(height * (horizontal_size / width))
# Resize the image to the new dimensions
resized_image = image.resize((horizontal_size, new_height), PIL.Image.Resampling.LANCZOS)
filename = uuid.uuid4()
# Save the resized image to a file
resized_image.save(f'{filename}.png')
return f'{filename}.png'
def img2ascii(filename):
filename = resize_aspect_ratio(filename, 1080)
img = cv2.imread(filename)
# Convert the image to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Create a data group containing vectors and depth values
data_group = []
for i in range(0, gray.shape[0], 8):
for j in range(0, gray.shape[1], 8):
block = gray[i:i+8, j:j+8]
avg_brightness = np.mean(block)
data_group.append([i, j, avg_brightness])
# Convert the image to ASCII art using 10 types of symbols
ascii_art = ''
for i in range(0, gray.shape[0], 8):
for j in range(0, gray.shape[1], 8):
block = gray[i:i+8, j:j+8]
avg_brightness = np.mean(block)
if avg_brightness < 50:
ascii_art += ' '
elif avg_brightness < 100:
ascii_art += '.'
elif avg_brightness < 150:
ascii_art += '#'
elif avg_brightness < 200:
ascii_art += '*'
elif avg_brightness < 250:
ascii_art += '+'
else:
ascii_art += '@'
ascii_art += '<br>'
# Save the ASCII art to a file
# with open('ascii_art.txt', 'w') as f:
# f.write(ascii_art)
print(ascii_art)
return ascii_art
@app.route('/')
def index():
return render_template('index.html')
@app.route('/upload', methods=['POST'])
def upload_image():
try:
image_file = request.files['image']
filename = uuid.uuid4()
file_path = os.path.join("temp",f"{filename}.png")
image_file.save(file_path)
ascii_art = img2ascii(f"temp/{filename}.png")
except Exception as e:
ascii_art = f"Failed:{e}"
return render_template('index.html', resolution=Markup(f'{ascii_art}'))
if __name__ == '__main__':
app.run(debug=True)
フロント側
{{ resolution }}
IISにバインドし、HTTPSでアクセスできるようにする web.config
ホストにアクセスがあったとき、pipenv環境のPythonでFlaskとアスキーアート生成の処理をして、フロントのpreタグに表示。 普通にちゃんと動いてる。面白い。 https://app.xenfo.org
最後まで読んでくれてありがとう! |
2023/11/01
