1
0
Fork 0

first commit

diego
diegoalrv 2023-08-29 00:18:41 -04:00
commit 3fc0f0e069
47 changed files with 2147 additions and 0 deletions

20
Dockerfile 100644
View File

@ -0,0 +1,20 @@
# Usa una imagen base de Python
FROM python:3.8
# Establece el directorio de trabajo en el contenedor
WORKDIR /app
# Copia el archivo requirements.txt al contenedor
COPY requirements.txt requirements.txt
# Instala las dependencias
RUN pip install -r requirements.txt
# Copia el archivo de configuración de Jupyter
COPY jupyter_notebook_config.py /root/.jupyter/
# Expone el puerto 8888 para Jupyter Notebook
EXPOSE 8888
# Ejecuta Jupyter Notebook cuando el contenedor se inicie
CMD ["jupyter", "notebook", "--ip=0.0.0.0", "--port=8888", "--no-browser", "--allow-root"]

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1,93 @@
Copyright 2017 The Barlow Project Authors (https://github.com/jpt/barlow)
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.

View File

@ -0,0 +1,28 @@
[
{
"direction": "I",
"distance": 1948.575483806973,
"epochTime": 1674650956,
"latitude": -33.43729782104492,
"licensePlate": "LJHX57",
"longitude": -70.52730560302734,
"realtime": true,
"route": "C",
"routeId": "C",
"timeLabel": "09:49",
"tripId": "C-I-L-005"
},
{
"direction": "R",
"distance": 1948.575483806973,
"epochTime": 1674650956,
"latitude": -33.43729782104492,
"licensePlate": "LJHA57",
"longitude": -70.52730560302734,
"realtime": true,
"route": "401",
"routeId": "401",
"timeLabel": "09:49",
"tripId": "401-I-L-005"
}
]

BIN
data/output.png 100644

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.4 KiB

View File

@ -0,0 +1,3 @@
c = get_config()
from notebook.auth import passwd
c.NotebookApp.password = passwd("...")

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,519 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import requests\n",
"import io\n",
"from io import BytesIO\n",
"from PIL import ImageDraw, ImageFont\n",
"from PIL import Image, ImageDraw, ImageFont\n",
"import matplotlib.pyplot as plt\n",
"import numpy as np"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"class MyDraw():\n",
" def __init__(self, height, width):\n",
" self.height = height\n",
" self.width = width\n",
" pass\n",
"\n",
" def save_image(self, filename):\n",
" self.image.save(filename)\n",
" pass\n",
"\n",
" def start_draw(self, background_color=None):\n",
" if background_color is None:\n",
" background_color = self.theme_params['background_color']\n",
"\n",
" self.image = Image.new(\"RGB\", (self.width, self.height), background_color)\n",
" self.draw = ImageDraw.Draw(self.image)\n",
" pass\n",
"\n",
" def add_image(self, obj, position):\n",
" image_to_add = obj.get_image() # Obtiene la imagen del objeto pasado como argumento\n",
" if image_to_add:\n",
" self.image.paste(image_to_add, position)\n",
" pass\n",
"\n",
" def get_draw(self):\n",
" return self.draw\n",
" \n",
" def get_image(self):\n",
" return self.image\n",
"\n",
" def set_params(self,params):\n",
" self.prms = params\n",
" pass\n",
"\n",
" def set_theme(self,mode='day'):\n",
" if(mode=='day'):\n",
" self.start_day_mode()\n",
" else:\n",
" self.start_night_mode()\n",
" pass\n",
"\n",
" def start_day_mode(self):\n",
" self.theme_params = {\n",
" 'background_color': 'white',\n",
" 'text_color': 'black',\n",
" 'poster_line_color': 'black',\n",
" }\n",
" pass\n",
"\n",
" def start_night_mode(self):\n",
" self.theme_params = {\n",
" 'background_color': 'black',\n",
" 'text_color': 'white',\n",
" 'poster_line_color': 'gray',\n",
" }\n",
" pass\n",
" \n",
" def load_barlow(self, font_size=None):\n",
" # Ruta a la fuente TTF personalizada\n",
" font_path = \"/app/data/Barlow-Medium.ttf\"\n",
" # Carga la fuente\n",
" if font_size is None:\n",
" self.font = ImageFont.truetype(font_path, self.prms['font_size'])\n",
" else:\n",
" self.font = ImageFont.truetype(font_path, font_size)\n",
" pass\n",
"\n",
" def preview(self):\n",
" plt.imshow(self.image)\n",
" plt.axis('off')\n",
" plt.show()\n",
"\n",
" def crop_image(self, top_cut, bottom_cut):\n",
" width, height = self.image.size\n",
" self.image = self.image.crop((0, top_cut, width, height - bottom_cut))\n",
" pass\n",
"\n",
" def resize_image(self, target_width=None, target_height=None):\n",
" \"\"\"\n",
" Ajusta el tamaño de la imagen mientras mantiene las proporciones.\n",
" \n",
" Args:\n",
" image (PIL.Image.Image): La imagen a redimensionar.\n",
" target_width (int, opcional): El ancho objetivo deseado.\n",
" target_height (int, opcional): La altura objetivo deseada.\n",
" \n",
" Returns:\n",
" PIL.Image.Image: La imagen redimensionada.\n",
" \"\"\"\n",
" width, height = self.image.size\n",
" aspect_ratio = width / height\n",
" \n",
" if target_width is None and target_height is None:\n",
" raise ValueError(\"Debes proporcionar al menos una de las dimensiones objetivo.\")\n",
" \n",
" if target_width is not None and target_height is None:\n",
" new_width = target_width\n",
" new_height = int(target_width / aspect_ratio)\n",
" elif target_width is None and target_height is not None:\n",
" new_width = int(target_height * aspect_ratio)\n",
" new_height = target_height\n",
" else:\n",
" new_width = target_width\n",
" new_height = target_height\n",
" \n",
" self.image = self.image.resize((new_width, new_height))\n",
" pass"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"class BusPoster(MyDraw):\n",
"\n",
" def start_draw(self):\n",
" return super().start_draw()\n",
"\n",
" def set_colors(self):\n",
" width_border = self.prms['width_border']\n",
" proportion = self.prms['proportion']\n",
" fill_color_l = self.prms['letter_background_color']\n",
" fill_color_n = self.prms['number_background_color']\n",
"\n",
"\n",
" self.draw.rounded_rectangle(\n",
" (0, 0, self.width-width_border, self.height-width_border),\n",
" fill=fill_color_l,\n",
" outline=self.theme_params['poster_line_color'],\n",
" width=width_border,\n",
" radius=5)\n",
" \n",
" self.draw.rounded_rectangle(\n",
" (0, 0, proportion*self.width-width_border, self.height-width_border),\n",
" fill=fill_color_n,\n",
" outline=self.theme_params['poster_line_color'],\n",
" width=width_border,\n",
" radius=5)\n",
" pass\n",
"\n",
" def set_bus_number(self, bus_number=\"11\"):\n",
" text_color = 'black'\n",
" width_border = self.prms['width_border']\n",
" text_bbox = self.font.getbbox(str(bus_number))\n",
" font_width, font_height = text_bbox[2] - text_bbox[0], text_bbox[3] - text_bbox[1]\n",
" offset_width = np.round((self.prms['proportion']*self.width-width_border)/2) - np.round(font_width/2)\n",
" text_position = (offset_width,0)\n",
" self.draw.text(\n",
" text_position,\n",
" bus_number,\n",
" fill=text_color,\n",
" font=self.font,\n",
" # align =\"center\"\n",
" )\n",
" pass\n",
"\n",
" def set_bus_letter(self, bus_letter=\"E\"):\n",
" proportion = self.prms['proportion']\n",
" width_border = self.prms['width_border']\n",
" text_color = 'white'\n",
" text_bbox = self.font.getbbox(str(bus_letter))\n",
" font_width, font_height = text_bbox[2] - text_bbox[0], text_bbox[3] - text_bbox[1]\n",
" offset_width = np.round((proportion*self.width-width_border)) + 0.75*np.round(font_width/2)\n",
" text_position = (offset_width,0)\n",
" self.draw.text(\n",
" text_position,\n",
" bus_letter,\n",
" fill=text_color,\n",
" font=self.font,\n",
" # align =\"center\"\n",
" )\n",
" pass"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"class TimeAnnouncement(MyDraw):\n",
"\n",
" def start_draw(self):\n",
" super().start_draw()\n",
" self.border = 1\n",
"\n",
" def set_background(self):\n",
" self.draw.rounded_rectangle(\n",
" (0, 0, self.width-0.5*self.border, self.height-0.5*self.border),\n",
" fill=\"#dcdcdc\",\n",
" outline=\"gray\",\n",
" width=self.border,\n",
" radius=1)\n",
" pass\n",
"\n",
" def set_base_text(self):\n",
" text = \"Tiempo aprox\"\n",
" text_color = self.theme_params['text_color']\n",
" self.load_barlow(font_size=11)\n",
" text_bbox = self.font.getbbox(text)\n",
" font_width, font_height = text_bbox[2] - text_bbox[0], text_bbox[3] - text_bbox[1]\n",
" # print(font_width, font_height)\n",
" offset_width = (np.round((self.width-self.border)) - np.round(font_width))/2\n",
" text_position = (offset_width,5)\n",
" # text_position = (0, 0)\n",
" self.draw.text(\n",
" text_position,\n",
" text,\n",
" fill=text_color,\n",
" font=self.font,\n",
" align =\"center\"\n",
" )\n",
" pass\n",
"\n",
" def set_min_max_text(self, min_time, max_time):\n",
"\n",
" text = \"Tiempo aprox\"\n",
" text_color = self.theme_params['text_color']\n",
" self.load_barlow(font_size=11)\n",
" text_bbox = self.font.getbbox(text)\n",
" base_font_width, base_font_height = text_bbox[2] - text_bbox[0], text_bbox[3] - text_bbox[1]\n",
"\n",
" if (int(max_time) <= 1):\n",
" text = f\"< 1 min\"\n",
" else:\n",
" text = f'{min_time} a {max_time} min'\n",
" \n",
" self.load_barlow(font_size=18)\n",
" text_bbox = self.font.getbbox(text)\n",
" font_width, font_height = text_bbox[2] - text_bbox[0], text_bbox[3] - text_bbox[1]\n",
" # print(font_width, font_height)\n",
" offset_width = (np.round((self.width-self.border)) - np.round(font_width))/2\n",
" offset_height = (np.round((self.height-self.border)) - np.round(base_font_height))/2\n",
" text_position = (offset_width,5+offset_height)\n",
" # text_position = (0, 0)\n",
" self.draw.text(\n",
" text_position,\n",
" text,\n",
" fill=text_color,\n",
" font=self.font,\n",
" align =\"center\"\n",
" )"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"class DistanceAnnouncement(MyDraw):\n",
"\n",
" def start_draw(self):\n",
" super().start_draw()\n",
" self.border = 1\n",
"\n",
" def set_background(self):\n",
" self.draw.rounded_rectangle(\n",
" (0, 0, self.width-0.5*self.border, self.height-0.5*self.border),\n",
" fill=\"#dcdcdc\",\n",
" outline=\"gray\",\n",
" width=self.border,\n",
" radius=1)\n",
" pass\n",
"\n",
" def set_base_text(self):\n",
" text = \"Distancia\"\n",
" text_color = self.theme_params['text_color']\n",
" self.load_barlow(font_size=11)\n",
" text_bbox = self.font.getbbox(text)\n",
" font_width, font_height = text_bbox[2] - text_bbox[0], text_bbox[3] - text_bbox[1]\n",
" # print(font_width, font_height)\n",
" offset_width = (np.round((self.width-self.border)) - np.round(font_width))/2\n",
" text_position = (offset_width,5)\n",
" # text_position = (0, 0)\n",
" self.draw.text(\n",
" text_position,\n",
" text,\n",
" fill=text_color,\n",
" font=self.font,\n",
" align =\"center\"\n",
" )\n",
" pass\n",
"\n",
" def set_distance_text(self, distance):\n",
"\n",
" text = \"Distancia\"\n",
" text_color = self.theme_params['text_color']\n",
" self.load_barlow(font_size=11)\n",
" text_bbox = self.font.getbbox(text)\n",
" base_font_width, base_font_height = text_bbox[2] - text_bbox[0], text_bbox[3] - text_bbox[1]\n",
"\n",
"\n",
" text = f'{distance} km'\n",
" self.load_barlow(font_size=18)\n",
" text_bbox = self.font.getbbox(text)\n",
" font_width, font_height = text_bbox[2] - text_bbox[0], text_bbox[3] - text_bbox[1]\n",
" # print(font_width, font_height)\n",
" offset_width = (np.round((self.width-self.border)) - np.round(font_width))/2\n",
" offset_height = (np.round((self.height-self.border)) - np.round(base_font_height))/2\n",
" text_position = (offset_width,5+offset_height)\n",
" # text_position = (0, 0)\n",
" self.draw.text(\n",
" text_position,\n",
" text,\n",
" fill=text_color,\n",
" font=self.font,\n",
" align =\"center\"\n",
" )"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"\n",
"class BusPlate():\n",
" def __init__(self, url=None) -> None:\n",
" if url is None:\n",
" self.url = \"https://matriculasdelmundo.com/gRCH1.php\"\n",
" pass\n",
"\n",
" def set_url(self, url):\n",
" self.url = url\n",
" pass\n",
"\n",
" def get_image(self):\n",
" if hasattr(self, 'image'):\n",
" return self.image\n",
" else:\n",
" print(\"Error: No se ha generado ninguna imagen aún.\")\n",
" return None\n",
"\n",
" def request_bus_plate(self, bus_plate=None):\n",
" if bus_plate is None:\n",
" self.bus_plate = \"AABB11\"\n",
" else:\n",
" self.bus_plate = bus_plate\n",
"\n",
" params = {\n",
" \"textRCH1\": self.bus_plate[0:2],\n",
" \"textRCH1A\": self.bus_plate[2:4],\n",
" \"textRCH1B\": self.bus_plate[4:],\n",
" \"textRCH1C\": \"\"\n",
" }\n",
"\n",
" self.response = requests.get(self.url, params=params)\n",
" pass\n",
"\n",
" def save_bus_plate_image(self):\n",
" if self.response.status_code == 200:\n",
" filename = f\"/app/data/output/plate_{self.bus_plate}.png\" \n",
" with open(filename, \"wb\") as f:\n",
" f.write(self.response.content)\n",
" print(f\"Imagen generada guardada como '{filename}'\")\n",
" else:\n",
" print(\"Error al guardar la imagen generada\")\n",
" pass\n",
"\n",
" def generate_image(self):\n",
" image_bytes = io.BytesIO(self.response.content)\n",
" self.image = Image.open(image_bytes)\n",
" self.image = self.image.convert(\"RGBA\") # Convertir a formato RGBA\n",
" pass\n",
"\n",
" def resize_image(self, new_size):\n",
" proportion = np.min([self.image.size[0]/new_size[0], self.image.size[1]/new_size[1]])\n",
" nx, ny = int(np.round(image.size[0]/proportion)), int(np.round(image.size[1]/proportion))\n",
" self.image = self.image.resize((nx, ny))\n",
" pass\n",
"\n",
" def preview(self):\n",
" plt.imshow(self.image)\n",
" plt.axis('off')\n",
" plt.show()\n",
" pass"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"class BusImage(MyDraw):\n",
" def __init__(self):\n",
" pass\n",
" \n",
" def load_image_from_url(self, url=None):\n",
" if(url is None):\n",
" # URL de la imagen en línea\n",
" url = \"https://img.freepik.com/iconos-gratis/autobus_318-574563.jpg\"\n",
"\n",
" # Descarga la imagen desde la URL\n",
" response = requests.get(url)\n",
" image_data = response.content\n",
" # Crea un objeto Image desde los datos descargados\n",
" self.image = Image.open(BytesIO(image_data))\n",
" # Crear una imagen en blanco del mismo tamaño que loaded_image con fondo blanco\n",
" background = Image.new(\"RGB\", self.image.size, self.theme_params['background_color'])\n",
"\n",
" # Pega la loaded_image en la imagen en blanco\n",
" background.paste(self.image, (0, 0), self.image)\n",
" \n",
" self.image = background\n",
"\n",
" # Calcula la posición para agregar la imagen cargada\n",
" image_position = (0, 0) # Cambia esto según tu diseño\n",
"\n",
" # Agrega la imagen a la imagen creada\n",
" self.image.paste(background, image_position)\n",
" pass"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"theme = 'night'\n",
"\n",
"panel_height, panel_width = 40, 80\n",
"n_panels = 3\n",
"full_panel = MyDraw(n_panels*panel_height, n_panels*panel_width)\n",
"full_panel.set_theme(theme)\n",
"full_panel.start_draw()\n",
"# full_panel.preview()\n",
"\n",
"bp = BusPlate()\n",
"plate = \"WXYZ88\"\n",
"bp.request_bus_plate(bus_plate=plate)\n",
"bp.generate_image()\n",
"bp.resize_image((40,80))\n",
"\n",
"dist_anmc = DistanceAnnouncement(50, 80)\n",
"dist_anmc.set_theme(theme)\n",
"dist_anmc.start_draw()\n",
"# dist_anmc.set_background()\n",
"dist_anmc.set_base_text()\n",
"dist_anmc.set_distance_text(distance=5)\n",
"\n",
"time_anmc = TimeAnnouncement(50, 80)\n",
"time_anmc.set_theme(theme)\n",
"time_anmc.start_draw()\n",
"# time_anmc.set_background()\n",
"time_anmc.set_base_text()\n",
"time_anmc.set_min_max_text(min_time=2, max_time=3)\n",
"\n",
"poster = BusPoster(30, 60)\n",
"poster.set_theme(theme)\n",
"poster.start_draw()\n",
"\n",
"poster_params = {\n",
" 'proportion': 0.6,\n",
" 'width_border': 1,\n",
" 'font_size': 25,\n",
" 'number_background_color': 'yellow',\n",
" 'letter_background_color': 'green',\n",
"}\n",
"\n",
"poster.set_params(poster_params)\n",
"poster.load_barlow()\n",
"poster.set_colors()\n",
"poster.set_bus_number(bus_number=\"20\")\n",
"poster.set_bus_letter(bus_letter=\"L\")\n",
"\n",
"bm = BusImage()\n",
"bm.set_theme(theme)\n",
"bm.load_image_from_url()\n",
"bm.crop_image(top_cut=165, bottom_cut=165)\n",
"bm.resize_image(target_width=80)\n",
"\n",
"full_panel.add_image(bp, (120, 80))\n",
"full_panel.add_image(dist_anmc, (90, 10))\n",
"full_panel.add_image(time_anmc, (160, 10))\n",
"full_panel.add_image(poster, (40, 80))\n",
"full_panel.add_image(bm, (5,20))\n",
"full_panel.get_image()\n",
"full_panel.save_image('/app/data/output.png')"
]
}
],
"metadata": {
"language_info": {
"name": "python"
},
"orig_nbformat": 4
},
"nbformat": 4,
"nbformat_minor": 2
}

5
requirements.txt 100644
View File

@ -0,0 +1,5 @@
matplotlib
seaborn
plotly
opencv-python
jupyter

View File

@ -0,0 +1,37 @@
import requests
import io
from io import BytesIO
from PIL import ImageDraw, ImageFont
from PIL import Image, ImageDraw, ImageFont
import matplotlib.pyplot as plt
import numpy as np
from MyDraw import MyDraw
class BusImage(MyDraw):
def __init__(self):
pass
def load_image_from_url(self, url=None):
if(url is None):
# URL de la imagen en línea
url = "https://img.freepik.com/iconos-gratis/autobus_318-574563.jpg"
# Descarga la imagen desde la URL
response = requests.get(url)
image_data = response.content
# Crea un objeto Image desde los datos descargados
self.image = Image.open(BytesIO(image_data))
# Crear una imagen en blanco del mismo tamaño que loaded_image con fondo blanco
background = Image.new("RGB", self.image.size, self.theme_params['background_color'])
# Pega la loaded_image en la imagen en blanco
background.paste(self.image, (0, 0), self.image)
self.image = background
# Calcula la posición para agregar la imagen cargada
image_position = (0, 0) # Cambia esto según tu diseño
# Agrega la imagen a la imagen creada
self.image.paste(background, image_position)
pass

View File

@ -0,0 +1,69 @@
import requests
import io
from io import BytesIO
from PIL import ImageDraw, ImageFont
from PIL import Image, ImageDraw, ImageFont
import matplotlib.pyplot as plt
import numpy as np
from MyDraw import MyDraw
class BusPlate(MyDraw):
def __init__(self, url=None) -> None:
if url is None:
self.url = "https://matriculasdelmundo.com/gRCH1.php"
pass
def set_url(self, url):
self.url = url
pass
def get_image(self):
if hasattr(self, 'image'):
return self.image
else:
print("Error: No se ha generado ninguna imagen aún.")
return None
def request_bus_plate(self, bus_plate=None):
if bus_plate is None:
self.bus_plate = "AABB11"
else:
self.bus_plate = bus_plate
params = {
"textRCH1": self.bus_plate[0:2],
"textRCH1A": self.bus_plate[2:4],
"textRCH1B": self.bus_plate[4:],
"textRCH1C": ""
}
self.response = requests.get(self.url, params=params)
pass
def save_bus_plate_image(self):
if self.response.status_code == 200:
filename = f"/app/data/output/plate_{self.bus_plate}.png"
with open(filename, "wb") as f:
f.write(self.response.content)
print(f"Imagen generada guardada como '{filename}'")
else:
print("Error al guardar la imagen generada")
pass
def generate_image(self):
image_bytes = io.BytesIO(self.response.content)
self.image = Image.open(image_bytes)
self.image = self.image.convert("RGBA") # Convertir a formato RGBA
pass
# def resize_image(self, new_size):
# proportion = np.min([self.image.size[0]/new_size[0], self.image.size[1]/new_size[1]])
# nx, ny = int(np.round(self.image.size[0]/proportion)), int(np.round(self.image.size[1]/proportion))
# self.image = self.image.resize((nx, ny))
# pass
def preview(self):
plt.imshow(self.image)
plt.axis('off')
plt.show()
pass

View File

@ -0,0 +1,68 @@
import requests
import io
from io import BytesIO
from PIL import ImageDraw, ImageFont
from PIL import Image, ImageDraw, ImageFont
import matplotlib.pyplot as plt
import numpy as np
from MyDraw import MyDraw
class BusPoster(MyDraw):
def start_draw(self):
return super().start_draw()
def set_colors(self):
width_border = self.prms['width_border']
proportion = self.prms['proportion']
fill_color_l = self.prms['letter_background_color']
fill_color_n = self.prms['number_background_color']
self.draw.rounded_rectangle(
(0, 0, self.width-width_border, self.height-width_border),
fill=fill_color_l,
outline=self.theme_params['poster_line_color'],
width=width_border,
radius=5)
self.draw.rounded_rectangle(
(0, 0, proportion*self.width-width_border, self.height-width_border),
fill=fill_color_n,
outline=self.theme_params['poster_line_color'],
width=width_border,
radius=5)
pass
def set_bus_number(self, bus_number="11"):
text_color = 'black'
width_border = self.prms['width_border']
text_bbox = self.font.getbbox(str(bus_number))
font_width, font_height = text_bbox[2] - text_bbox[0], text_bbox[3] - text_bbox[1]
offset_width = np.round((self.prms['proportion']*self.width-width_border)/2) - np.round(font_width/2)
text_position = (offset_width,0)
self.draw.text(
text_position,
bus_number,
fill=text_color,
font=self.font,
# align ="center"
)
pass
def set_bus_letter(self, bus_letter="E"):
proportion = self.prms['proportion']
width_border = self.prms['width_border']
text_color = 'white'
text_bbox = self.font.getbbox(str(bus_letter))
font_width, font_height = text_bbox[2] - text_bbox[0], text_bbox[3] - text_bbox[1]
offset_width = np.round((proportion*self.width-width_border)) + 0.75*np.round(font_width/2)
text_position = (offset_width,0)
self.draw.text(
text_position,
bus_letter,
fill=text_color,
font=self.font,
# align ="center"
)
pass

View File

@ -0,0 +1,68 @@
import requests
import io
from io import BytesIO
from PIL import ImageDraw, ImageFont
from PIL import Image, ImageDraw, ImageFont
import matplotlib.pyplot as plt
import numpy as np
from MyDraw import MyDraw
class DistanceAnnouncement(MyDraw):
def start_draw(self):
super().start_draw()
self.border = 1
def set_background(self):
self.draw.rounded_rectangle(
(0, 0, self.width-0.5*self.border, self.height-0.5*self.border),
fill="#dcdcdc",
outline="gray",
width=self.border,
radius=1)
pass
def set_base_text(self):
text = "Distancia"
text_color = self.theme_params['text_color']
self.load_barlow(font_size=11)
text_bbox = self.font.getbbox(text)
font_width, font_height = text_bbox[2] - text_bbox[0], text_bbox[3] - text_bbox[1]
# print(font_width, font_height)
offset_width = (np.round((self.width-self.border)) - np.round(font_width))/2
text_position = (offset_width,5)
# text_position = (0, 0)
self.draw.text(
text_position,
text,
fill=text_color,
font=self.font,
align ="center"
)
pass
def set_distance_text(self, distance):
text = "Distancia"
text_color = self.theme_params['text_color']
self.load_barlow(font_size=11)
text_bbox = self.font.getbbox(text)
base_font_width, base_font_height = text_bbox[2] - text_bbox[0], text_bbox[3] - text_bbox[1]
text = f'{distance} km'
self.load_barlow(font_size=18)
text_bbox = self.font.getbbox(text)
font_width, font_height = text_bbox[2] - text_bbox[0], text_bbox[3] - text_bbox[1]
# print(font_width, font_height)
offset_width = (np.round((self.width-self.border)) - np.round(font_width))/2
offset_height = (np.round((self.height-self.border)) - np.round(base_font_height))/2
text_position = (offset_width,5+offset_height)
# text_position = (0, 0)
self.draw.text(
text_position,
text,
fill=text_color,
font=self.font,
align ="center"
)

115
scripts/MyDraw.py 100644
View File

@ -0,0 +1,115 @@
import requests
import io
from io import BytesIO
from PIL import ImageDraw, ImageFont
from PIL import Image, ImageDraw, ImageFont
import matplotlib.pyplot as plt
import numpy as np
class MyDraw():
def __init__(self, height, width):
self.height = height
self.width = width
pass
def save_image(self, filename):
self.image.save(filename)
pass
def start_draw(self, background_color=None):
if background_color is None:
background_color = self.theme_params['background_color']
self.image = Image.new("RGB", (self.width, self.height), background_color)
self.draw = ImageDraw.Draw(self.image)
pass
def add_image(self, obj, position):
image_to_add = obj.get_image() # Obtiene la imagen del objeto pasado como argumento
if image_to_add:
self.image.paste(image_to_add, position)
pass
def get_draw(self):
return self.draw
def get_image(self):
return self.image
def set_params(self,params):
self.prms = params
pass
def set_theme(self,mode='day'):
if(mode=='day'):
self.start_day_mode()
else:
self.start_night_mode()
pass
def start_day_mode(self):
self.theme_params = {
'background_color': 'white',
'text_color': 'black',
'poster_line_color': 'black',
}
pass
def start_night_mode(self):
self.theme_params = {
'background_color': 'black',
'text_color': 'white',
'poster_line_color': 'gray',
}
pass
def load_barlow(self, font_size=None):
# Ruta a la fuente TTF personalizada
font_path = "/app/data/Barlow-Medium.ttf"
# Carga la fuente
if font_size is None:
self.font = ImageFont.truetype(font_path, self.prms['font_size'])
else:
self.font = ImageFont.truetype(font_path, font_size)
pass
def preview(self):
plt.imshow(self.image)
plt.axis('off')
plt.show()
def crop_image(self, top_cut, bottom_cut):
width, height = self.image.size
self.image = self.image.crop((0, top_cut, width, height - bottom_cut))
pass
def resize_image(self, target_width=None, target_height=None):
"""
Ajusta el tamaño de la imagen mientras mantiene las proporciones.
Args:
image (PIL.Image.Image): La imagen a redimensionar.
target_width (int, opcional): El ancho objetivo deseado.
target_height (int, opcional): La altura objetivo deseada.
Returns:
PIL.Image.Image: La imagen redimensionada.
"""
width, height = self.image.size
aspect_ratio = width / height
if target_width is None and target_height is None:
raise ValueError("Debes proporcionar al menos una de las dimensiones objetivo.")
if target_width is not None and target_height is None:
new_width = target_width
new_height = int(target_width / aspect_ratio)
elif target_width is None and target_height is not None:
new_width = int(target_height * aspect_ratio)
new_height = target_height
else:
new_width = target_width
new_height = target_height
self.image = self.image.resize((new_width, new_height))
pass

View File

@ -0,0 +1,73 @@
import requests
import io
from io import BytesIO
from PIL import ImageDraw, ImageFont
from PIL import Image, ImageDraw, ImageFont
import matplotlib.pyplot as plt
import numpy as np
from MyDraw import MyDraw
class TimeAnnouncement(MyDraw):
def start_draw(self):
super().start_draw()
self.border = 1
def set_background(self):
self.draw.rounded_rectangle(
(0, 0, self.width-0.5*self.border, self.height-0.5*self.border),
fill="#dcdcdc",
outline="gray",
width=self.border,
radius=1)
pass
def set_base_text(self):
text = "Tiempo aprox"
text_color = self.theme_params['text_color']
self.load_barlow(font_size=11)
text_bbox = self.font.getbbox(text)
font_width, font_height = text_bbox[2] - text_bbox[0], text_bbox[3] - text_bbox[1]
# print(font_width, font_height)
offset_width = (np.round((self.width-self.border)) - np.round(font_width))/2
text_position = (offset_width,5)
# text_position = (0, 0)
self.draw.text(
text_position,
text,
fill=text_color,
font=self.font,
align ="center"
)
pass
def set_min_max_text(self, min_time, max_time):
text = "Tiempo aprox"
text_color = self.theme_params['text_color']
self.load_barlow(font_size=11)
text_bbox = self.font.getbbox(text)
base_font_width, base_font_height = text_bbox[2] - text_bbox[0], text_bbox[3] - text_bbox[1]
if (int(max_time) <= 1):
text = "< 1 min"
elif (int(min_time) >= 10):
text = "> 10 min"
else:
text = f'{min_time} a {max_time} min'
self.load_barlow(font_size=18)
text_bbox = self.font.getbbox(text)
font_width, font_height = text_bbox[2] - text_bbox[0], text_bbox[3] - text_bbox[1]
# print(font_width, font_height)
offset_width = (np.round((self.width-self.border)) - np.round(font_width))/2
offset_height = (np.round((self.height-self.border)) - np.round(base_font_height))/2
text_position = (offset_width,5+offset_height)
# text_position = (0, 0)
self.draw.text(
text_position,
text,
fill=text_color,
font=self.font,
align ="center"
)

View File

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

136
scripts/main.py 100644
View File

@ -0,0 +1,136 @@
from MyDraw import MyDraw
from BusPoster import BusPoster
from TimeAnnouncement import TimeAnnouncement
from DistanceAnnouncement import DistanceAnnouncement
from BusPlate import BusPlate
from BusImage import BusImage
import numpy as np
from datetime import datetime, timedelta
def aprox(n):
return int(np.round(n))
def load_data():
data = {
"direction": "R",
"distance": 1948.575483806973,
"epochTime": 1674650956,
"latitude": -33.43729782104492,
"licensePlate": "LJHA57",
"longitude": -70.52730560302734,
"realtime": True,
"route": "401",
"routeId": "401",
"timeLabel": "09:49",
"tripId": "401-I-L-005"
}
return data
def approx_km(data):
distance_meters = data["distance"]
distance_km = distance_meters / 100 # Convert meters to kilometers
approx_km = int(np.round(distance_km)) # Take only the integer part of the distance in kilometers
approx_km = approx_km/10.0
return approx_km
def calc_remaining_time(data):
arrival_time = data["timeLabel"]
target_time = datetime.strptime(arrival_time, "%H:%M").time()
current_time = datetime.now().time()
if current_time < target_time:
remaining_time = datetime.combine(datetime.today(), target_time) - datetime.combine(datetime.today(), current_time)
else:
remaining_time = datetime.combine(datetime.today() + timedelta(days=1), target_time) - datetime.combine(datetime.today(), current_time)
remaining_minutes = int(remaining_time.total_seconds() // 60)
return remaining_minutes
def obtain_min_max_time(remaining_time):
if remaining_time == 1:
return 0, 1
elif remaining_time == 2:
return 1, 2
elif 2 <= remaining_time <= 5:
return 2, 5
elif remaining_time > 5 and remaining_time <= 7:
return 5, 7
elif remaining_time > 7 and remaining_time <= 10:
return 7, 10
else:
return 10, remaining_time
data = load_data()
distance = approx_km(data)
remaining_time = calc_remaining_time(data)
min_time, max_time = obtain_min_max_time(remaining_time)
theme = 'day'
# panel_height, panel_width = 40, 80
# n_panels = 3
# height, width = n_panels*panel_height, n_panels*panel_width
height, width = 120, 240
full_panel = MyDraw(height=height, width=width)
full_panel.set_theme(theme)
full_panel.start_draw()
# full_panel.preview()
bp = BusPlate()
plate = data["licensePlate"]
bp.request_bus_plate(bus_plate=plate)
bp.generate_image()
bp.resize_image(target_height=aprox((3/10)*height))
dist_anmc = DistanceAnnouncement(aprox((2/5)*height), aprox((1/3)*width))
dist_anmc.set_theme(theme)
dist_anmc.start_draw()
# dist_anmc.set_background()
dist_anmc.set_base_text()
dist_anmc.set_distance_text(distance=distance)
time_anmc = TimeAnnouncement(aprox((2/5)*height), aprox((1/3)*width))
time_anmc.set_theme(theme)
time_anmc.start_draw()
# time_anmc.set_background()
time_anmc.set_base_text()
time_anmc.set_min_max_text(min_time=min_time, max_time=max_time)
poster = BusPoster(aprox((1/4)*height), aprox((1/4)*width))
poster.set_theme(theme)
poster.start_draw()
poster_params = {
'proportion': 0.6,
'width_border': 1,
'font_size': 25,
'number_background_color': 'yellow',
'letter_background_color': 'green',
}
poster.set_params(poster_params)
poster.load_barlow()
poster.set_colors()
poster.set_bus_number(bus_number=data["route"])
poster.set_bus_letter(bus_letter=data["direction"])
bm = BusImage()
bm.set_theme(theme)
bm.load_image_from_url()
bm.crop_image(top_cut=165, bottom_cut=165)
bm.resize_image(target_width=aprox((1/3)*width))
full_panel.add_image(bp, (aprox(0.5*width), aprox((2/3)*height)))
full_panel.add_image(dist_anmc, (aprox((3/8)*width), aprox(0.1*height)))
full_panel.add_image(time_anmc, (aprox((2/3)*width), aprox(0.1*height)))
full_panel.add_image(poster, (aprox((1/6)*width), aprox((2/3)*height)))
full_panel.add_image(bm, (aprox(0.02*width),aprox((1/6)*height)))
full_panel.get_image()
full_panel.save_image('/app/data/output.png')