Untitled
unknown
plain_text
2 years ago
2.6 kB
9
Indexable
from flask import Flask, request, jsonify
from PIL import Image
import os
from min_dalle import MinDalle
import torch
from imgurpython import ImgurClient
###########################################
model = MinDalle(
is_mega=False,
models_root='min-dalle-main/pretrained',
is_reusable=False,
is_verbose=True,
dtype=torch.float32
)
client_id = '2eb62070d6c69a3'
client_secret = 'da2ccfbdf29051fe858c0c3238b76f106d37f281'
client = ImgurClient(client_id, client_secret)
image_path = 'generated.png'
def ascii_from_image(image: Image.Image, size: int = 128) -> str:
gray_pixels = image.resize((size, int(0.55 * size))).convert('L').getdata()
chars = list('.,;/IOX')
chars = [chars[i * len(chars) // 256] for i in gray_pixels]
chars = [chars[i * size: (i + 1) * size] for i in range(size // 2)]
return '\n'.join(''.join(row) for row in chars)
def save_image(image: Image.Image, path: str):
if os.path.isdir(path):
path = os.path.join(path, 'generated.png')
elif not path.endswith('.png'):
path += '.png'
print("saving image to", path)
image.save(path)
return image
def generate_image(
text: str,
grid_size: int,
):
image = model.generate_image(
text,
-1,
grid_size,
top_k=128,
is_verbose=True
)
save_image(image, 'generated')
print(ascii_from_image(image, size=128))
def create_link():
data = client.upload_from_path(image_path)
image_url = data['link']
print('output:', image_url)
return image_url
############################################
app = Flask(__name__)
@app.route('/api', methods=['GET'])
def get_data():
# Code xử lý cho GET request
data = "Hello API"
return {'data': data}
@app.route('/api', methods=['POST'])
def post_api():
data = request.get_json() # Lấy dữ liệu từ request dưới dạng JSON
prompt = data.get('prompt') # Lấy giá trị trường 'name' từ dữ liệu JSON
grid_size = data.get('grid_size')
generate_image(prompt,grid_size)
img_link = create_link()
# Thực hiện xử lý với dữ liệu nhận được
# Ở đây chúng ta có thể lưu dữ liệu vào cơ sở dữ liệu hoặc thực hiện những tác vụ khác
# Trong ví dụ này, chúng ta chỉ in ra tên người dùng nhận được
return img_link
#
#
if __name__ == '__main__':
app.run()
Editor is loading...