Skip to content

Instantly share code, notes, and snippets.

@darrenwiens
Last active July 2, 2024 18:28
Show Gist options
  • Save darrenwiens/802b11399ae993defe32e4837118e491 to your computer and use it in GitHub Desktop.
Save darrenwiens/802b11399ae993defe32e4837118e491 to your computer and use it in GitHub Desktop.
A FastAPI for generating ascii map tiles (png)
# MIT License
# Copyright (c) 2024 Darren Wiens
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from starlette.responses import StreamingResponse
import io
import numpy as np
import requests
from io import BytesIO
from PIL import Image, ImageDraw, ImageFont
TILE_KEY = "<YOUR_MAPTILER_KEY>"
app = FastAPI()
origins = ["*"]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
def get_char_from_brightness(brightness):
ascii_chars = "|%#*+=-:. "
length = len(ascii_chars)
unit = 256 / length
return ascii_chars[int(brightness / unit)]
def image_to_ascii(image, font_size, flatness):
image = image.convert("L")
width, height = image.size
aspect_ratio = height / width
new_height = int(aspect_ratio * font_size * flatness)
image = image.resize((font_size, new_height))
image_array = np.array(image)
ascii_image = "\n".join(
"".join(get_char_from_brightness(pixel) for pixel in row) for row in image_array
)
return ascii_image
def ascii_to_image(ascii_art):
try:
# source: https://fontlibrary.org/en/font/cmu-typewriter
# license: https://openfontlicense.org/
font = ImageFont.truetype(
"<PATH_TO_FONT>/cmu-typewriter/Typewriter/cmuntt.ttf",
64,
)
except IOError:
font = ImageFont.load_default()
font_width, font_height = font.getbbox("A")[2:]
lines = ascii_art.split("\n")
image_width = max(len(line) for line in lines) * font_width
image_height = len(lines) * font_height
image = Image.new("RGB", (image_width, image_height), "white")
draw = ImageDraw.Draw(image)
y = 0
for line in lines:
draw.text((0, y), line, fill="black", font=font)
y += font_height
image = image.resize([256, 256])
return image
@app.get("/{z}/{x}/{y}")
async def read_item(x: int, y: int, z: int, font_size: int = 10, flatness: float = 1.0):
url = f"https://api.maptiler.com/tiles/satellite-v2/{z}/{x}/{y}.jpg?key={TILE_KEY}"
response = requests.get(url)
bytes = BytesIO(response.content)
img = Image.open(bytes)
font_size = int((1 / font_size) * 256)
ascii_art = image_to_ascii(img, font_size, flatness)
img = ascii_to_image(ascii_art)
img_bytes = io.BytesIO()
img.save(img_bytes, "PNG")
img_bytes.seek(0)
headers = {
"Content-Type": "image/png",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "OPTIONS,GET",
"Access-Control-Allow-Headers": "Content-Type",
}
return StreamingResponse(img_bytes, headers=headers)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment