Skip to content

Commit

Permalink
Massive refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
iwatkot authored Apr 19, 2024
2 parents ef20f93 + b8a4175 commit 993a224
Show file tree
Hide file tree
Showing 24 changed files with 900 additions and 792 deletions.
4 changes: 3 additions & 1 deletion .dockerignore
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,6 @@ README.md
requirements.txt
run.ps1
run.sh
maps4fs.zip
maps4fs.zip
.DS_Store
maps/
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,6 @@ bot.env
logs/
archives/
previews/
maps4fs.zip
maps4fs.zip
.DS_Store
maps/
17 changes: 14 additions & 3 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
@@ -1,11 +1,22 @@
{
"version": "0.2.0",
"configurations": [
{
"name": "Current File",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal",
"justMyCode": false,
"env": {
"PYTHONPATH": "${workspaceFolder}${pathSeparator}${env:PYTHONPATH}"
}
},
{
"name": "Windows Script",
"type": "python",
"request": "launch",
"program": "src/main.py",
"program": "maps4fs/ui.py",
"console": "integratedTerminal",
"justMyCode": true,
"env": {
Expand All @@ -29,7 +40,7 @@
"name": "Linux / Mac Script",
"type": "python",
"request": "launch",
"program": "src/main.py",
"program": "maps4fs/ui.py",
"console": "integratedTerminal",
"justMyCode": true,
"env": {
Expand All @@ -41,7 +52,7 @@
"name": "Linux / Mac Bot",
"type": "python",
"request": "launch",
"program": "src/bot.py",
"program": "bot/bot.py",
"console": "integratedTerminal",
"justMyCode": true,
"env": {
Expand Down
2 changes: 1 addition & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,4 @@ COPY . .

RUN pip install -r bot_requirements.txt

CMD ["python", "-u", "./src/bot.py"]
CMD ["python", "-u", "./bot/bot.py"]
38 changes: 24 additions & 14 deletions src/bot.py → bot/bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,18 @@
KeyboardButton,
ReplyKeyboardMarkup,
)
from bot_templates import Buttons, Messages
from dotenv import load_dotenv

import generate
from bot_templates import Buttons, Messages
from logger import Logger
import maps4fs as mfs

logger = Logger(__name__)
logger = mfs.Logger(__name__, level="DEBUG")
working_directory = os.getcwd()
map_template = os.path.join(working_directory, "data", "map-template.zip")
maps_directory = os.path.join(working_directory, "maps")
archives_directory = os.path.join(working_directory, "archives")
os.makedirs(maps_directory, exist_ok=True)
os.makedirs(archives_directory, exist_ok=True)
logger.info(f"Working directory: {working_directory}")
env_path = os.path.join(working_directory, "bot.env")
if os.path.exists(env_path):
Expand All @@ -25,7 +29,6 @@
if not token:
raise RuntimeError("No token provided.")

logger = Logger(__name__)
bot = Bot(token=token)
dp = Dispatcher(bot=bot)

Expand All @@ -52,22 +55,29 @@ def __init__(self, telegram_id: int, coordinates: tuple[float, float]):
self.telegram_id = telegram_id
self.timestamp = int(datetime.now().timestamp())
self.name = f"{self.telegram_id}_{self.timestamp}"
self.map_directory = os.path.join(maps_directory, self.name)
self.coordinates = coordinates
self.distance = None
self.dem_settings = None
self.max_height = None

def run(self) -> tuple[str, str]:
"""Runs the session and returns paths to the preview and the archive.
Returns:
tuple[str, str]: Paths to the preview and the archive.
"""
gm = generate.Map(
working_directory, self.coordinates, self.distance, self.dem_settings, logger, self.name
mp = mfs.Map(
self.coordinates,
self.distance,
self.map_directory,
blur_seed=5,
max_height=self.max_height,
map_template=map_template,
logger=logger,
)
gm.info_sequence()
preview_path = gm.preview()
archive_path = gm.pack()
mp.generate()
preview_path = mp.previews()[0]
archive_path = mp.pack(os.path.join(archives_directory, self.name))
return preview_path, archive_path


Expand Down Expand Up @@ -193,7 +203,7 @@ async def coordinates(message: types.Message) -> None:
telegram_id = message.from_user.id
sessions[telegram_id] = Session(telegram_id, (latitude, longitude))

sizes = generate.MAP_SIZES
sizes = mfs.globals.MAP_SIZES
indicators = ["🟢", "🟢", "🟡", "🔴"]
buttons = {}
# * Slice sizes because VPS can not handle large images.
Expand Down Expand Up @@ -224,7 +234,7 @@ async def map_size_callback(callback_query: types.CallbackQuery) -> None:
return
session.distance = int(map_size / 2)

heights = generate.MAX_HEIGHTS
heights = mfs.globals.MAX_HEIGHTS
buttons = {}
for height, description in heights.items():
buttons[f"max_height_{height}"] = description
Expand All @@ -251,7 +261,7 @@ async def max_height_callback(callback_query: types.CallbackQuery) -> None:
if not session:
return

session.dem_settings = generate.DemSettings(5, max_height)
session.max_height = max_height

await bot.send_message(
callback_query.from_user.id,
Expand Down
4 changes: 2 additions & 2 deletions src/bot_templates.py → bot/bot_templates.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,12 @@ class Messages(Enum):
ENTER_COORDINATES = (
"Enter the coordinates of the center of the map\."
"The coordinates are latitude and longitude separated by a comma\.\n\n"
"For example: `52\.520008, 13\.404954`\n\n"
"For example: `45\.2602, 19\.8086`\n\n"
"You can obtain them by right\-clicking on the map in [Google Maps](https://www.google.com/maps)\."
)
WRONG_COORDINATES = (
"Please enter the coordinates in the correct format\.\n\n"
"For example: `52\.520008, 13\.404954`\n\n"
"For example: `45\.2602, 19\.8086`\n\n"
)

SELECT_MAP_SIZE = (
Expand Down
3 changes: 2 additions & 1 deletion bot_requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@ opencv-python==4.9.0.80
osmnx==1.8.1
rasterio==1.3.9
python_dotenv==1.0.0
aiogram==2.25.1
aiogram==2.25.1
tqdm==4.66.2
5 changes: 0 additions & 5 deletions build.sh

This file was deleted.

2 changes: 2 additions & 0 deletions maps4fs/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
from maps4fs.generator.map import Map
from maps4fs.logger import Logger
6 changes: 6 additions & 0 deletions maps4fs/generator/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from maps4fs.generator.component import Component
from maps4fs.generator.config import Config
from maps4fs.generator.dem import DEM
from maps4fs.generator.texture import Texture

BaseComponents = [Config, Texture, DEM]
34 changes: 34 additions & 0 deletions maps4fs/generator/component.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
from typing import Any

import maps4fs as mfs


class Component:
"""Base class for all map generation components.
Args:
coordinates (tuple[float, float]): The latitude and longitude of the center of the map.
distance (int): The distance from the center to the edge of the map.
map_directory (str): The directory where the map files are stored.
logger (Any, optional): The logger to use. Must have at least three basic methods: debug,
info, warning. If not provided, default logging will be used.
"""

def __init__(
self,
coordinates: tuple[float, float],
distance: int,
map_directory: str,
logger: Any = None,
**kwargs,
):
self.coordinates = coordinates
self.distance = distance
self.map_directory = map_directory

if not logger:
logger = mfs.Logger(__name__, to_stdout=True, to_file=False)
self.logger = logger

def process(self):
raise NotImplementedError
47 changes: 47 additions & 0 deletions maps4fs/generator/config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import os
from typing import Any
from xml.etree import ElementTree as ET

from maps4fs.generator import Component


class Config(Component):
"""Component for map settings and configuration.
Args:
coordinates (tuple[float, float]): The latitude and longitude of the center of the map.
distance (int): The distance from the center to the edge of the map.
map_directory (str): The directory where the map files are stored.
logger (Any, optional): The logger to use. Must have at least three basic methods: debug,
info, warning. If not provided, default logging will be used.
"""

def __init__(
self,
coordinates: tuple[float, float],
distance: int,
map_directory: str,
logger: Any = None,
**kwargs,
):
super().__init__(coordinates, distance, map_directory, logger)
self._map_xml_path = os.path.join(self.map_directory, "maps", "map", "map.xml")

def process(self):
self._set_map_size()

def _set_map_size(self):
"""Edits map.xml file to set correct map size."""
if not os.path.isfile(self._map_xml_path):
self.logger.warning(f"Map XML file not found: {self._map_xml_path}.")
return
tree = ET.parse(self._map_xml_path)
self.logger.debug(f"Map XML file loaded from: {self._map_xml_path}.")
root = tree.getroot()
for map_elem in root.iter("map"):
width = height = str(self.distance * 2)
map_elem.set("width", width)
map_elem.set("height", height)
self.logger.debug(f"Map size set to {width}x{height} in Map XML file.")
tree.write(self._map_xml_path)
self.logger.debug(f"Map XML file saved to: {self._map_xml_path}.")
Loading

0 comments on commit 993a224

Please sign in to comment.