initial commit

This commit is contained in:
2025-10-26 23:39:49 -05:00
commit 5fb0909e8d
120 changed files with 11279 additions and 0 deletions

86
.dockerignore Normal file
View File

@@ -0,0 +1,86 @@
# Git
.git
.gitignore
# Python
__pycache__
*.pyc
*.pyo
*.pyd
.Python
pip-log.txt
pip-delete-this-directory.txt
.tox
.pytest_cache
nosetests.xml
.cache
# Virtual environments
venv/
env/
ENV/
.venv/
# IDEs
.vscode/
.idea/
*.swp
*.swo
# OS
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
ehthumbs.db
Thumbs.db
# Tests and coverage (not needed in production)
tests/
htmlcov/
.coverage
.coverage.*
coverage.xml
*.cover
# Development scripts (not needed in production)
scripts/
# Docker files
Dockerfile
docker-compose.yml
docker-compose.dev.yml
.dockerignore
# Documentation (optional in production)
README.md
CHANGELOG.md
LICENSE
docs/
# Development dependencies and tools
requirements-dev.txt
Makefile
.flake8
pytest.ini
pyproject.toml
# Backup files
*.backup
*.bak
data/*.backup
# Environment files (use environment variables in Docker)
.env*
# Temporary files and logs
*.tmp
*.temp
temp/
tmp/
logs/
*.log
# Version files
_version.py

140
.env.sample Normal file
View File

@@ -0,0 +1,140 @@
# ====================================
# CONFIGURACIÓN DE ENTORNO - BALOTARIO LICENCIA A-I
# ====================================
# Copia este archivo como .env y ajusta los valores según tu entorno
# ====================================
# CONFIGURACIÓN DE FLASK
# ====================================
# Clave secreta para Flask (CAMBIAR EN PRODUCCIÓN)
# Genera una nueva con: python -c "import secrets; print(secrets.token_hex(32))"
SECRET_KEY=balotario_secret_key_2024_super_secure
# Entorno de ejecución (development, production, testing)
FLASK_ENV=development
# Configuración específica de Flask
FLASK_CONFIG=development
# Modo debug (true/false)
FLASK_DEBUG=true
# ====================================
# CONFIGURACIÓN DE LA APLICACIÓN
# ====================================
# Puerto de la aplicación (por defecto: 5000)
PORT=5000
# Host de la aplicación (por defecto: 0.0.0.0 para Docker, 127.0.0.1 para local)
HOST=127.0.0.1
# ====================================
# CONFIGURACIÓN DE DOCKER
# ====================================
# Indica si la aplicación se ejecuta en Docker
DOCKER_CONTAINER=false
# ====================================
# CONFIGURACIÓN DE BASE DE DATOS (FUTURO)
# ====================================
# Descomenta y configura si planeas agregar una base de datos
# DATABASE_URL=sqlite:///balotario.db
# DB_HOST=localhost
# DB_PORT=5432
# DB_NAME=balotario
# DB_USER=balotario_user
# DB_PASSWORD=secure_password
# ====================================
# CONFIGURACIÓN DE LOGGING
# ====================================
# Nivel de logging (DEBUG, INFO, WARNING, ERROR, CRITICAL)
LOG_LEVEL=INFO
# Archivo de logs (opcional)
# LOG_FILE=logs/balotario.log
# ====================================
# CONFIGURACIÓN DE SEGURIDAD
# ====================================
# Configuración CORS (si es necesario)
# CORS_ORIGINS=http://localhost:3000,http://localhost:8080
# Configuración de rate limiting (si se implementa)
# RATE_LIMIT_ENABLED=true
# RATE_LIMIT_REQUESTS=100
# RATE_LIMIT_WINDOW=3600
# ====================================
# CONFIGURACIÓN DE CACHE (FUTURO)
# ====================================
# Descomenta si planeas agregar Redis u otro sistema de cache
# REDIS_URL=redis://localhost:6379/0
# CACHE_TYPE=redis
# CACHE_DEFAULT_TIMEOUT=300
# ====================================
# CONFIGURACIÓN DE EMAIL (FUTURO)
# ====================================
# Descomenta si planeas agregar funcionalidad de email
# MAIL_SERVER=smtp.gmail.com
# MAIL_PORT=587
# MAIL_USE_TLS=true
# MAIL_USERNAME=tu-email@gmail.com
# MAIL_PASSWORD=tu-password-de-aplicacion
# ====================================
# CONFIGURACIÓN DE ANALYTICS (FUTURO)
# ====================================
# Descomenta si planeas agregar Google Analytics u otros
# GOOGLE_ANALYTICS_ID=GA_MEASUREMENT_ID
# ENABLE_ANALYTICS=false
# ====================================
# CONFIGURACIÓN DE DESARROLLO
# ====================================
# Recargar automáticamente en cambios (solo desarrollo)
AUTO_RELOAD=true
# Mostrar errores detallados (solo desarrollo)
SHOW_DEBUG_TOOLBAR=false
# ====================================
# CONFIGURACIÓN DE PRODUCCIÓN
# ====================================
# Variables específicas para entorno de producción
# Dominio de la aplicación
# DOMAIN=tu-dominio.com
# Configuración SSL
# SSL_ENABLED=false
# SSL_CERT_PATH=/path/to/cert.pem
# SSL_KEY_PATH=/path/to/key.pem
# ====================================
# CONFIGURACIÓN DE MONITOREO (FUTURO)
# ====================================
# Descomenta si planeas agregar monitoreo
# SENTRY_DSN=https://your-sentry-dsn
# ENABLE_MONITORING=false
# ====================================
# NOTAS IMPORTANTES
# ====================================
# 1. NUNCA subas el archivo .env al repositorio
# 2. Cambia SECRET_KEY en producción
# 3. Usa valores seguros para passwords
# 4. Revisa que .env esté en .gitignore
# 5. Para Docker, algunas variables se sobrescriben en docker-compose.yml

View File

@@ -0,0 +1,47 @@
name: release
on:
schedule:
- cron: '0 10 * * *'
push:
branches:
- main
jobs:
release-default:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Set up QEMU
uses: docker/setup-qemu-action@v3
- name: Set up Docker BuildX
uses: docker/setup-buildx-action@v3
- name: Login to DockerHub
uses: docker/login-action@v3
with:
username: ${{ secrets.DOCKER_REGISTRY_USER }}
password: ${{ secrets.DOCKER_REGISTRY_PASSWORD }}
- name: Check syntax docker
uses: hadolint/hadolint-action@v3.1.0
with:
dockerfile: Dockerfile
ignore: DL3013,DL3008,DL4006
- name: Push Docker image
uses: docker/build-push-action@v6
with:
context: .
file: Dockerfile
platforms: |
linux/amd64
linux/arm64
push: true
no-cache: false
tags: |
${{ secrets.DOCKER_REGISTRY_USER}}/driving-academy:${{ github.sha }}
${{ secrets.DOCKER_REGISTRY_USER}}/driving-academy:latest

187
.gitignore vendored Normal file
View File

@@ -0,0 +1,187 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
pip-wheel-metadata/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
.python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# PEP 582; used by e.g. github.com/David-OConnor/pyflow
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# IDEs
.vscode/
.idea/
*.swp
*.swo
*~
# OS generated files
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
ehthumbs.db
Thumbs.db
# Logs
*.log
logs/
# Temporary files
*.tmp
*.temp
temp/
tmp/
# Application specific
*.db
*.sqlite
*.sqlite3
session_data/
uploads/
# Backup files
*.backup
*.bak
data/*.backup
# Environment files (keep .env.sample)
.env
.env.local
.env.development
.env.production
# Coverage reports
htmlcov/
.coverage
coverage.xml
*.cover
# Development tools
.flake8
pytest.ini
pyproject.toml
# Version files
_version.py

44
Dockerfile Normal file
View File

@@ -0,0 +1,44 @@
# Use official Python Alpine base image
FROM python:3.11-alpine
# Maintainer information
LABEL maintainer="Balotario Licencia A-I"
LABEL description="Interactive web application to study driving license test questions"
LABEL version="1.0.0"
# Set working directory
WORKDIR /app
# Update system packages for security (CVEs)
RUN apk update && apk upgrade --no-cache && \
rm -rf /var/cache/apk/*
# Copy dependency files
COPY requirements.txt .
# Install Python dependencies
RUN pip install --no-cache-dir --upgrade pip && \
pip install --no-cache-dir -r requirements.txt
# Copy application code
COPY . .
# Create non-root user for security
RUN adduser -D -s /bin/sh app && \
chown -R app:app /app
USER app
# Expose port
EXPOSE 5000
# Environment variables
ENV FLASK_APP=app.py
ENV FLASK_ENV=production
ENV PYTHONPATH=/app
# Docker health check command
HEALTHCHECK --interval=30s --timeout=30s --start-period=5s --retries=3 \
CMD wget --no-verbose --tries=1 --spider http://localhost:5000/ || exit 1
# Default command
CMD ["python", "run.py"]

674
LICENSE Normal file
View File

@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

83
Makefile Normal file
View File

@@ -0,0 +1,83 @@
# Makefile for Flask Balotario Application
# Provides convenient commands for development and deployment
.PHONY: help install install-dev install-test clean test lint format run docker-build docker-run
# Default target
help:
@echo "Available commands:"
@echo " install - Install production dependencies"
@echo " install-dev - Install development dependencies"
@echo " clean - Clean up cache and temporary files"
@echo " test - Run tests with coverage"
@echo " lint - Run linting checks"
@echo " format - Format code with black and isort"
@echo " security - Run security checks"
@echo " run - Run development server"
@echo " run-prod - Run production server with gunicorn"
@echo " docker-build - Build Docker image"
@echo " docker-run - Run Docker container"
@echo " download-images - Download all images locally"
@echo " verify-images - Verify all images are available"
# Installation targets
install:
pip install -r requirements.txt
install-dev:
pip install -r requirements-dev.txt
# Development targets
clean:
find . -type f -name "*.pyc" -delete
find . -type d -name "__pycache__" -delete
find . -type d -name "*.egg-info" -exec rm -rf {} +
rm -rf .pytest_cache
rm -rf .coverage
rm -rf htmlcov/
test:
pytest --cov=. --cov-report=html --cov-report=term-missing
lint:
flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics
flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics
format:
black .
isort .
security:
bandit -r . -x tests/
safety check
# Server targets
run:
python app.py
run-prod:
gunicorn --bind 0.0.0.0:5000 --workers 4 app:app
# Docker targets
docker-build:
docker build -t driving-academy .
docker-run:
docker run -p 5000:5000 driving-academy
# Image management
download-images:
python scripts/download_images.py
verify-images:
python scripts/verify_images.py
# Development setup (complete environment)
setup-dev: install-dev download-images
@echo "Development environment ready!"
@echo "Run 'make run' to start the development server"
# Production setup
setup-prod: install
@echo "Production environment ready!"
@echo "Run 'make run-prod' to start the production server"

273
README.md Normal file
View File

@@ -0,0 +1,273 @@
# 🚗 Balotario Licencia Clase A - Categoría I
Una aplicación web interactiva desarrollada con Flask para estudiar las preguntas del balotario oficial de la licencia de conducir Clase A - Categoría I del Perú.
## ✨ Características
- **📚 Modo Estudio**: Revisa todas las preguntas con sus respuestas correctas
- **🏋️ Modo Práctica**: Practica con preguntas aleatorias y retroalimentación inmediata
- **📝 Examen Simulado**: Simula el examen real con tiempo limitado
- **📊 Estadísticas**: Seguimiento de tu progreso y precisión
- **🖼️ Imágenes**: Incluye todas las señales de tránsito oficiales
- **📱 Responsive**: Funciona perfectamente en móviles y tablets
- **🎨 Interfaz Moderna**: Diseño atractivo y fácil de usar
## 🚀 Instalación y Configuración
### 🐳 Opción 1: Docker (Recomendado)
```bash
# Clonar el repositorio
git clone <url-del-repositorio>
cd balotario-licencia-a1
# Opción A: Docker Compose (más fácil)
docker-compose up -d
# Opción B: Docker simple
docker build -t balotario .
docker run -p 5000:5000 balotario
# Opción C: Script de utilidades
./scripts/docker.sh compose-up
```
### 🐍 Opción 2: Instalación Local
#### Prerrequisitos
- Python 3.7 o superior
- pip (gestor de paquetes de Python)
#### Pasos de instalación
1. **Clona o descarga el proyecto**
```bash
# Si tienes git instalado
git clone <url-del-repositorio>
cd balotario-licencia-a1
```
2. **Configura las variables de entorno**
```bash
# Linux/Mac
./scripts/env-setup.sh dev
# Windows
scripts\env-setup.bat dev
# O manualmente
cp .env.sample .env
# Edita .env con tus valores
```
3. **Instala las dependencias**
```bash
pip install -r requirements.txt
```
4. **Ejecuta la aplicación**
```bash
python run.py
```
5. **Abre tu navegador**
- Ve a: `http://localhost:5000`
- ¡Listo para estudiar! 🎉
### 🌐 Acceso
- **Docker**: `http://localhost:5000` (o `http://localhost` con Nginx)
- **Local**: `http://localhost:5000`
## ⚙️ Configuración de Variables de Entorno
### 🔧 Configuración Rápida
```bash
# Desarrollo local
./scripts/env-setup.sh dev
# Producción
./scripts/env-setup.sh prod
# Docker
./scripts/env-setup.sh docker
```
### 📋 Variables Principales
| Variable | Descripción | Por Defecto |
|----------|-------------|-------------|
| `SECRET_KEY` | Clave secreta de Flask | `balotario_secret_key_2024_super_secure` |
| `FLASK_ENV` | Entorno de ejecución | `development` |
| `FLASK_DEBUG` | Modo debug | `true` |
| `HOST` | Dirección del servidor | `127.0.0.1` |
| `PORT` | Puerto del servidor | `5000` |
### 📚 Documentación Completa
Ver [docs/ENVIRONMENT.md](docs/ENVIRONMENT.md) para configuración avanzada.
## 📖 Cómo usar la aplicación
### 🏠 Página Principal
- Resumen de estadísticas
- Acceso rápido a todos los modos
- Información del balotario
### 📚 Modo Estudio
- Navega por todas las preguntas secuencialmente
- Filtra por rango de preguntas
- Muestra/oculta respuestas correctas
- Navegación con teclado (flechas y espacio)
### 🏋️ Modo Práctica
- Selecciona el número de preguntas (10, 20, 30, 50)
- Preguntas aleatorias
- Retroalimentación inmediata
- Estadísticas de sesión
### 📝 Examen Simulado
- Configura número de preguntas y tiempo límite
- Cronómetro en tiempo real
- Navegador de preguntas
- Calificación final con porcentaje de aprobación
## 🛠️ Estructura del Proyecto
```
balotario-licencia-a1/
├── app.py # Aplicación Flask principal
├── run_app.py # Script de inicio mejorado
├── config.py # Configuración modular
├── requirements.txt # Dependencias Python
├── data/ # Datos y contenido
│ ├── balotario_clase_a_cat_I.md # 200 preguntas oficiales
│ ├── README.md # Documentación del contenido
│ └── backup/ # Respaldos del contenido
├── templates/ # Templates HTML
│ ├── base.html # Template base
│ ├── index.html # Página principal
│ ├── study.html # Modo estudio
│ ├── practice.html # Modo práctica
│ └── exam.html # Examen simulado
├── static/ # Archivos estáticos
│ ├── css/
│ │ └── custom.css # Estilos personalizados
│ └── js/
│ └── app.js # JavaScript principal
├── test/ # Tests y pruebas
│ ├── README.md # Documentación de tests
│ ├── test_parser.py # Tests del parser
│ ├── test_sounds.html # Tests de sonidos
│ └── ... # Otros tests
├── scripts/ # Scripts de utilidades
│ └── dev.py # Herramientas de desarrollo
├── CHANGELOG.md # Registro de cambios
├── INSTALL.md # Guía de instalación
└── README.md # Esta documentación
```
## 🎯 Funcionalidades Técnicas
### Backend (Flask)
- **API RESTful** para obtener preguntas
- **Sesiones** para estadísticas persistentes
- **Parser inteligente** del markdown con regex
- **Filtros dinámicos** por rango y modo
### Frontend
- **Bootstrap 5** para diseño responsive
- **jQuery** para interactividad
- **Font Awesome** para iconos
- **Animaciones CSS** para mejor UX
- **LocalStorage** para persistencia del lado cliente
### Características Especiales
- **Navegación por teclado** en modo estudio
- **Cronómetro visual** en examen simulado
- **Navegador de preguntas** con estado visual
- **Estadísticas en tiempo real**
- **Confirmación antes de finalizar examen**
## 📊 Datos del Balotario
- **200 preguntas** oficiales
- **Respuestas correctas** marcadas con ✅
- **Imágenes de señales** de tránsito incluidas
- **Categorías**: Reglamentarias, preventivas, informativas
- **Temas**: Normas de tránsito, señalización, seguridad vial
## 🔧 Personalización
### Modificar preguntas
Edita el archivo `balotario_clase_a_cat_I.md` siguiendo el formato:
```markdown
### [NÚMERO]
[PREGUNTA]
a) [OPCIÓN A]
b) [OPCIÓN B]
c) [OPCIÓN C]
✅ d) [OPCIÓN CORRECTA]
```
### Cambiar estilos
Los estilos CSS están en `templates/base.html` dentro de la etiqueta `<style>`.
### Agregar funcionalidades
Modifica `app.py` para agregar nuevas rutas o funcionalidades.
## 🐛 Solución de Problemas
### La aplicación no inicia
- Verifica que Python esté instalado: `python --version`
- Instala las dependencias: `pip install -r requirements.txt`
- Verifica que el puerto 5000 esté libre
### Las preguntas no se cargan
- Verifica que el archivo `balotario_clase_a_cat_I.md` esté presente
- Revisa la consola para errores de parsing
### Problemas con imágenes
- Las imágenes se cargan desde URLs externas
- Verifica tu conexión a internet
## 📝 Licencia
Este proyecto está licenciado bajo la **GNU General Public License v3.0** (GPL-3.0).
### ¿Qué significa esto?
-**Libertad de uso**: Puedes usar este software para cualquier propósito
-**Libertad de estudio**: Puedes estudiar cómo funciona y modificarlo
-**Libertad de distribución**: Puedes redistribuir copias para ayudar a otros
-**Libertad de mejora**: Puedes mejorar el programa y publicar las mejoras
### Condiciones importantes
- 📋 **Código abierto**: Si distribuyes versiones modificadas, debes mantener el código fuente disponible
- 📋 **Misma licencia**: Las obras derivadas deben usar la misma licencia GPL-3.0
- 📋 **Atribución**: Debes mantener los avisos de copyright y licencia originales
### Contenido educativo
El contenido del balotario está basado en las preguntas oficiales del **MTC (Ministerio de Transportes y Comunicaciones) del Perú** y es de dominio público para fines educativos.
Para más detalles, consulta el archivo [LICENSE](LICENSE) en este repositorio.
## 🤝 Contribuciones
¡Las contribuciones son bienvenidas! Puedes:
- Reportar bugs
- Sugerir nuevas funcionalidades
- Mejorar la documentación
- Optimizar el código
## 📞 Soporte
Si tienes problemas o preguntas:
1. Revisa este README
2. Verifica los logs de la aplicación
3. Busca en los issues del repositorio
---
**¡Buena suerte en tu examen de manejo! 🚗💨**

192
app.py Normal file
View File

@@ -0,0 +1,192 @@
from flask import Flask, render_template, request, jsonify, session
import json
import random
import re
import os
from datetime import datetime
from config import config
# Create Flask application
app = Flask(__name__)
# Configure the application
config_name = os.environ.get('FLASK_CONFIG', 'default')
app.config.from_object(config[config_name])
config[config_name].init_app(app)
# Function to parse markdown and extract questions
def parse_markdown_questions():
with open(app.config['MARKDOWN_FILE'], 'r', encoding='utf-8') as file:
content = file.read()
questions = []
# Split content by questions using ### as separator
question_blocks = re.split(r'\n### (\d+)\n', content)[1:] # Ignore first empty element
for i in range(0, len(question_blocks), 2):
if i + 1 >= len(question_blocks):
break
question_num = int(question_blocks[i])
question_content = question_blocks[i + 1].strip()
# Check if there's an image at the beginning (now supports both local and remote URLs)
has_image = ('![](https://sierdgtt.mtc.gob.pe/Content/img-data/' in question_content or
'![](/static/images/' in question_content)
image_url = ""
if has_image:
# Try local images first, then remote
img_match = re.search(r'!\[\]\((/static/images/[^)]+)\)', question_content)
if not img_match:
img_match = re.search(r'!\[\]\((https://sierdgtt\.mtc\.gob\.pe/Content/img-data/[^)]+)\)', question_content)
if img_match:
image_url = img_match.group(1)
question_content = re.sub(r'!\[\]\([^)]+\)\n*', '', question_content).strip()
# Separate question from options
lines = question_content.split('\n')
question_lines = []
option_lines = []
in_options = False
for line in lines:
line = line.strip()
if not line:
continue
if re.match(r'^✅?\s*[a-d]\)', line):
in_options = True
option_lines.append(line)
elif not in_options:
question_lines.append(line)
question_text = ' '.join(question_lines).strip()
# Extract options and correct answer
options = []
correct_option = ""
for line in option_lines:
original_line = line.strip()
# Check if this line has the ✅
if '' in original_line:
# Extract the letter of the correct option
match = re.search(r'\s*([a-d])\)', original_line)
if match:
correct_option = match.group(1)
# Clean the line by removing ✅ completely and any extra spaces
clean_line = re.sub(r'\s*', '', original_line)
clean_line = re.sub(r'', '', clean_line) # In case there's ✅ without spaces
clean_line = clean_line.strip()
options.append(clean_line)
if len(options) >= 2 and correct_option and question_text: # Validate we have complete data
questions.append({
'id': question_num,
'question': question_text,
'options': options,
'correct': correct_option,
'image': image_url,
'has_image': has_image
})
return sorted(questions, key=lambda x: x['id'])
# Load questions when starting the application
QUESTIONS = parse_markdown_questions()
@app.route('/')
def index():
return render_template('index.html', total_questions=len(QUESTIONS))
@app.route('/study')
def study():
return render_template('study.html')
@app.route('/practice')
def practice():
return render_template('practice.html')
@app.route('/exam')
def exam():
return render_template('exam.html')
@app.route('/api/questions')
def get_questions():
mode = request.args.get('mode', 'all')
count = request.args.get('count', type=int)
if mode == 'random':
questions = random.sample(QUESTIONS, min(count or 20, len(QUESTIONS)))
elif mode == 'range':
start = request.args.get('start', 1, type=int)
end = request.args.get('end', len(QUESTIONS), type=int)
questions = [q for q in QUESTIONS if start <= q['id'] <= end]
else:
questions = QUESTIONS
return jsonify(questions)
@app.route('/api/question/<int:question_id>')
def get_question(question_id):
question = next((q for q in QUESTIONS if q['id'] == question_id), None)
if question:
return jsonify(question)
return jsonify({'error': 'Pregunta no encontrada'}), 404
@app.route('/api/check_answer', methods=['POST'])
def check_answer():
data = request.json
question_id = data.get('question_id')
user_answer = data.get('answer')
question = next((q for q in QUESTIONS if q['id'] == question_id), None)
if not question:
return jsonify({'error': 'Pregunta no encontrada'}), 404
is_correct = user_answer == question['correct']
return jsonify({
'correct': is_correct,
'correct_answer': question['correct'],
'explanation': f"La respuesta correcta es: {question['correct']}"
})
@app.route('/api/stats')
def get_stats():
# Statistics are now handled completely in client localStorage
# This endpoint returns default stats for compatibility
return jsonify({
'total_answered': 0,
'correct_answers': 0,
'incorrect_answers': 0,
'accuracy': 0,
'message': 'Stats handled by localStorage'
})
@app.route('/api/update_stats', methods=['POST'])
def update_stats():
# Statistics are now handled completely in client localStorage
# This endpoint only confirms that the update was received
data = request.json
is_correct = data.get('correct', False)
return jsonify({
'success': True,
'message': 'Stats updated in localStorage',
'received_correct': is_correct
})
@app.route('/api/reset_stats', methods=['POST'])
def reset_stats():
"""Confirm that statistics were reset in localStorage"""
return jsonify({
'success': True,
'message': 'Estadísticas restablecidas correctamente en localStorage'
})
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=5000)

74
config.py Normal file
View File

@@ -0,0 +1,74 @@
"""
Configuración de la aplicación Balotario Licencia A-I
"""
import os
class Config:
"""Configuración base de la aplicación"""
# Configuración de Flask
SECRET_KEY = os.environ.get('SECRET_KEY') or 'balotario_secret_key_2024_super_secure'
DEBUG = os.environ.get('FLASK_DEBUG', 'True').lower() == 'true'
# Configuración de la aplicación
APP_NAME = "Balotario Licencia Clase A - Categoría I"
APP_VERSION = "1.0.0"
APP_DESCRIPTION = "Aplicación interactiva para estudiar el balotario oficial del MTC Perú"
# Configuración del balotario
MARKDOWN_FILE = 'data/balotario_clase_a_cat_I.md'
TOTAL_QUESTIONS = 200
# Configuración de límites
MAX_PRACTICE_QUESTIONS = 50
MAX_EXAM_QUESTIONS = 40
DEFAULT_EXAM_TIME = 30 # minutos
# Configuración de la interfaz
ITEMS_PER_PAGE = 20
ANIMATION_DURATION = 300 # milisegundos
# URLs de imágenes
IMAGE_BASE_URL = "https://sierdgtt.mtc.gob.pe/Content/img-data/"
# Configuración de estadísticas
STATS_RETENTION_DAYS = 30
# Configuración de temas
DEFAULT_THEME = "light"
AVAILABLE_THEMES = ["light", "dark"]
# Configuración de sonidos
SOUND_ENABLED = True
# Configuración de accesibilidad
HIGH_CONTRAST_MODE = False
LARGE_TEXT_MODE = False
@staticmethod
def init_app(app):
"""Inicializar configuración específica de la aplicación"""
pass
class DevelopmentConfig(Config):
"""Configuración para desarrollo"""
DEBUG = True
class ProductionConfig(Config):
"""Configuración para producción"""
DEBUG = False
SECRET_KEY = os.environ.get('SECRET_KEY') or 'production_secret_key_change_this'
class TestingConfig(Config):
"""Configuración para testing"""
TESTING = True
DEBUG = True
# Configuraciones disponibles
config = {
'development': DevelopmentConfig,
'production': ProductionConfig,
'testing': TestingConfig,
'default': DevelopmentConfig
}

113
data/README.md Normal file
View File

@@ -0,0 +1,113 @@
# 📚 Datos del Balotario
Este directorio contiene los archivos de datos principales de la aplicación Balotario Licencia A-I.
## 📄 Archivos de Contenido
### `balotario_clase_a_cat_I.md`
**Archivo principal con las preguntas del balotario**
#### Características:
-**200 preguntas oficiales** del MTC Perú
-**Formato markdown** estructurado
-**Respuestas correctas** marcadas con ✅
-**Imágenes incluidas** de señales de tránsito
-**Numeración secuencial** del 1 al 200
#### Estructura de cada pregunta:
```markdown
### [NÚMERO]
[TEXTO DE LA PREGUNTA]
a) [OPCIÓN A]
b) [OPCIÓN B]
✅ c) [OPCIÓN CORRECTA]
d) [OPCIÓN D]
---
```
#### Categorías de preguntas:
- 🚦 **Señales de tránsito** (reglamentarias, preventivas, informativas)
- 🚗 **Normas de circulación** y preferencia de paso
- 📋 **Documentos obligatorios** y licencias
-**Límites de velocidad** por tipo de vía
- ⚖️ **Infracciones y sanciones**
- 🛡️ **Seguridad vial** y primeros auxilios
- 🔧 **Mantenimiento vehicular** e inspecciones
## 🔄 Actualización de Contenido
### Fuente Oficial
- **Origen**: Ministerio de Transportes y Comunicaciones (MTC) del Perú
- **Tipo**: Balotario oficial para Licencia Clase A - Categoría I
- **Vigencia**: Actualizado según normativa vigente
### Formato de Imágenes
Las imágenes de señales se referencian con:
```markdown
![](https://sierdgtt.mtc.gob.pe/Content/img-data/img[NÚMERO].jpg)
```
### Validación de Contenido
Para verificar la integridad del archivo:
```bash
# Contar preguntas
grep -c "^### [0-9]" data/balotario_clase_a_cat_I.md
# Contar respuestas correctas
grep -c "✅" data/balotario_clase_a_cat_I.md
# Verificar numeración secuencial
python test/test_parser.py
```
## 📊 Estadísticas del Contenido
- **Total preguntas**: 200
- **Con imágenes**: ~50 preguntas
- **Categorías principales**: 7
- **Formato**: Markdown estándar
- **Encoding**: UTF-8
- **Tamaño aproximado**: ~150KB
## 🔧 Uso en la Aplicación
El archivo es parseado por `app.py` usando:
```python
def parse_markdown_questions():
with open(app.config['MARKDOWN_FILE'], 'r', encoding='utf-8') as file:
content = file.read()
# ... procesamiento
```
## 🛡️ Respaldo y Versionado
### Recomendaciones:
-**Mantener en control de versiones** (Git)
-**Crear respaldos** antes de modificaciones
-**Validar formato** después de cambios
-**Probar parser** con contenido actualizado
### Estructura de respaldo:
```
data/
├── balotario_clase_a_cat_I.md # Actual
├── backup/
│ ├── balotario_2024_10_26.md # Respaldo por fecha
│ └── balotario_original.md # Versión original
└── README.md # Esta documentación
```
## ⚠️ Notas Importantes
- **No modificar** la estructura de numeración (### 1, ### 2, etc.)
- **Mantener formato** de opciones (a), b), c), d))
- **Preservar** el emoji ✅ para respuestas correctas
- **Validar** URLs de imágenes si se actualizan
- **Probar** la aplicación después de cambios
---
**Fuente**: Contenido oficial del MTC Perú para examen de Licencia de Conducir Clase A - Categoría I

File diff suppressed because it is too large Load Diff

23
docker-compose.dev.yml Normal file
View File

@@ -0,0 +1,23 @@
version: '3.8'
services:
balotario-dev:
build: .
container_name: balotario-dev
ports:
- "5000:5000"
environment:
- FLASK_ENV=development
- FLASK_DEBUG=true
- DOCKER_CONTAINER=true
volumes:
# Montar código para desarrollo (hot reload)
- .:/app
- /app/venv # Excluir venv del montaje
restart: "no"
networks:
- balotario-dev-network
networks:
balotario-dev-network:
driver: bridge

48
docker-compose.yml Normal file
View File

@@ -0,0 +1,48 @@
version: '3.8'
services:
balotario:
build: .
container_name: balotario-app
ports:
- "5000:5000"
environment:
- FLASK_ENV=production
- FLASK_DEBUG=false
- DOCKER_CONTAINER=true
volumes:
# Montar datos para persistencia (opcional)
- ./data:/app/data:ro
restart: unless-stopped
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:5000/"]
interval: 30s
timeout: 10s
retries: 3
start_period: 40s
networks:
- balotario-network
# Nginx como proxy reverso (opcional)
nginx:
image: nginx:alpine
container_name: balotario-nginx
ports:
- "80:80"
- "443:443"
volumes:
- ./docker/nginx.conf:/etc/nginx/nginx.conf:ro
- ./docker/ssl:/etc/nginx/ssl:ro
depends_on:
- balotario
restart: unless-stopped
networks:
- balotario-network
networks:
balotario-network:
driver: bridge
volumes:
balotario-data:
driver: local

213
docker/README.md Normal file
View File

@@ -0,0 +1,213 @@
# 🐳 Docker para Balotario Licencia A-I
Este directorio contiene la configuración de Docker para la aplicación Balotario.
## 📁 Archivos de Docker
### `Dockerfile`
**Imagen principal de la aplicación**
#### Características:
-**Base**: Python 3.11-slim (imagen ligera)
-**Usuario no-root** para seguridad
-**Multi-stage** optimizado para producción
-**Health check** integrado
-**Variables de entorno** configurables
### `docker-compose.yml`
**Orquestación de servicios**
#### Servicios incluidos:
- **balotario**: Aplicación Flask principal
- **nginx**: Proxy reverso (opcional)
### `nginx.conf`
**Configuración de Nginx**
#### Funcionalidades:
-**Proxy reverso** hacia Flask
-**Compresión gzip** para mejor rendimiento
-**Rate limiting** para protección
-**Headers de seguridad**
-**Cache de archivos estáticos**
## 🚀 Uso Rápido
### Opción 1: Docker Simple
```bash
# Construir imagen
docker build -t balotario .
# Ejecutar en desarrollo
docker run -p 5000:5000 -e FLASK_ENV=development balotario
# Ejecutar en producción
docker run -d -p 5000:5000 -e FLASK_ENV=production balotario
```
### Opción 2: Docker Compose (Recomendado)
```bash
# Iniciar todos los servicios
docker-compose up -d
# Ver logs
docker-compose logs -f
# Detener servicios
docker-compose down
```
### Opción 3: Script de Utilidades
```bash
# Usar el script helper
./scripts/docker.sh build
./scripts/docker.sh compose-up
./scripts/docker.sh logs
./scripts/docker.sh clean
```
## 🔧 Configuración
### Variables de Entorno
#### Para Desarrollo:
```bash
FLASK_ENV=development
FLASK_DEBUG=true
DOCKER_CONTAINER=true
```
#### Para Producción:
```bash
FLASK_ENV=production
FLASK_DEBUG=false
DOCKER_CONTAINER=true
SECRET_KEY=tu_clave_secreta_aqui
```
### Puertos
- **5000**: Aplicación Flask
- **80**: Nginx (si se usa)
- **443**: HTTPS (si se configura)
## 📊 Recursos
### Imagen Docker
- **Tamaño base**: ~150MB (Python slim)
- **Tamaño final**: ~200MB (con dependencias)
- **RAM recomendada**: 512MB mínimo
- **CPU**: 1 core suficiente
### Volúmenes
```yaml
volumes:
- ./data:/app/data:ro # Datos de solo lectura
- balotario-logs:/app/logs # Logs persistentes
```
## 🛡️ Seguridad
### Medidas Implementadas:
-**Usuario no-root** en el contenedor
-**Health checks** para monitoreo
-**Rate limiting** en Nginx
-**Headers de seguridad**
-**Secrets** via variables de entorno
### Recomendaciones Adicionales:
- 🔒 Usar **secrets de Docker** para claves
- 🔒 Configurar **HTTPS** con certificados
- 🔒 Implementar **logging** centralizado
- 🔒 Usar **registry privado** para imágenes
## 🚀 Despliegue
### Desarrollo Local
```bash
# Clonar proyecto
git clone <repo>
cd balotario-licencia-a1
# Iniciar con Docker Compose
docker-compose up -d
# Acceder a la aplicación
open http://localhost:5000
```
### Producción
```bash
# Variables de entorno
export FLASK_ENV=production
export SECRET_KEY=tu_clave_super_secreta
# Construir y ejecutar
docker build -t balotario:prod .
docker run -d -p 80:5000 \
-e FLASK_ENV=production \
-e SECRET_KEY=$SECRET_KEY \
--name balotario-prod \
--restart unless-stopped \
balotario:prod
```
### Con Nginx (Recomendado para Producción)
```bash
# Usar Docker Compose completo
docker-compose -f docker-compose.yml up -d
# Acceder via Nginx
open http://localhost
```
## 🐛 Troubleshooting
### Problemas Comunes
#### Puerto ocupado:
```bash
# Cambiar puerto en docker-compose.yml
ports:
- "8080:5000" # Usar puerto 8080 en lugar de 5000
```
#### Permisos:
```bash
# Verificar permisos de archivos
ls -la data/
chmod 644 data/balotario_clase_a_cat_I.md
```
#### Logs:
```bash
# Ver logs detallados
docker-compose logs -f balotario
docker logs balotario-prod
```
#### Limpiar todo:
```bash
# Limpiar completamente
./scripts/docker.sh clean
docker system prune -a
```
## 📈 Monitoreo
### Health Checks
```bash
# Verificar salud del contenedor
docker inspect balotario-prod | grep Health -A 10
# Endpoint de salud
curl http://localhost:5000/
```
### Métricas
- **CPU**: `docker stats balotario-prod`
- **Memoria**: `docker stats --no-stream`
- **Logs**: `docker logs --tail 100 balotario-prod`
---
**Nota**: Esta configuración está optimizada para facilidad de uso y seguridad básica. Para producción enterprise, considera usar Kubernetes o Docker Swarm.

95
docker/nginx.conf Normal file
View File

@@ -0,0 +1,95 @@
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
# Logging
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
error_log /var/log/nginx/error.log warn;
# Gzip compression
gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_types text/plain text/css text/xml text/javascript
application/javascript application/xml+rss
application/json application/xml;
# Rate limiting
limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
limit_req_zone $binary_remote_addr zone=static:10m rate=50r/s;
# Upstream para la aplicación Flask
upstream balotario_app {
server balotario:5000;
}
# Servidor principal
server {
listen 80;
server_name localhost;
# Security headers
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
# Archivos estáticos con cache
location /static/ {
limit_req zone=static burst=20 nodelay;
proxy_pass http://balotario_app;
proxy_cache_valid 200 1d;
expires 1d;
add_header Cache-Control "public, immutable";
}
# API endpoints con rate limiting
location /api/ {
limit_req zone=api burst=5 nodelay;
proxy_pass http://balotario_app;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
# Aplicación principal
location / {
proxy_pass http://balotario_app;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
# Timeouts
proxy_connect_timeout 30s;
proxy_send_timeout 30s;
proxy_read_timeout 30s;
}
# Health check
location /health {
access_log off;
proxy_pass http://balotario_app;
}
}
# Configuración HTTPS (opcional)
# server {
# listen 443 ssl http2;
# server_name localhost;
#
# ssl_certificate /etc/nginx/ssl/cert.pem;
# ssl_certificate_key /etc/nginx/ssl/key.pem;
#
# # Resto de configuración igual que HTTP
# }
}

5
requirements-dev.txt Normal file
View File

@@ -0,0 +1,5 @@
# Include production requirements
-r requirements.txt
# Development and testing tools
requests
pytest

2
requirements.txt Normal file
View File

@@ -0,0 +1,2 @@
Flask==2.3.3
Werkzeug==2.3.7

199
run.py Normal file
View File

@@ -0,0 +1,199 @@
#!/usr/bin/env python3
"""
Script unificado para ejecutar la aplicación Balotario
Maneja tanto desarrollo como producción según variables de entorno
"""
import os
import sys
import webbrowser
import time
from threading import Timer
from pathlib import Path
# Agregar el directorio actual al path
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
def load_env_file():
"""Cargar variables de entorno desde archivo .env si existe"""
env_file = Path('.env')
if env_file.exists():
print("📄 Cargando variables de entorno desde .env")
try:
with open(env_file, 'r', encoding='utf-8') as f:
for line in f:
line = line.strip()
# Ignorar líneas vacías y comentarios
if line and not line.startswith('#'):
# Separar clave=valor
if '=' in line:
key, value = line.split('=', 1)
key = key.strip()
value = value.strip()
# Remover comillas si existen
if value.startswith('"') and value.endswith('"'):
value = value[1:-1]
elif value.startswith("'") and value.endswith("'"):
value = value[1:-1]
# Solo establecer si no existe ya
if key not in os.environ:
os.environ[key] = value
print("✅ Variables de entorno cargadas")
except Exception as e:
print(f"⚠️ Error cargando .env: {e}")
else:
print("💡 Archivo .env no encontrado, usando valores por defecto")
print(" Copia .env.sample a .env para personalizar la configuración")
def get_environment():
"""Determinar el entorno de ejecución"""
flask_env = os.environ.get('FLASK_ENV', 'development').lower()
flask_debug = os.environ.get('FLASK_DEBUG', 'true').lower() == 'true'
is_production = flask_env == 'production' or not flask_debug
is_docker = os.path.exists('/.dockerenv') or os.environ.get('DOCKER_CONTAINER', False)
return {
'is_production': is_production,
'is_docker': is_docker,
'flask_env': flask_env,
'flask_debug': flask_debug
}
def print_banner(env_info):
"""Mostrar banner de inicio"""
if env_info['is_production']:
print("🐳 BALOTARIO LICENCIA CLASE A - CATEGORÍA I")
print("=" * 50)
print("🚀 Modo: PRODUCCIÓN")
print("🔒 Debug: Desactivado")
print("📍 Puerto: 5000")
if env_info['is_docker']:
print("🐳 Ejecutándose en Docker")
print("=" * 50)
else:
print("=" * 60)
print("🚗 BALOTARIO LICENCIA CLASE A - CATEGORÍA I")
print("=" * 60)
print("📚 200 preguntas oficiales del MTC Perú")
print("🎯 Modos: Estudio, Práctica y Examen Simulado")
print("🌐 Interfaz moderna y responsive")
print("📊 Seguimiento de progreso y estadísticas")
print("=" * 60)
def check_dependencies():
"""Verificar que las dependencias estén instaladas"""
try:
import flask
print("✅ Flask encontrado")
return True
except ImportError:
print("❌ Flask no encontrado")
print("💡 Instala las dependencias con: pip install -r requirements.txt")
return False
def check_files():
"""Verificar que los archivos necesarios existan"""
required_files = [
'data/balotario_clase_a_cat_I.md',
'templates/base.html',
'templates/index.html',
'static/css/custom.css',
'static/js/app.js'
]
missing_files = []
for file in required_files:
if not Path(file).exists():
missing_files.append(file)
if missing_files:
print("❌ Archivos faltantes:")
for file in missing_files:
print(f" - {file}")
return False
print("✅ Todos los archivos necesarios están presentes")
return True
def open_browser():
"""Abrir el navegador después de un breve delay (solo en desarrollo)"""
try:
webbrowser.open('http://localhost:5000')
except Exception:
# Si no puede abrir el navegador, no hacer nada
pass
def setup_production_config():
"""Configurar variables de entorno para producción"""
os.environ.setdefault('FLASK_ENV', 'production')
os.environ.setdefault('FLASK_DEBUG', 'False')
os.environ.setdefault('FLASK_CONFIG', 'production')
def main():
"""Función principal"""
# Cargar variables de entorno
load_env_file()
# Determinar entorno
env_info = get_environment()
# Mostrar banner
print_banner(env_info)
# Verificar dependencias
if not check_dependencies():
sys.exit(1)
# Verificar archivos
if not check_files():
sys.exit(1)
try:
from app import app
print("✅ Aplicación cargada correctamente")
if env_info['is_production']:
# Configuración de producción
print("🚀 Servidor iniciado en modo producción")
app.run(
host='0.0.0.0',
port=5000,
debug=False,
threaded=True
)
else:
# Configuración de desarrollo
print("\n🚀 Iniciando servidor...")
print("📍 URL: http://localhost:5000")
print("🔧 Modo: Desarrollo")
print("💡 Presiona Ctrl+C para detener el servidor")
print("🎨 Usa Ctrl+D para cambiar tema")
print("=" * 60)
# Abrir navegador automáticamente después de 2 segundos (solo en desarrollo local)
if not env_info['is_docker']:
Timer(2.0, open_browser).start()
app.run(
debug=True,
host='0.0.0.0',
port=5000,
use_reloader=True,
threaded=True
)
except ImportError as e:
print(f"❌ Error al importar la aplicación: {e}")
sys.exit(1)
except KeyboardInterrupt:
if not env_info['is_production']:
print("\n\n👋 Servidor detenido por el usuario")
print("¡Gracias por usar el Balotario!")
except Exception as e:
print(f"❌ Error inesperado: {e}")
sys.exit(1)
if __name__ == "__main__":
main()

136
scripts/README.md Normal file
View File

@@ -0,0 +1,136 @@
# 🛠️ Scripts de Utilidades
Este directorio contiene scripts útiles para el desarrollo y mantenimiento del proyecto Balotario.
## 📁 Scripts Disponibles
### 🐍 `dev.py`
**Script principal de desarrollo en Python**
#### Comandos:
```bash
# Limpiar cache y archivos temporales
python scripts/dev.py clean
# Ejecutar todos los tests de Python
python scripts/dev.py test
# Verificar dependencias instaladas
python scripts/dev.py deps
# Iniciar servidor de desarrollo
python scripts/dev.py dev
# Mostrar ayuda
python scripts/dev.py help
```
#### Funcionalidades:
- ✅ Limpieza automática de `__pycache__` y archivos `.pyc`
- ✅ Ejecución de tests de Python
- ✅ Verificación de dependencias
- ✅ Inicio del servidor de desarrollo
- ✅ Ayuda integrada
### 🧹 `clean.sh`
**Script de limpieza rápida en Bash**
#### Uso:
```bash
# Ejecutar limpieza completa
./scripts/clean.sh
# O con bash explícito
bash scripts/clean.sh
```
#### Funcionalidades:
- ✅ Elimina `__pycache__` recursivamente
- ✅ Elimina archivos `.pyc`, `.pyo`
- ✅ Elimina archivos temporales (`.tmp`, `.temp`, `*~`)
- ✅ Elimina archivos del sistema (`.DS_Store`)
- ✅ Elimina logs (`.log`)
- ✅ Muestra estadísticas del proyecto
## 🚀 Uso Rápido
### Desarrollo Diario
```bash
# 1. Limpiar proyecto
./scripts/clean.sh
# 2. Verificar que todo esté bien
python scripts/dev.py test
# 3. Iniciar desarrollo
python scripts/dev.py dev
```
### Antes de Commit
```bash
# Limpiar y verificar
./scripts/clean.sh
python scripts/dev.py test
```
### Configuración Inicial
```bash
# Verificar dependencias
python scripts/dev.py deps
# Si faltan dependencias
pip install -r requirements.txt
```
## 🔧 Personalización
### Agregar Nuevos Comandos a `dev.py`
1. Crear nueva función en `dev.py`
2. Agregar comando en `main()`
3. Documentar en `show_help()`
### Modificar `clean.sh`
- Agregar nuevos patrones de archivos a limpiar
- Modificar las estadísticas mostradas
- Agregar verificaciones adicionales
## 📊 Estadísticas
El script `clean.sh` muestra:
- 📁 Directorio actual
- 📄 Número de archivos Python
- 🌐 Número de archivos HTML
- 🎨 Número de archivos CSS
- ⚡ Número de archivos JavaScript
- 🧪 Número de tests
## 🐛 Troubleshooting
### Permisos en Linux/macOS
```bash
# Dar permisos de ejecución
chmod +x scripts/clean.sh
chmod +x scripts/dev.py
```
### Problemas con Python
```bash
# Verificar versión de Python
python --version
# Verificar que esté en el entorno virtual
which python
```
### Problemas con Bash
```bash
# Ejecutar con bash explícito
bash scripts/clean.sh
# Verificar sintaxis
bash -n scripts/clean.sh
```
---
**Nota**: Estos scripts están diseñados para facilitar el desarrollo. Úsalos regularmente para mantener el proyecto limpio y organizado.

31
scripts/clean.sh Executable file
View File

@@ -0,0 +1,31 @@
#!/bin/bash
# Script de limpieza para el proyecto Balotario
echo "🧹 Limpiando proyecto Balotario..."
# Limpiar cache de Python
echo "📦 Eliminando __pycache__..."
find . -type d -name "__pycache__" -exec rm -rf {} + 2>/dev/null || true
find . -name "*.pyc" -delete 2>/dev/null || true
find . -name "*.pyo" -delete 2>/dev/null || true
# Limpiar archivos temporales
echo "🗑️ Eliminando archivos temporales..."
find . -name "*.tmp" -delete 2>/dev/null || true
find . -name "*.temp" -delete 2>/dev/null || true
find . -name "*~" -delete 2>/dev/null || true
find . -name ".DS_Store" -delete 2>/dev/null || true
# Limpiar logs
echo "📝 Eliminando logs..."
find . -name "*.log" -delete 2>/dev/null || true
echo "✅ Limpieza completada"
echo ""
echo "📊 Estado del proyecto:"
echo " 📁 Directorio principal: $(pwd)"
echo " 📄 Archivos Python: $(find . -name "*.py" | wc -l)"
echo " 🌐 Archivos HTML: $(find . -name "*.html" | wc -l)"
echo " 🎨 Archivos CSS: $(find . -name "*.css" | wc -l)"
echo " ⚡ Archivos JS: $(find . -name "*.js" | wc -l)"
echo " 🧪 Tests: $(find test/ -name "test_*" | wc -l)"

127
scripts/dev.py Normal file
View File

@@ -0,0 +1,127 @@
#!/usr/bin/env python3
"""
Script de utilidades para desarrollo del Balotario
"""
import os
import sys
import subprocess
import shutil
from pathlib import Path
def clean_cache():
"""Limpiar archivos de cache y temporales"""
print("🧹 Limpiando archivos de cache...")
# Limpiar __pycache__
for root, dirs, files in os.walk('.'):
for dir_name in dirs:
if dir_name == '__pycache__':
cache_path = os.path.join(root, dir_name)
print(f" Eliminando: {cache_path}")
shutil.rmtree(cache_path)
# Limpiar archivos .pyc
for root, dirs, files in os.walk('.'):
for file in files:
if file.endswith('.pyc'):
pyc_path = os.path.join(root, file)
print(f" Eliminando: {pyc_path}")
os.remove(pyc_path)
print("✅ Cache limpiado")
def run_tests():
"""Ejecutar todos los tests de Python"""
print("🧪 Ejecutando tests de Python...")
test_files = [
'test/test_parser.py',
'test/test_clean_parser.py'
]
for test_file in test_files:
if os.path.exists(test_file):
print(f"\n📝 Ejecutando: {test_file}")
try:
subprocess.run([sys.executable, test_file], check=True)
print(f"{test_file} - PASÓ")
except subprocess.CalledProcessError:
print(f"{test_file} - FALLÓ")
else:
print(f"⚠️ {test_file} - NO ENCONTRADO")
def check_dependencies():
"""Verificar que las dependencias estén instaladas"""
print("📦 Verificando dependencias...")
try:
import flask
print(f"✅ Flask {flask.__version__}")
except ImportError:
print("❌ Flask no instalado")
return False
return True
def start_dev_server():
"""Iniciar servidor de desarrollo"""
print("🚀 Iniciando servidor de desarrollo...")
if not check_dependencies():
print("❌ Faltan dependencias. Ejecuta: pip install -r requirements.txt")
return
# Configurar variables de entorno para desarrollo
os.environ['FLASK_ENV'] = 'development'
os.environ['FLASK_DEBUG'] = 'true'
try:
subprocess.run([sys.executable, 'run.py'])
except KeyboardInterrupt:
print("\n👋 Servidor detenido")
def show_help():
"""Mostrar ayuda"""
print("""
🛠️ Script de Utilidades - Balotario Licencia A-I
Comandos disponibles:
clean - Limpiar archivos de cache y temporales
test - Ejecutar todos los tests de Python
deps - Verificar dependencias instaladas
dev - Iniciar servidor de desarrollo
help - Mostrar esta ayuda
Uso:
python scripts/dev.py <comando>
Ejemplos:
python scripts/dev.py clean
python scripts/dev.py test
python scripts/dev.py dev
""")
def main():
if len(sys.argv) < 2:
show_help()
return
command = sys.argv[1].lower()
if command == 'clean':
clean_cache()
elif command == 'test':
run_tests()
elif command == 'deps':
check_dependencies()
elif command == 'dev':
start_dev_server()
elif command == 'help':
show_help()
else:
print(f"❌ Comando desconocido: {command}")
show_help()
if __name__ == '__main__':
main()

192
scripts/docker.sh Executable file
View File

@@ -0,0 +1,192 @@
#!/bin/bash
# Scripts de utilidades para Docker
set -e
# Colores para output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
# Funciones de utilidad
log_info() {
echo -e "${BLUE} $1${NC}"
}
log_success() {
echo -e "${GREEN}$1${NC}"
}
log_warning() {
echo -e "${YELLOW}⚠️ $1${NC}"
}
log_error() {
echo -e "${RED}$1${NC}"
}
# Función para construir la imagen
build() {
log_info "Construyendo imagen Docker..."
docker build -t balotario:latest .
log_success "Imagen construida exitosamente"
}
# Función para ejecutar en desarrollo
dev() {
log_info "Iniciando contenedor en modo desarrollo..."
docker run -it --rm \
-p 5000:5000 \
-v $(pwd):/app \
-e FLASK_ENV=development \
-e FLASK_DEBUG=true \
-e DOCKER_CONTAINER=true \
--name balotario-dev \
balotario:latest
}
# Función para ejecutar en producción
prod() {
log_info "Iniciando contenedor en modo producción..."
docker run -d \
-p 5000:5000 \
-e FLASK_ENV=production \
-e FLASK_DEBUG=false \
-e DOCKER_CONTAINER=true \
--name balotario-prod \
--restart unless-stopped \
balotario:latest
log_success "Contenedor iniciado en modo producción"
log_info "Accede a: http://localhost:5000"
}
# Función para usar Docker Compose
compose_up() {
log_info "Iniciando servicios con Docker Compose..."
docker-compose up -d
log_success "Servicios iniciados"
log_info "Aplicación: http://localhost:5000"
log_info "Nginx: http://localhost:80"
}
# Función para detener Docker Compose
compose_down() {
log_info "Deteniendo servicios..."
docker-compose down
log_success "Servicios detenidos"
}
# Función para ver logs
logs() {
local service=${1:-balotario}
log_info "Mostrando logs de $service..."
docker-compose logs -f $service
}
# Función para limpiar contenedores e imágenes
clean() {
log_warning "Limpiando contenedores e imágenes..."
# Detener contenedores
docker stop balotario-dev balotario-prod 2>/dev/null || true
docker rm balotario-dev balotario-prod 2>/dev/null || true
# Limpiar con docker-compose
docker-compose down --rmi all --volumes --remove-orphans 2>/dev/null || true
# Limpiar imágenes huérfanas
docker image prune -f
log_success "Limpieza completada"
}
# Función para mostrar estado
status() {
log_info "Estado de contenedores:"
docker ps -a --filter "name=balotario"
echo ""
log_info "Estado de servicios Docker Compose:"
docker-compose ps
}
# Función para entrar al contenedor
shell() {
local container=${1:-balotario-prod}
log_info "Entrando al contenedor $container..."
docker exec -it $container /bin/bash
}
# Función de ayuda
help() {
echo "🐳 Scripts de Docker para Balotario"
echo ""
echo "Uso: $0 <comando>"
echo ""
echo "Comandos disponibles:"
echo " build - Construir imagen Docker"
echo " dev - Ejecutar en modo desarrollo"
echo " prod - Ejecutar en modo producción"
echo " compose-up - Iniciar con Docker Compose"
echo " compose-down - Detener Docker Compose"
echo " logs [service]- Ver logs (default: balotario)"
echo " clean - Limpiar contenedores e imágenes"
echo " status - Mostrar estado de contenedores"
echo " shell [name] - Entrar al contenedor"
echo " help - Mostrar esta ayuda"
echo ""
echo "Ejemplos:"
echo " $0 build"
echo " $0 compose-up"
echo " $0 logs nginx"
echo " $0 shell balotario-prod"
}
# Función principal
main() {
case "${1:-help}" in
build)
build
;;
dev)
build
dev
;;
prod)
build
prod
;;
compose-up)
compose_up
;;
compose-down)
compose_down
;;
logs)
logs $2
;;
clean)
clean
;;
status)
status
;;
shell)
shell $2
;;
help|*)
help
;;
esac
}
# Verificar que Docker esté instalado
if ! command -v docker &> /dev/null; then
log_error "Docker no está instalado"
exit 1
fi
# Ejecutar función principal
main "$@"

156
scripts/download_images.py Normal file
View File

@@ -0,0 +1,156 @@
#!/usr/bin/env python3
"""
Script to download all images from the MTC website and store them locally.
This makes the application work completely offline.
"""
import os
import re
import requests
from urllib.parse import urlparse
import time
from pathlib import Path
def create_images_directory():
"""Create the static/images directory if it doesn't exist."""
images_dir = Path("static/images")
images_dir.mkdir(parents=True, exist_ok=True)
return images_dir
def extract_image_urls_from_markdown():
"""Extract all image URLs from the markdown file."""
markdown_file = Path("data/balotario_clase_a_cat_I.md")
if not markdown_file.exists():
print(f"Error: {markdown_file} not found!")
return []
with open(markdown_file, 'r', encoding='utf-8') as f:
content = f.read()
# Find all image URLs
pattern = r'!\[\]\((https://sierdgtt\.mtc\.gob\.pe/Content/img-data/img\d+\.jpg)\)'
urls = re.findall(pattern, content)
return list(set(urls)) # Remove duplicates
def download_image(url, images_dir, retries=3):
"""Download a single image with retry logic."""
try:
# Extract filename from URL
filename = os.path.basename(urlparse(url).path)
filepath = images_dir / filename
# Skip if already exists
if filepath.exists():
print(f"{filename} already exists")
return True
print(f"📥 Downloading {filename}...")
# Download with retries
for attempt in range(retries):
try:
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
}
response = requests.get(url, headers=headers, timeout=30)
response.raise_for_status()
# Save the image
with open(filepath, 'wb') as f:
f.write(response.content)
print(f"✅ Downloaded {filename} ({len(response.content)} bytes)")
return True
except requests.RequestException as e:
print(f"❌ Attempt {attempt + 1} failed for {filename}: {e}")
if attempt < retries - 1:
time.sleep(2) # Wait before retry
print(f"💥 Failed to download {filename} after {retries} attempts")
return False
except Exception as e:
print(f"💥 Error downloading {url}: {e}")
return False
def update_markdown_file(images_dir):
"""Update the markdown file to use local image paths."""
markdown_file = Path("data/balotario_clase_a_cat_I.md")
backup_file = Path("data/balotario_clase_a_cat_I.md.backup")
# Create backup
if not backup_file.exists():
with open(markdown_file, 'r', encoding='utf-8') as f:
content = f.read()
with open(backup_file, 'w', encoding='utf-8') as f:
f.write(content)
print(f"📋 Created backup: {backup_file}")
# Read current content
with open(markdown_file, 'r', encoding='utf-8') as f:
content = f.read()
# Replace URLs with local paths
pattern = r'!\[\]\(https://sierdgtt\.mtc\.gob\.pe/Content/img-data/(img\d+\.jpg)\)'
replacement = r'![](/static/images/\1)'
updated_content = re.sub(pattern, replacement, content)
# Write updated content
with open(markdown_file, 'w', encoding='utf-8') as f:
f.write(updated_content)
print("📝 Updated markdown file to use local image paths")
def main():
"""Main function to download all images."""
print("🚀 Starting image download process...")
# Create images directory
images_dir = create_images_directory()
print(f"📁 Images will be saved to: {images_dir}")
# Extract image URLs
urls = extract_image_urls_from_markdown()
print(f"🔍 Found {len(urls)} unique images to download")
if not urls:
print("❌ No image URLs found!")
return
# Download images
successful = 0
failed = 0
for i, url in enumerate(urls, 1):
print(f"\n[{i}/{len(urls)}] Processing: {url}")
if download_image(url, images_dir):
successful += 1
else:
failed += 1
# Small delay to be respectful to the server
time.sleep(0.5)
# Summary
print(f"\n📊 Download Summary:")
print(f"✅ Successful: {successful}")
print(f"❌ Failed: {failed}")
print(f"📁 Total files: {len(list(images_dir.glob('*.jpg')))}")
# Update markdown file
if successful > 0:
print(f"\n🔄 Updating markdown file...")
update_markdown_file(images_dir)
print(f"✅ Process completed!")
print(f"💡 You can now run your app completely offline!")
else:
print(f"❌ No images were downloaded successfully")
if __name__ == "__main__":
main()

288
scripts/env-setup.bat Normal file
View File

@@ -0,0 +1,288 @@
@echo off
REM ====================================
REM SCRIPT DE CONFIGURACIÓN DE ENTORNO
REM Balotario Licencia A-I (Windows)
REM =============================
setlocal enabledelayedexpansion
REM Función para generar SECRET_KEY
:generate_secret_key
python -c "import secrets; print(secrets.token_hex(32))" 2>nul
if errorlevel 1 (
REM Fallback si Python no está disponible
echo %RANDOM%%RANDOM%%RANDOM%%RANDOM%
)
goto :eof
REM Función para mostrar header
:print_header
echo ======================================
echo 🌍 CONFIGURACIÓN DE ENTORNO
echo Balotario Licencia A-I
echo ======================================
echo.
goto :eof
REM Función para configurar desarrollo
:setup_development
echo Configurando entorno de desarrollo...
REM Generar SECRET_KEY
for /f %%i in ('python -c "import secrets; print(secrets.token_hex(32))" 2^>nul') do set SECRET_KEY=%%i
if "!SECRET_KEY!"=="" set SECRET_KEY=%RANDOM%%RANDOM%%RANDOM%%RANDOM%
REM Crear archivo .env
(
echo # ====================================
echo # CONFIGURACIÓN DE DESARROLLO
echo # Generado automáticamente: %date% %time%
echo # ====================================
echo.
echo # Configuración de Flask
echo SECRET_KEY=!SECRET_KEY!
echo FLASK_ENV=development
echo FLASK_CONFIG=development
echo FLASK_DEBUG=true
echo.
echo # Configuración del servidor
echo HOST=127.0.0.1
echo PORT=5000
echo.
echo # Configuración de Docker
echo DOCKER_CONTAINER=false
echo.
echo # Configuración de logging
echo LOG_LEVEL=DEBUG
echo AUTO_RELOAD=true
echo SHOW_DEBUG_TOOLBAR=false
echo.
echo # ====================================
echo # NOTAS:
echo # - Cambia SECRET_KEY antes de ir a producción
echo # - Revisa .env.sample para más opciones
echo # ====================================
) > .env
echo ✅ Configuración de desarrollo creada en .env
goto :eof
REM Función para configurar producción
:setup_production
echo Configurando entorno de producción...
REM Generar SECRET_KEY
for /f %%i in ('python -c "import secrets; print(secrets.token_hex(32))" 2^>nul') do set SECRET_KEY=%%i
if "!SECRET_KEY!"=="" set SECRET_KEY=%RANDOM%%RANDOM%%RANDOM%%RANDOM%
REM Crear archivo .env
(
echo # ====================================
echo # CONFIGURACIÓN DE PRODUCCIÓN
echo # Generado automáticamente: %date% %time%
echo # ====================================
echo.
echo # Configuración de Flask
echo SECRET_KEY=!SECRET_KEY!
echo FLASK_ENV=production
echo FLASK_CONFIG=production
echo FLASK_DEBUG=false
echo.
echo # Configuración del servidor
echo HOST=0.0.0.0
echo PORT=5000
echo.
echo # Configuración de Docker
echo DOCKER_CONTAINER=true
echo.
echo # Configuración de logging
echo LOG_LEVEL=INFO
echo.
echo # ====================================
echo # IMPORTANTE:
echo # - Guarda SECRET_KEY en lugar seguro
echo # - Revisa todas las configuraciones antes de desplegar
echo # ====================================
) > .env
echo ✅ Configuración de producción creada en .env
echo ⚠️ IMPORTANTE: Guarda la SECRET_KEY en un lugar seguro
goto :eof
REM Función para configurar Docker
:setup_docker
echo Configurando entorno para Docker...
REM Generar SECRET_KEY
for /f %%i in ('python -c "import secrets; print(secrets.token_hex(32))" 2^>nul') do set SECRET_KEY=%%i
if "!SECRET_KEY!"=="" set SECRET_KEY=%RANDOM%%RANDOM%%RANDOM%%RANDOM%
REM Crear archivo .env
(
echo # ====================================
echo # CONFIGURACIÓN PARA DOCKER
echo # Generado automáticamente: %date% %time%
echo # ====================================
echo.
echo # Configuración de Flask
echo SECRET_KEY=!SECRET_KEY!
echo FLASK_ENV=production
echo FLASK_CONFIG=production
echo FLASK_DEBUG=false
echo.
echo # Configuración del servidor
echo HOST=0.0.0.0
echo PORT=5000
echo.
echo # Configuración de Docker
echo DOCKER_CONTAINER=true
echo.
echo # Configuración de logging
echo LOG_LEVEL=INFO
echo.
echo # ====================================
echo # DOCKER NOTES:
echo # - Estas variables pueden ser sobrescritas en docker-compose.yml
echo # - Para desarrollo con Docker, cambia FLASK_ENV=development
echo # ====================================
) > .env
echo ✅ Configuración para Docker creada en .env
goto :eof
REM Función para validar configuración
:validate_env
echo Validando configuración...
if not exist ".env" (
echo ❌ Archivo .env no encontrado
exit /b 1
)
findstr /C:"SECRET_KEY=" .env >nul
if errorlevel 1 (
echo ❌ SECRET_KEY no encontrada en .env
exit /b 1
)
findstr /C:"FLASK_ENV=" .env >nul
if errorlevel 1 (
echo ❌ FLASK_ENV no encontrada en .env
exit /b 1
)
echo ✅ Configuración válida
echo.
echo Resumen de configuración:
echo ------------------------
for /f "tokens=1,2 delims==" %%a in ('findstr /R "^SECRET_KEY= ^FLASK_ENV= ^FLASK_DEBUG= ^HOST= ^PORT=" .env') do (
if "%%a"=="SECRET_KEY" (
echo %%a=***OCULTA***
) else (
echo %%a=%%b
)
)
goto :eof
REM Función para mostrar ayuda
:show_help
echo Uso: %~nx0 [COMANDO]
echo.
echo Comandos disponibles:
echo dev Configurar para desarrollo local
echo prod Configurar para producción
echo docker Configurar para Docker
echo validate Validar configuración actual
echo backup Crear backup de .env actual
echo restore Restaurar desde .env.sample
echo help Mostrar esta ayuda
echo.
echo Ejemplos:
echo %~nx0 dev # Configuración de desarrollo
echo %~nx0 prod # Configuración de producción
echo %~nx0 docker # Configuración para Docker
goto :eof
REM Función para crear backup
:backup_env
if exist ".env" (
set backup_file=.env.backup.%date:~-4%%date:~3,2%%date:~0,2%_%time:~0,2%%time:~3,2%%time:~6,2%
set backup_file=!backup_file: =0!
copy .env "!backup_file!" >nul
echo ✅ Backup creado: !backup_file!
) else (
echo ⚠️ No hay archivo .env para respaldar
)
goto :eof
REM Función para restaurar desde sample
:restore_env
if exist ".env.sample" (
copy .env.sample .env >nul
echo ✅ Configuración restaurada desde .env.sample
echo ⚠️ Recuerda personalizar los valores en .env
) else (
echo ❌ Archivo .env.sample no encontrado
exit /b 1
)
goto :eof
REM Función principal
:main
call :print_header
if "%1"=="" goto help
if "%1"=="dev" goto dev
if "%1"=="development" goto dev
if "%1"=="prod" goto prod
if "%1"=="production" goto prod
if "%1"=="docker" goto docker
if "%1"=="validate" goto validate
if "%1"=="check" goto validate
if "%1"=="backup" goto backup
if "%1"=="restore" goto restore
if "%1"=="help" goto help
if "%1"=="--help" goto help
if "%1"=="-h" goto help
echo ❌ Comando desconocido: %1
echo.
goto help
:dev
call :backup_env
call :setup_development
call :validate_env
goto end
:prod
call :backup_env
call :setup_production
call :validate_env
goto end
:docker
call :backup_env
call :setup_docker
call :validate_env
goto end
:validate
call :validate_env
goto end
:backup
call :backup_env
goto end
:restore
call :backup_env
call :restore_env
goto end
:help
call :show_help
goto end
:end
pause

296
scripts/env-setup.sh Executable file
View File

@@ -0,0 +1,296 @@
#!/bin/bash
# ====================================
# SCRIPT DE CONFIGURACIÓN DE ENTORNO
# Balotario Licencia A-I
# ====================================
set -e # Salir en caso de error
# Colores para output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
# Función para imprimir con colores
print_info() {
echo -e "${ $1${NC}"
}
print_success() {
echo -e "${GREEN}$1${NC}"
}
print_warning() {
echo -e "${YELLOW}⚠️ $1${NC}"
}
print_error() {
echo -e "${RED}$1${NC}"
}
print_header() {
echo -e "${BLUE}"
echo "======================================"
echo "🌍 CONFIGURACIÓN DE ENTORNO"
echo "Balotario Licencia A-I"
echo "======================================"
echo -e "${NC}"
}
# Función para generar SECRET_KEY
generate_secret_key() {
if command -v python3 &> /dev/null; then
python3 -c "import secrets; print(secrets.token_hex(32))"
elif command -v python &> /dev/null; then
python -c "import secrets; print(secrets.token_hex(32))"
elif command -v openssl &> /dev/null; then
openssl rand -hex 32
else
# Fallback básico
date +%s | sha256sum | base64 | head -c 32
fi
}
# Función para configurar desarrollo
setup_development() {
print_info "Configurando entorno de desarrollo..."
SECRET_KEY=$(generate_secret_key)
cat > .env << EOF
# ====================================
# CONFIGURACIÓN DE DESARROLLO
# Generado automáticamente: $(date)
# ====================================
# Configuración de Flask
SECRET_KEY=${SECRET_KEY}
FLASK_ENV=development
FLASK_CONFIG=development
FLASK_DEBUG=true
# Configuración del servidor
HOST=127.0.0.1
PORT=5000
# Configuración de Docker
DOCKER_CONTAINER=false
# Configuración de logging
LOG_LEVEL=DEBUG
AUTO_RELOAD=true
SHOW_DEBUG_TOOLBAR=false
# ====================================
# NOTAS:
# - Cambia SECRET_KEY antes de ir a producción
# - Revisa .env.sample para más opciones
# ====================================
EOF
print_success "Configuración de desarrollo creada en .env"
}
# Función para configurar producción
setup_production() {
print_info "Configurando entorno de producción..."
SECRET_KEY=$(generate_secret_key)
cat > .env << EOF
# ====================================
# CONFIGURACIÓN DE PRODUCCIÓN
# Generado automáticamente: $(date)
# ====================================
# Configuración de Flask
SECRET_KEY=${SECRET_KEY}
FLASK_ENV=production
FLASK_CONFIG=production
FLASK_DEBUG=false
# Configuración del servidor
HOST=0.0.0.0
PORT=5000
# Configuración de Docker
DOCKER_CONTAINER=true
# Configuración de logging
LOG_LEVEL=INFO
# ====================================
# IMPORTANTE:
# - Guarda SECRET_KEY en lugar seguro
# - Revisa todas las configuraciones antes de desplegar
# - Considera usar variables de entorno del sistema
# ====================================
EOF
print_success "Configuración de producción creada en .env"
print_warning "IMPORTANTE: Guarda la SECRET_KEY en un lugar seguro"
}
# Función para configurar Docker
setup_docker() {
print_info "Configurando entorno para Docker..."
SECRET_KEY=$(generate_secret_key)
cat > .env << EOF
# ====================================
# CONFIGURACIÓN PARA DOCKER
# Generado automáticamente: $(date)
# ====================================
# Configuración de Flask
SECRET_KEY=${SECRET_KEY}
FLASK_ENV=production
FLASK_CONFIG=production
FLASK_DEBUG=false
# Configuración del servidor
HOST=0.0.0.0
PORT=5000
# Configuración de Docker
DOCKER_CONTAINER=true
# Configuración de logging
LOG_LEVEL=INFO
# ====================================
# DOCKER NOTES:
# - Estas variables pueden ser sobrescritas en docker-compose.yml
# - Para desarrollo con Docker, cambia FLASK_ENV=development
# ====================================
EOF
print_success "Configuración para Docker creada en .env"
}
# Función para validar configuración
validate_env() {
print_info "Validando configuración..."
if [ ! -f ".env" ]; then
print_error "Archivo .env no encontrado"
return 1
fi
# Verificar variables esenciales
if ! grep -q "SECRET_KEY=" .env; then
print_error "SECRET_KEY no encontrada en .env"
return 1
fi
if ! grep -q "FLASK_ENV=" .env; then
print_error "FLASK_ENV no encontrada en .env"
return 1
fi
print_success "Configuración válida"
# Mostrar resumen
echo ""
print_info "Resumen de configuración:"
echo "------------------------"
grep -E "^(SECRET_KEY|FLASK_ENV|FLASK_DEBUG|HOST|PORT)=" .env | while read line; do
key=$(echo $line | cut -d'=' -f1)
value=$(echo $line | cut -d'=' -f2)
if [ "$key" = "SECRET_KEY" ]; then
echo " $key=***OCULTA***"
else
echo " $key=$value"
fi
done
}
# Función para mostrar ayuda
show_help() {
echo "Uso: $0 [COMANDO]"
echo ""
echo "Comandos disponibles:"
echo " dev Configurar para desarrollo local"
echo " prod Configurar para producción"
echo " docker Configurar para Docker"
echo " validate Validar configuración actual"
echo " backup Crear backup de .env actual"
echo " restore Restaurar desde .env.sample"
echo " help Mostrar esta ayuda"
echo ""
echo "Ejemplos:"
echo " $0 dev # Configuración de desarrollo"
echo " $0 prod # Configuración de producción"
echo " $0 docker # Configuración para Docker"
}
# Función para crear backup
backup_env() {
if [ -f ".env" ]; then
backup_file=".env.backup.$(date +%Y%m%d_%H%M%S)"
cp .env "$backup_file"
print_success "Backup creado: $backup_file"
else
print_warning "No hay archivo .env para respaldar"
fi
}
# Función para restaurar desde sample
restore_env() {
if [ -f ".env.sample" ]; then
cp .env.sample .env
print_success "Configuración restaurada desde .env.sample"
print_warning "Recuerda personalizar los valores en .env"
else
print_error "Archivo .env.sample no encontrado"
return 1
fi
}
# Función principal
main() {
print_header
case "${1:-help}" in
"dev"|"development")
backup_env
setup_development
validate_env
;;
"prod"|"production")
backup_env
setup_production
validate_env
;;
"docker")
backup_env
setup_docker
validate_env
;;
"validate"|"check")
validate_env
;;
"backup")
backup_env
;;
"restore")
backup_env
restore_env
;;
"help"|"--help"|"-h")
show_help
;;
*)
print_error "Comando desconocido: $1"
echo ""
show_help
exit 1
;;
esac
}
# Ejecutar función principal
main "$@"

85
scripts/verify_images.py Normal file
View File

@@ -0,0 +1,85 @@
#!/usr/bin/env python3
"""
Script to verify that all local images are available and working.
"""
import os
import re
from pathlib import Path
def verify_local_images():
"""Verify that all referenced images exist locally."""
markdown_file = Path("data/balotario_clase_a_cat_I.md")
images_dir = Path("static/images")
if not markdown_file.exists():
print(f"❌ Markdown file not found: {markdown_file}")
return False
if not images_dir.exists():
print(f"❌ Images directory not found: {images_dir}")
return False
# Read markdown content
with open(markdown_file, 'r', encoding='utf-8') as f:
content = f.read()
# Find all local image references
pattern = r'!\[\]\(/static/images/(img\d+\.jpg)\)'
referenced_images = re.findall(pattern, content)
print(f"🔍 Found {len(referenced_images)} image references in markdown")
# Check if all referenced images exist
missing_images = []
existing_images = []
for img_name in referenced_images:
img_path = images_dir / img_name
if img_path.exists():
existing_images.append(img_name)
print(f"{img_name} - {img_path.stat().st_size} bytes")
else:
missing_images.append(img_name)
print(f"{img_name} - NOT FOUND")
# Check for extra images
all_local_images = list(images_dir.glob("*.jpg"))
extra_images = []
for img_path in all_local_images:
if img_path.name not in referenced_images:
extra_images.append(img_path.name)
# Summary
print(f"\n📊 Verification Summary:")
print(f"✅ Images found: {len(existing_images)}")
print(f"❌ Images missing: {len(missing_images)}")
print(f"📁 Total local images: {len(all_local_images)}")
print(f" Extra images: {len(extra_images)}")
if missing_images:
print(f"\n❌ Missing images:")
for img in missing_images:
print(f" - {img}")
if extra_images:
print(f"\n Extra images (not referenced):")
for img in extra_images:
print(f" - {img}")
# Calculate total size
total_size = sum(img.stat().st_size for img in all_local_images)
print(f"\n💾 Total images size: {total_size / 1024 / 1024:.2f} MB")
return len(missing_images) == 0
if __name__ == "__main__":
print("🔍 Verifying local images...")
success = verify_local_images()
if success:
print("\n🎉 All images are available locally!")
print("💡 Your app can now run completely offline!")
else:
print("\n⚠️ Some images are missing. Run download_images.py to fix this.")

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

798
static/css/custom.css Normal file
View File

@@ -0,0 +1,798 @@
/* Estilos personalizados para el Balotario */
:root {
--primary-color: #2c3e50;
--secondary-color: #3498db;
--success-color: #27ae60;
--danger-color: #e74c3c;
--warning-color: #f39c1
-light-bg: #ecf0f1;
--gradient-primary: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
--gradient-success: linear-gradient(45deg, #27ae60, #58d68d);
--gradient-danger: linear-gradient(45deg, #e74c3c, #ec7063);
--gradient-warning: linear-gradient(45deg, #f39c12, #f7dc6f);
}
/* Animaciones personalizadas */
@keyframes pulse {
0% { transform: scale(1); }
50% { transform: scale(1.05); }
100% { transform: scale(1); }
}
@keyframes slideInUp {
from {
opacity: 0;
transform: translateY(30px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
@keyframes fadeInScale {
from {
opacity: 0;
transform: scale(0.9);
}
to {
opacity: 1;
transform: scale(1);
}
}
/* Efectos de hover mejorados */
.card-hover {
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}
.card-hover:hover {
transform: translateY(-8px);
box-shadow: 0 20px 40px rgba(0,0,0,0.15);
}
/* Botones con efectos especiales */
.btn-glow {
position: relative;
overflow: hidden;
}
.btn-glow::before {
content: '';
position: absolute;
top: 0;
left: -100%;
width: 100%;
height: 100%;
background: linear-gradient(90deg, transparent, rgba(255,255,255,0.3), transparent);
transition: left 0.5s;
}
.btn-glow:hover::before {
left: 100%;
}
/* Indicadores de progreso mejorados */
.progress-ring {
width: 120px;
height: 120px;
position: relative;
}
.progress-ring svg {
width: 100%;
height: 100%;
transform: rotate(-90deg);
}
.progress-ring circle {
fill: none;
stroke-width: 8;
stroke-linecap: round;
}
.progress-ring .bg {
stroke: rgba(255,255,255,0.2);
}
.progress-ring .progress {
stroke: #fff;
stroke-dasharray: 283;
stroke-dashoffset: 283;
transition: stroke-dashoffset 0.5s ease-in-out;
}
/* Efectos de texto */
.text-glow {
text-shadow: 0 0 10px rgba(255,255,255,0.5);
}
.text-gradient {
background: linear-gradient(45deg, #667eea, #764ba2);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
}
/* Tarjetas de preguntas mejoradas - tema claro por defecto */
.question-card-enhanced {
background: white;
color: #333333;
border-radius: 20px;
padding: 2.5rem;
margin-bottom: 2rem;
box-shadow: 0 15px 35px rgba(0,0,0,0.1);
position: relative;
overflow: hidden;
}
.question-card-enhanced::before {
content: '';
position: absolute;
top: 0;
left: 0;
right: 0;
height: 4px;
background: var(--gradient-primary);
}
/* Opciones de respuesta mejoradas */
.option-enhanced {
background: white;
border: 2px solid #e9ecef;
border-radius: 15px;
padding: 20px;
margin-bottom: 15px;
transition: all 0.3s ease;
cursor: pointer;
position: relative;
overflow: hidden;
}
.option-enhanced::before {
content: '';
position: absolute;
top: 0;
left: -100%;
width: 100%;
height: 100%;
background: linear-gradient(90deg, transparent, rgba(52, 152, 219, 0.1), transparent);
transition: left 0.3s ease;
pointer-events: none;
}
.option-enhanced:hover::before {
left: 100%;
}
.option-enhanced:hover {
border-color: var(--secondary-color);
transform: translateX(5px);
box-shadow: 0 8px 25px rgba(52, 152, 219, 0.2);
}
.option-enhanced.selected {
border-color: var(--secondary-color);
background: rgba(52, 152, 219, 0.25);
transform: translateX(5px);
box-shadow: 0 4px 15px rgba(52, 152, 219, 0.3);
}
.option-enhanced.correct {
border-color: var(--success-color);
background: rgba(39, 174, 96, 0.25);
animation: pulse 0.6s ease-in-out;
color: #1e5631;
font-weight: 600;
}
.option-enhanced.incorrect {
border-color: var(--danger-color);
background: rgba(231, 76, 60, 0.25);
color: #721c24;
font-weight: 600;
}
/* Navegador de preguntas mejorado */
.question-navigator {
background: rgba(255,255,255,0.95);
backdrop-filter: blur(10px);
border-radius: 15px;
padding: 1.5rem;
box-shadow: 0 8px 25px rgba(0,0,0,0.1);
}
.nav-question-btn {
width: 45px;
height: 45px;
border-radius: 50%;
border: 2px solid #e9ecef;
background: white;
display: flex;
align-items: center;
justify-content: center;
font-weight: 600;
transition: all 0.3s ease;
margin: 5px;
}
.nav-question-btn:hover {
transform: scale(1.1);
box-shadow: 0 5px 15px rgba(0,0,0,0.2);
}
.nav-question-btn.answered {
background: var(--gradient-success);
border-color: var(--success-color);
color: white;
}
.nav-question-btn.current {
background: var(--gradient-primary);
border-color: var(--secondary-color);
color: white;
animation: pulse 2s infinite;
}
/* Timer mejorado */
.timer-display {
background: var(--gradient-warning);
color: white;
padding: 15px 25px;
border-radius: 25px;
font-size: 1.5rem;
font-weight: bold;
text-align: center;
box-shadow: 0 8px 25px rgba(243, 156, 18, 0.3);
position: relative;
}
.timer-display.warning {
background: var(--gradient-danger);
animation: pulse 1s infinite;
}
/* Estadísticas mejoradas */
.stats-enhanced {
background: var(--gradient-primary);
color: white;
border-radius: 20px;
padding: 2rem;
text-align: center;
position: relative;
overflow: hidden;
}
.stats-enhanced::before {
content: '';
position: absolute;
top: -50%;
left: -50%;
width: 200%;
height: 200%;
background: radial-gradient(circle, rgba(255,255,255,0.1) 0%, transparent 70%);
animation: rotate 20s linear infinite;
}
@keyframes rotate {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
.stats-number {
font-size: 2.5rem;
font-weight: bold;
text-shadow: 0 2px 4px rgba(0,0,0,0.3);
}
/* Responsive mejoras */
@media (max-width: 768px) {
.question-card-enhanced {
padding: 1.5rem;
margin-bottom: 1.5rem;
}
.option-enhanced {
padding: 15px;
margin-bottom: 10px;
}
.nav-question-btn {
width: 40px;
height: 40px;
margin: 3px;
}
.timer-display {
font-size: 1.2rem;
padding: 10px 20px;
}
}
/* Tema claro - respuestas seleccionadas más intensas */
[data-theme="light"] .option-enhanced.selected,
:root:not([data-theme="dark"]) .option-enhanced.selected {
border-color: var(--secondary-color);
background: rgba(52, 152, 219, 0.35);
transform: translateX(5px);
box-shadow: 0 6px 20px rgba(52, 152, 219, 0.4);
border-width: 3px;
}
[data-theme="light"] .option-btn.selected,
:root:not([data-theme="dark"]) .option-btn.selected {
background: rgba(52, 152, 219, 0.35) !important;
border-color: var(--secondary-color) !important;
box-shadow: 0 6px 20px rgba(52, 152, 219, 0.4) !important;
border-width: 3px !important;
}
/* Tema claro - respuestas correctas más intensas */
[data-theme="light"] .option-enhanced.correct,
:root:not([data-theme="dark"]) .option-enhanced.correct {
border-color: #1e7e34;
background: rgba(39, 174, 96, 0.4);
color: #0d4016;
font-weight: 700;
border-width: 3px;
box-shadow: 0 6px 20px rgba(39, 174, 96, 0.3);
}
[data-theme="light"] .option-btn.correct,
:root:not([data-theme="dark"]) .option-btn.correct {
background: rgba(39, 174, 96, 0.4) !important;
border-color: #1e7e34 !important;
color: #0d4016 !important;
font-weight: 700 !important;
border-width: 3px !important;
box-shadow: 0 6px 20px rgba(39, 174, 96, 0.3) !important;
}
/* Tema claro - respuestas incorrectas más intensas */
[data-theme="light"] .option-enhanced.incorrect,
:root:not([data-theme="dark"]) .option-enhanced.incorrect {
border-color: #c82333;
background: rgba(231, 76, 60, 0.4);
color: #721c24;
font-weight: 700;
border-width: 3px;
box-shadow: 0 6px 20px rgba(231, 76, 60, 0.3);
}
[data-theme="light"] .option-btn.incorrect,
:root:not([data-theme="dark"]) .option-btn.incorrect {
background: rgba(231, 76, 60, 0.4) !important;
border-color: #c82333 !important;
color: #721c24 !important;
font-weight: 700 !important;
border-width: 3px !important;
box-shadow: 0 6px 20px rgba(231, 76, 60, 0.3) !important;
}
/* Modal support for light theme - ensuring proper styling */
[data-theme="light"] .modal-content,
:root:not([data-theme="dark"]) .modal-content {
background: #ffffff !important;
color: #333333 !important;
border: 1px solid #dee2e6 !important;
}
[data-theme="light"] .modal-header,
:root:not([data-theme="dark"]) .modal-header {
border-bottom-color: #dee2e6 !important;
}
[data-theme="light"] .modal-footer,
:root:not([data-theme="dark"]) .modal-footer {
border-top-color: #dee2e6 !important;
}
[data-theme="light"] .modal-title,
:root:not([data-theme="dark"]) .modal-title {
color: #333333 !important;
}
/* Tema claro - question cards */
[data-theme="light"] .question-card-enhanced,
:root:not([data-theme="dark"]) .question-card-enhanced {
background: white !important;
color: #333333 !important;
box-shadow: 0 15px 35px rgba(0,0,0,0.1) !important;
}
[data-theme="light"] .question-card,
:root:not([data-theme="dark"]) .question-card {
background: white !important;
color: #333333 !important;
}
/* Modo oscuro */
[data-theme="dark"] {
background: #1a1a1a !important;
color: #e0e0e0 !important;
}
[data-theme="dark"] body {
background: linear-gradient(135deg, #2c3e50 0%, #34495e 100%) !important;
color: #e0e0e0 !important;
}
[data-theme="dark"] .container-main {
background: rgba(44, 62, 80, 0.95) !important;
color: #e0e0e0 !important;
}
[data-theme="dark"] .card {
background: #34495e !important;
color: #e0e0e0 !important;
border-color: #4a5f7a !important;
}
[data-theme="dark"] .question-card,
[data-theme="dark"] .question-card-enhanced {
background: #34495e !important;
color: #e0e0e0 !important;
}
[data-theme="dark"] .option-btn,
[data-theme="dark"] .option-enhanced {
background: #2c3e50 !important;
border-color: #4a5f7a !important;
color: #e0e0e0 !important;
}
[data-theme="dark"] .option-btn:hover,
[data-theme="dark"] .option-enhanced:hover {
background: #3d566e !important;
border-color: var(--secondary-color) !important;
}
[data-theme="dark"] .option-btn.correct,
[data-theme="dark"] .option-enhanced.correct {
background: rgba(39, 174, 96, 0.3) !important;
border-color: #27ae60 !important;
color: #ffffff !important;
}
[data-theme="dark"] .option-btn.incorrect,
[data-theme="dark"] .option-enhanced.incorrect {
background: rgba(231, 76, 60, 0.3) !important;
border-color: #e74c3c !important;
color: #ffffff !important;
}
[data-theme="dark"] .option-btn.selected,
[data-theme="dark"] .option-enhanced.selected {
background: rgba(52, 152, 219, 0.3) !important;
border-color: #3498db !important;
color: #ffffff !important;
}
[data-theme="dark"] .navbar {
background: rgba(26, 26, 26, 0.95) !important;
}
[data-theme="dark"] .form-control,
[data-theme="dark"] .form-select {
background: #2c3e50 !important;
border-color: #4a5f7a !important;
color: #e0e0e0 !important;
}
[data-theme="dark"] .form-control:focus,
[data-theme="dark"] .form-select:focus {
background: #34495e !important;
border-color: var(--secondary-color) !important;
color: #e0e0e0 !important;
box-shadow: 0 0 0 0.2rem rgba(52, 152, 219, 0.25) !important;
}
[data-theme="dark"] .alert-success {
background: rgba(39, 174, 96, 0.2) !important;
border-color: var(--success-color) !important;
color: #e0e0e0 !important;
}
[data-theme="dark"] .alert-danger {
background: rgba(231, 76, 60, 0.2) !important;
border-color: var(--danger-color) !important;
color: #e0e0e0 !important;
}
[data-theme="dark"] .badge {
color: #fff !important;
}
[data-theme="dark"] .text-muted {
color: #bbb !important;
}
[data-theme="dark"] .correct-option {
background: rgba(39, 174, 96, 0.4) !important;
border-color: #27ae60 !important;
color: #ffffff !important;
}
[data-theme="dark"] .answer-indicator {
color: #27ae60 !important;
}
[data-theme="dark"] .fa-check-circle {
color: #27ae60 !important;
}
[data-theme="dark"] .text-success {
color: #2ecc71 !important;
}
[data-theme="dark"] .text-danger {
color: #e74c3c !important;
}
[data-theme="dark"] .text-warning {
color: #f39c12 !important;
}
[data-theme="dark"] .text-primary {
color: #3498db !important;
}
/* Modal support for dark theme */
[data-theme="dark"] .modal-content {
background: #2c3e50 !important;
color: #e0e0e0 !important;
border: 1px solid #4a5f7a !important;
}
[data-theme="dark"] .modal-header {
border-bottom-color: #4a5f7a !important;
}
[data-theme="dark"] .modal-footer {
border-top-color: #4a5f7a !important;
}
[data-theme="dark"] .modal-title {
color: #e0e0e0 !important;
}
[data-theme="dark"] .btn-close {
filter: invert(1) grayscale(100%) brightness(200%);
}
/* Buttons in dark theme */
[data-theme="dark"] .btn-secondary {
background: #4a5f7a !important;
border-color: #4a5f7a !important;
color: #e0e0e0 !important;
}
[data-theme="dark"] .btn-secondary:hover {
background: #5a6f8a !important;
border-color: #5a6f8a !important;
}
[data-theme="dark"] .btn-outline-secondary {
border-color: #4a5f7a !important;
color: #e0e0e0 !important;
}
[data-theme="dark"] .btn-outline-secondary:hover {
background: #4a5f7a !important;
border-color: #4a5f7a !important;
color: #ffffff !important;
}
[data-theme="dark"] .btn-outline-primary {
border-color: var(--secondary-color) !important;
color: var(--secondary-color) !important;
}
[data-theme="dark"] .btn-outline-primary:hover {
background: var(--secondary-color) !important;
border-color: var(--secondary-color) !important;
color: #ffffff !important;
}
/* Progress bars in dark theme */
[data-theme="dark"] .progress {
background: rgba(255, 255, 255, 0.1) !important;
}
/* Badges in dark theme */
[data-theme="dark"] .badge.bg-warning {
background: var(--warning-color) !important;
color: #ffffff !important;
}
[data-theme="dark"] .badge.bg-success {
background: var(--success-color) !important;
color: #ffffff !important;
}
[data-theme="dark"] .badge.bg-primary {
background: var(--secondary-color) !important;
color: #ffffff !important;
}
/* Question navigator buttons in dark theme */
[data-theme="dark"] .question-nav-btn,
[data-theme="dark"] .nav-question-btn {
background: #2c3e50 !important;
border-color: #4a5f7a !important;
color: #e0e0e0 !important;
}
[data-theme="dark"] .question-nav-btn:hover,
[data-theme="dark"] .nav-question-btn:hover {
background: #3d566e !important;
border-color: var(--secondary-color) !important;
}
[data-theme="dark"] .question-nav-btn.btn-success,
[data-theme="dark"] .nav-question-btn.answered {
background: var(--success-color) !important;
border-color: var(--success-color) !important;
color: #ffffff !important;
}
[data-theme="dark"] .question-nav-btn.btn-primary,
[data-theme="dark"] .nav-question-btn.current {
background: var(--secondary-color) !important;
border-color: var(--secondary-color) !important;
color: #ffffff !important;
}
/* Timer and other exam elements */
[data-theme="dark"] .timer-display {
background: var(--gradient-warning) !important;
color: #ffffff !important;
}
[data-theme="dark"] .timer-display.warning {
background: var(--gradient-danger) !important;
}
/* Question navigator card */
[data-theme="dark"] .question-navigator {
background: rgba(44, 62, 80, 0.95) !important;
color: #e0e0e0 !important;
}
/* Modal theme support only - no interference with Bootstrap functionality */
/* Modal with reasonable z-index */
.modal {
z-index: 1055;
}
.modal-backdrop {
z-index: 1050;
}
/* Custom modal styling */
#confirmModal {
z-index: 1055;
}
#confirmBackdrop {
z-index: 1050;
}
#confirmDialog {
z-index: 1055;
}
/* Prevent scroll when modal is open */
body.modal-open {
overflow: hidden;
}
/* Ensure modal doesn't cause horizontal scroll */
#confirmModal {
overflow-x: hidden;
overflow-y: auto;
}
#confirmDialog {
margin: 20px;
max-width: calc(100vw - 40px);
max-height: calc(100vh - 40px);
}
/* Force modal to be centered and visible */
#confirmModal.show {
top: 50% !important;
left: 50% !important;
transform: translate(-50%, -50%) !important;
margin: 0 !important;
width: auto !important;
height: auto !important;
}
#confirmModal .modal-dialog {
margin: 0 !important;
position: relative !important;
}
/* Ensure backdrop covers entire screen */
.modal-backdrop.show {
position: fixed !important;
top: 0 !important;
left: 0 !important;
width: 100vw !important;
height: 100vh !important;
background-color: rgba(0, 0, 0, 0.5) !important;
}
/* Custom modal theme support */
[data-theme="dark"] #confirmDialog {
background: #2c3e50 !important;
color: #e0e0e0 !important;
}
[data-theme="dark"] #confirmDialog h5 {
color: #e0e0e0 !important;
}
[data-theme="dark"] #confirmDialog p {
color: #e0e0e0 !important;
}
[data-theme="dark"] #confirmDialog #confirm-message {
color: #e0e0e0 !important;
}
[data-theme="dark"] #confirmModalClose {
color: #e0e0e0 !important;
}
/* Modo oscuro automático removido para evitar conflictos */
/* Efectos de carga */
.loading-dots {
display: inline-block;
}
.loading-dots::after {
content: '';
animation: dots 1.5s steps(5, end) infinite;
}
@keyframes dots {
0%, 20% { content: ''; }
40% { content: '.'; }
60% { content: '..'; }
80%, 100% { content: '...'; }
}
/* Confetti effect para celebrar */
.confetti {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
pointer-events: none;
z-index: 1040;
}
.confetti-piece {
position: absolute;
width: 10px;
height: 10px;
background: #f39c12;
animation: confetti-fall 3s linear infinite;
}
@keyframes confetti-fall {
0% {
transform: translateY(-100vh) rotate(0deg);
opacity: 1;
}
100% {
transform: translateY(100vh) rotate(720deg);
opacity: 0;
}
}

View File

@@ -0,0 +1,252 @@
/* Font Awesome Local CSS */
@font-face {
font-family: "Font Awesome 6 Free";
font-style: normal;
font-weight: 900;
font-display: swap;
src: url("../fonts/fa-solid-900.woff2") format("woff2");
}
.fa,
.fas {
font-family: "Font Awesome 6 Free";
font-weight: 900;
font-style: normal;
font-variant: normal;
text-rendering: auto;
line-height: 1;
-webkit-font-smoothing: antialias
-moz-osx-font-smoothing: grayscale;
}
/* Core Font Awesome Icons */
.fa-home:before { content: "\f015"; }
.fa-book:before { content: "\f02d"; }
.fa-dumbbell:before { content: "\f44b"; }
.fa-clipboard-check:before { content: "\f46c"; }
.fa-car:before { content: "\f1b9"; }
.fa-moon:before { content: "\f186"; }
.fa-sun:before { content: "\f185"; }
.fa-check-circle:before { content: "\f058"; }
.fa-times-circle:before { content: "\f057"; }
.fa-arrow-left:before { content: "\f060"; }
.fa-arrow-right:before { content: "\f061"; }
.fa-play:before { content: "\f04b"; }
.fa-pause:before { content: "\f04c"; }
.fa-stop:before { content: "\f04d"; }
.fa-refresh:before { content: "\f021"; }
.fa-reset:before { content: "\f021"; }
.fa-redo:before { content: "\f01e"; }
.fa-chart-bar:before { content: "\f080"; }
.fa-trophy:before { content: "\f091"; }
.fa-star:before { content: "\f005"; }
.fa-clock:before { content: "\f017"; }
.fa-question:before { content: "\f128"; }
.fa-info:before { content: "\f129"; }
.fa-exclamation:before { content: "\f12a"; }
.fa-warning:before { content: "\f071"; }
.fa-exclamation-triangle:before { content: "\f071"; }
.fa-check:before { content: "\f00c"; }
.fa-times:before { content: "\f00d"; }
.fa-plus:before { content: "\f067"; }
.fa-minus:before { content: "\f068"; }
.fa-edit:before { content: "\f044"; }
.fa-trash:before { content: "\f1f8"; }
.fa-save:before { content: "\f0c7"; }
.fa-download:before { content: "\f019"; }
.fa-upload:before { content: "\f093"; }
.fa-search:before { content: "\f002"; }
.fa-filter:before { content: "\f0b0"; }
.fa-sort:before { content: "\f0dc"; }
.fa-list:before { content: "\f03a"; }
.fa-th:before { content: "\f00a"; }
.fa-th-list:before { content: "\f00b"; }
.fa-bars:before { content: "\f0c9"; }
.fa-cog:before { content: "\f013"; }
.fa-gear:before { content: "\f013"; }
.fa-settings:before { content: "\f013"; }
.fa-user:before { content: "\f007"; }
.fa-users:before { content: "\f0c0"; }
.fa-envelope:before { content: "\f0e0"; }
.fa-phone:before { content: "\f095"; }
.fa-calendar:before { content: "\f073"; }
.fa-folder:before { content: "\f07b"; }
.fa-file:before { content: "\f15b"; }
.fa-image:before { content: "\f03e"; }
.fa-video:before { content: "\f03d"; }
.fa-music:before { content: "\f001"; }
.fa-volume-up:before { content: "\f028"; }
.fa-volume-down:before { content: "\f027"; }
.fa-volume-off:before { content: "\f026"; }
.fa-mute:before { content: "\f131"; }
.fa-heart:before { content: "\f004"; }
.fa-thumbs-up:before { content: "\f164"; }
.fa-thumbs-down:before { content: "\f165"; }
.fa-share:before { content: "\f064"; }
.fa-print:before { content: "\f02f"; }
.fa-copy:before { content: "\f0c5"; }
.fa-cut:before { content: "\f0c4"; }
.fa-paste:before { content: "\f0ea"; }
.fa-undo:before { content: "\f0e2"; }
.fa-forward:before { content: "\f04e"; }
.fa-backward:before { content: "\f04a"; }
.fa-step-forward:before { content: "\f051"; }
.fa-step-backward:before { content: "\f048"; }
.fa-fast-forward:before { content: "\f050"; }
.fa-fast-backward:before { content: "\f049"; }
.fa-random:before { content: "\f074"; }
.fa-shuffle:before { content: "\f074"; }
.fa-repeat:before { content: "\f01e"; }
.fa-lock:before { content: "\f023"; }
.fa-unlock:before { content: "\f09c"; }
.fa-key:before { content: "\f084"; }
.fa-shield:before { content: "\f132"; }
.fa-eye:before { content: "\f06e"; }
.fa-eye-slash:before { content: "\f070"; }
.fa-lightbulb:before { content: "\f0eb"; }
.fa-bell:before { content: "\f0f3"; }
.fa-bell-slash:before { content: "\f1f6"; }
.fa-flag:before { content: "\f024"; }
.fa-bookmark:before { content: "\f02e"; }
.fa-tag:before { content: "\f02b"; }
.fa-tags:before { content: "\f02c"; }
.fa-comment:before { content: "\f075"; }
.fa-comments:before { content: "\f086"; }
.fa-quote-left:before { content: "\f10d"; }
.fa-quote-right:before { content: "\f10e"; }
.fa-link:before { content: "\f0c1"; }
.fa-unlink:before { content: "\f127"; }
.fa-external-link:before { content: "\f08e"; }
.fa-external-link-alt:before { content: "\f35d"; }
.fa-anchor:before { content: "\f13d"; }
.fa-globe:before { content: "\f0ac"; }
.fa-language:before { content: "\f1ab"; }
.fa-map:before { content: "\f279"; }
.fa-map-marker:before { content: "\f041"; }
.fa-location:before { content: "\f041"; }
.fa-compass:before { content: "\f14e"; }
.fa-road:before { content: "\f018"; }
.fa-plane:before { content: "\f072"; }
.fa-train:before { content: "\f238"; }
.fa-bus:before { content: "\f207"; }
.fa-taxi:before { content: "\f1ba"; }
.fa-bicycle:before { content: "\f206"; }
.fa-motorcycle:before { content: "\f21c"; }
.fa-truck:before { content: "\f0d1"; }
.fa-ship:before { content: "\f21a"; }
.fa-rocket:before { content: "\f135"; }
.fa-fire:before { content: "\f06d"; }
.fa-bolt:before { content: "\f0e7"; }
.fa-lightning:before { content: "\f0e7"; }
.fa-magic:before { content: "\f0d0"; }
.fa-wand:before { content: "\f0d0"; }
.fa-gift:before { content: "\f06b"; }
.fa-birthday-cake:before { content: "\f1fd"; }
.fa-cake:before { content: "\f1fd"; }
.fa-coffee:before { content: "\f0f4"; }
.fa-beer:before { content: "\f0fc"; }
.fa-wine:before { content: "\f72f"; }
.fa-utensils:before { content: "\f2e7"; }
.fa-cutlery:before { content: "\f0f5"; }
.fa-shopping-cart:before { content: "\f07a"; }
.fa-credit-card:before { content: "\f09d"; }
.fa-money:before { content: "\f0d6"; }
.fa-dollar:before { content: "\f155"; }
.fa-euro:before { content: "\f153"; }
.fa-pound:before { content: "\f154"; }
.fa-yen:before { content: "\f157"; }
.fa-bitcoin:before { content: "\f379"; }
.fa-bank:before { content: "\f19c"; }
.fa-building:before { content: "\f1ad"; }
.fa-hospital:before { content: "\f0f8"; }
.fa-school:before { content: "\f549"; }
.fa-university:before { content: "\f19c"; }
.fa-graduation-cap:before { content: "\f19d"; }
.fa-briefcase:before { content: "\f0b1"; }
.fa-suitcase:before { content: "\f0f2"; }
.fa-laptop:before { content: "\f109"; }
.fa-desktop:before { content: "\f108"; }
.fa-tablet:before { content: "\f10a"; }
.fa-mobile:before { content: "\f10b"; }
.fa-phone-alt:before { content: "\f879"; }
.fa-keyboard:before { content: "\f11c"; }
.fa-mouse:before { content: "\f8cc"; }
.fa-gamepad:before { content: "\f11b"; }
.fa-tv:before { content: "\f26c"; }
.fa-camera:before { content: "\f030"; }
.fa-microphone:before { content: "\f130"; }
.fa-headphones:before { content: "\f025"; }
.fa-speaker:before { content: "\f028"; }
.fa-battery-full:before { content: "\f240"; }
.fa-battery-half:before { content: "\f242"; }
.fa-battery-empty:before { content: "\f244"; }
.fa-plug:before { content: "\f1e6"; }
.fa-wifi:before { content: "\f1eb"; }
.fa-signal:before { content: "\f012"; }
.fa-bluetooth:before { content: "\f293"; }
.fa-usb:before { content: "\f287"; }
.fa-cloud:before { content: "\f0c2"; }
.fa-cloud-upload:before { content: "\f0ee"; }
.fa-cloud-download:before { content: "\f0ed"; }
.fa-database:before { content: "\f1c0"; }
.fa-server:before { content: "\f233"; }
.fa-code:before { content: "\f121"; }
.fa-terminal:before { content: "\f120"; }
.fa-bug:before { content: "\f188"; }
.fa-wrench:before { content: "\f0ad"; }
.fa-hammer:before { content: "\f6e3"; }
.fa-screwdriver:before { content: "\f54a"; }
.fa-tools:before { content: "\f7d9"; }
.fa-paint-brush:before { content: "\f1fc"; }
.fa-palette:before { content: "\f53f"; }
.fa-ruler:before { content: "\f545"; }
.fa-calculator:before { content: "\f1ec"; }
.fa-balance-scale:before { content: "\f24e"; }
.fa-thermometer:before { content: "\f491"; }
.fa-stopwatch:before { content: "\f2f2"; }
.fa-timer:before { content: "\f2f2"; }
.fa-hourglass:before { content: "\f254"; }
.fa-history:before { content: "\f1da"; }
.fa-calendar-alt:before { content: "\f073"; }
.fa-calendar-check:before { content: "\f274"; }
.fa-calendar-times:before { content: "\f273"; }
.fa-calendar-plus:before { content: "\f271"; }
.fa-calendar-minus:before { content: "\f272"; }
.fa-sticky-note:before { content: "\f249"; }
.fa-paperclip:before { content: "\f0c6"; }
.fa-pushpin:before { content: "\f08d"; }
.fa-thumbtack:before { content: "\f08d"; }
.fa-eraser:before { content: "\f12d"; }
.fa-pen:before { content: "\f304"; }
.fa-pencil:before { content: "\f040"; }
.fa-marker:before { content: "\f5a1"; }
.fa-highlighter:before { content: "\f591"; }
.fa-ruler-combined:before { content: "\f546"; }
.fa-compass-drafting:before { content: "\f568"; }
.fa-drafting-compass:before { content: "\f568"; }
.fa-square:before { content: "\f0c8"; }
.fa-circle:before { content: "\f111"; }
.fa-triangle:before { content: "\f2ec"; }
.fa-polygon:before { content: "\f2ec"; }
.fa-shapes:before { content: "\f61f"; }
.fa-cube:before { content: "\f1b2"; }
.fa-cubes:before { content: "\f1b3"; }
.fa-dice:before { content: "\f522"; }
.fa-dice-one:before { content: "\f525"; }
.fa-dice-two:before { content: "\f528"; }
.fa-dice-three:before { content: "\f527"; }
.fa-dice-four:before { content: "\f524"; }
.fa-dice-five:before { content: "\f523"; }
.fa-dice-six:before { content: "\f526"; }
.fa-chess:before { content: "\f439"; }
.fa-chess-king:before { content: "\f43f"; }
.fa-chess-queen:before { content: "\f445"; }
.fa-chess-rook:before { content: "\f447"; }
.fa-chess-bishop:before { content: "\f43a"; }
.fa-chess-knight:before { content: "\f441"; }
.fa-chess-pawn:before { content: "\f443"; }
.fa-puzzle-piece:before { content: "\f12e"; }
.fa-jigsaw:before { content: "\f12e"; }
.fa-gamepad2:before { content: "\f11b"; }
.fa-joystick:before { content: "\f11b"; }
.fa-controller:before { content: "\f11b"; }

14
static/favicon.svg Normal file
View File

@@ -0,0 +1,14 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
<defs>
<linearGradient id="bg" x1="0%" y1="0%" x2="100%" y2="100%">
<stop offset="0%" style="stop-color:#3498db"/>
<stop offset="100%" style="stop-color:#2c3e50"/>
</linearGradient>
</defs>
<!-- Background -->
<circle cx="50" cy="50" r="48" fill="url(#bg)"/>
<!-- Car emoji -->
<text x="50" y="65" text-anchor="middle" font-size="45" fill="#fff">🚗</text>
</svg>

After

Width:  |  Height:  |  Size: 466 B

Binary file not shown.

BIN
static/images/img100.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

BIN
static/images/img101.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

BIN
static/images/img102.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

BIN
static/images/img103.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

BIN
static/images/img104.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

BIN
static/images/img105.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

BIN
static/images/img106.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

BIN
static/images/img107.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

BIN
static/images/img108.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

BIN
static/images/img109.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

BIN
static/images/img110.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

BIN
static/images/img111.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

BIN
static/images/img112.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

BIN
static/images/img113.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

BIN
static/images/img114.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

BIN
static/images/img115.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

BIN
static/images/img116.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

BIN
static/images/img117.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

BIN
static/images/img118.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

BIN
static/images/img119.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

BIN
static/images/img120.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

BIN
static/images/img121.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

BIN
static/images/img122.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

BIN
static/images/img123.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

BIN
static/images/img124.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

BIN
static/images/img125.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

BIN
static/images/img126.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

BIN
static/images/img127.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

BIN
static/images/img128.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

BIN
static/images/img129.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

BIN
static/images/img130.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

BIN
static/images/img131.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

BIN
static/images/img132.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

BIN
static/images/img133.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

BIN
static/images/img134.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

BIN
static/images/img135.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

BIN
static/images/img136.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

BIN
static/images/img137.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

BIN
static/images/img138.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

BIN
static/images/img139.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

BIN
static/images/img140.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

BIN
static/images/img141.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

BIN
static/images/img142.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

BIN
static/images/img143.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

BIN
static/images/img144.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

BIN
static/images/img145.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

BIN
static/images/img146.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

BIN
static/images/img147.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

BIN
static/images/img148.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

BIN
static/images/img151.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

BIN
static/images/img18.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

BIN
static/images/img181.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

BIN
static/images/img182.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

BIN
static/images/img187.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

BIN
static/images/img197.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

BIN
static/images/img199.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

BIN
static/images/img200.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

BIN
static/images/img28.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

BIN
static/images/img32.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

BIN
static/images/img33.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

BIN
static/images/img35.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

BIN
static/images/img4.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

BIN
static/images/img50.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

BIN
static/images/img67.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

BIN
static/images/img9.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

BIN
static/images/img93.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

BIN
static/images/img99.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Some files were not shown because too many files have changed in this diff Show More