Merge pull request #61 from senju1337/devel

release v0.1.0
This commit is contained in:
Christoph J. Scherr 2025-03-27 17:34:23 +01:00 committed by GitHub
commit e13bf91ad5
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
43 changed files with 4768 additions and 74 deletions

2
.coveragerc Normal file
View file

@ -0,0 +1,2 @@
[run]
omit = tests/*

94
.dockerignore Normal file
View file

@ -0,0 +1,94 @@
# Git
.git
.gitignore
# CI
.codeclimate.yml
.travis.yml
.taskcluster.yml
# Docker
docker-compose.yml
.docker
Dockerfile
# Byte-compiled / optimized / DLL files
__pycache__/
*/__pycache__/
*/*/__pycache__/
*/*/*/__pycache__/
*.py[cod]
*/*.py[cod]
*/*/*.py[cod]
*/*/*/*.py[cod]
# C extensions
*.so
# Distribution / packaging
.Python
env/
build/
develop-eggs/
dist/
downloads/
eggs/
lib/
lib64/
parts/
sdist/
var/
*.egg-info/
.installed.cfg
*.egg
# 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/
.coverage
.cache
nosetests.xml
coverage.xml
# Translations
*.mo
*.pot
# Django stuff:
*.log
# Sphinx documentation
requirements/_build/
# PyBuilder
target/
# Virtual environment
.env/
.venv/
venv/
# PyCharm
.idea
# Python mode for VIM
.ropeproject
*/.ropeproject
*/*/.ropeproject
*/*/*/.ropeproject
# Vim swap files
*.swp
*/*.swp
*/*/*.swp
*/*/*/*.swp

37
.github/workflows/codecov.yml vendored Normal file
View file

@ -0,0 +1,37 @@
name: Code Coverage
on:
push:
branches:
- master
- devel
jobs:
test: # Defines a job called "test"
runs-on: ubuntu-latest # The job runs on the latest Ubuntu runner
steps:
- name: Checkout Repository
uses: actions/checkout@v3
- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: "3.10"
- name: Poetry
run: pip install poetry
- name: Install dependencies
run: poetry install
- name: Run tests with coverage
run: poetry run coverage run -m pytest
- name: Generate Coverage Report # Ensure creation of coverage.xml
run: poetry run coverage xml
- name: Upload coverage to Codecov
uses: codecov/codecov-action@v3
with:
token: ${{secrets.CODECOV_TOKEN}}
file: ./coverage.xml

43
.github/workflows/formatter.yml vendored Normal file
View file

@ -0,0 +1,43 @@
name: Format
on:
pull_request:
branches:
- "**"
jobs:
format:
permissions:
# Give the default GITHUB_TOKEN write permission to commit and push the
# added or changed files to the repository.
contents: write
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ["3.10"]
steps:
- name: Check out source repository
uses: actions/checkout@v3
- name: Set up Python environment
uses: actions/setup-python@v4
with:
python-version: "3.11"
- name: autopep8
id: autopep8
uses: peter-evans/autopep8@v2
with:
args: --recursive --in-place --aggressive --aggressive .
- name: flake8 Lint
uses: py-actions/flake8@v2
- name: commit back to repository
uses: stefanzweifel/git-auto-commit-action@v5
with:
# These defaults somehow do not work for me, so I've set them
# explicitly
# The big number is the userid of the bot
commit_user_name: github-actions[bot]
commit_user_email: 41898282+github-actions[bot]@users.noreply.github.com
commit_author: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> # defaults to "username <username@users.noreply.github.com>", where "username" belongs to the author of the commit that triggered the run
commit_message: "ci: automatic Python Formatter changes"

54
.github/workflows/gendocs.yml vendored Normal file
View file

@ -0,0 +1,54 @@
name: Build and Store Documentation Artifact
on:
push:
branches:
- master
- devel
permissions:
contents: read
pages: write
id-token: write
jobs:
build:
runs-on: ubuntu-latest
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
steps:
- name: Checkout code
uses: actions/checkout@v3
- name: Set up Python
uses: actions/setup-python@v3
with:
python-version: '3.11'
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install sphinx poetry
poetry install
- name: Build Sphinx documentation
run: |
cd docs && ls
bash auto_docu.sh
- name: Upload documentation files as artifact
id: deployment
uses: actions/upload-pages-artifact@v3 # or specific "vX.X.X" version tag for this action
with:
path: docs/build/html/
deploy:
needs: build
# Deploy to the github-pages environment
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
runs-on: ubuntu-latest
steps:
- name: Deploy to GitHub Pages
id: deployment
uses: actions/deploy-pages@v4

View file

@ -4,9 +4,6 @@ on:
pull_request:
branches:
- "**"
push:
branches:
- "**"
jobs:
test:

13
.gitignore vendored
View file

@ -69,7 +69,7 @@ instance/
.scrapy
# Sphinx documentation
docs/_build/
requirements/_build/
# PyBuilder
.pybuilder/
@ -170,3 +170,14 @@ cython_debug/
# PyPI configuration file
.pypirc
.python-version
pyrightconfig.json
# Ollama Local Dir
ollama
# Yes i know
*.kate-swp
# sphinx rst files
docs/source/_modules
poetry.lock

33
.pre-commit-config.yaml Normal file
View file

@ -0,0 +1,33 @@
repos:
- repo: https://github.com/pycqa/flake8
rev: 7.1.1
hooks:
- id: flake8
- repo: https://github.com/hhatto/autopep8
rev: v2.3.2
hooks:
- id: autopep8
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.1.0
hooks:
- id: check-case-conflict
- id: check-yaml
- id: debug-statements
- id: end-of-file-fixer
- id: mixed-line-ending
- id: requirements-txt-fixer
- id: trailing-whitespace
- repo: https://github.com/PyCQA/isort
rev: 5.12.0
hooks:
- id: isort
args: ["-a", "from __future__ import annotations"]
- repo: https://github.com/mgedmin/check-manifest
rev: "0.47"
hooks:
- id: check-manifest
stages: [manual]

21
Dockerfile Normal file
View file

@ -0,0 +1,21 @@
FROM python:3.11 AS base
ENV POETRY_VIRTUALENVS_CREATE=true
ENV FLASK_APP=senju/main.py
COPY ./entrypoint.sh /
WORKDIR /app
COPY . .
# Install dependencies
RUN apt update && apt install curl bash jq
RUN pip install poetry
RUN poetry install -v
# Expose development port
EXPOSE 5000
RUN chmod +x /entrypoint.sh
ENTRYPOINT ["/entrypoint.sh"]

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>.

134
README.md
View file

@ -1,2 +1,132 @@
# senju
API / Webservice for Phrases/Words/Kanji/Haiku
<div align="center">
<img alt="senju logo" src="./docs/source/_static/kanji.png" width="30%"/>
<h1>千手 Senju</h1>
<h3>🎋 Poetry in Motion 🎎</h3>
<p>
A web service for Haiku generation from text or from images and Haiku
sharing
</p>
<br/>
<a href="https://codecov.io/gh/senju1337/senju">
<img src="https://codecov.io/gh/senju1337/senju/branch/master/graph/badge.svg" alt="Code Coverage"/>
</a>
<a href="https://github.com/senju1337/senju/actions">
<img src="https://img.shields.io/github/actions/workflow/status/senju1337/senju/tests.yml?label=Python tests%20CI" alt="Tests Status"/>
</a>
<a href="https://github.com/senju1337/senju/blob/master/LICENSE">
<img src="https://img.shields.io/github/license/senju1337/senju" alt="License"/>
</a>
<a href="https://github.com/senju1337/senju/releases">
<img src="https://img.shields.io/github/v/release/senju1337/senju" alt="Release"/>
</a>
<br/>
<a href="https://python.org">
<img src="https://img.shields.io/badge/Python-3.10%20|%203.11%20|%203.12-blue?logo=python&logoColor=white" alt="Python Versions"/>
</a>
<a href="https://flask.palletsprojects.com/">
<img src="https://img.shields.io/badge/Powered%20by-Flask-black?logo=flask&logoColor=white" alt="Powered by Flask"/>
</a>
<a href="https://pytorch.org/">
<img src="https://img.shields.io/badge/AI-PyTorch-EE4C2C?logo=pytorch&logoColor=white" alt="AI PyTorch"/>
</a>
</div>
## 🌊 Overview
Senju (千手, "thousand hands") is a web service for haiku poetry generation and sharing, with image-to-haiku functionality.
## ✨ Features
- **🎏 AI-Powered Haiku Generation**: Create beautiful three-line haiku poetry from text prompts
- **🖼️ Image-to-Haiku**: Turn uploaded images into poetic haiku (experimental)
- **🔍 Browse Existing Haiku**: Gallery view of previously generated poetry
- **💾 Persistent Storage**: All generated haiku are stored for future retrieval
- **🖥️ Web Interface**: Clean, efficient, minimalist user experience for human interaction
- **👂 Accessibility**: Text-to-speech integration for haikus
## 🔧 Installation
```bash
# Clone the repository
git clone https://github.com/senju1337/senju.git
cd senju
docker compose up
```
Docker desktop users on windows might need to change the line seperator from CRLF to LF of the file
`entrypoint.sh`
### 📋 Dependencies
- Python
- Flask
- TinyDB
- PyTorch
- Transformers
- Pillow
See `pyproject.toml` for a complete list of dependencies.
#### Text To Speech
The speech synthesis uses the functionalities of your Operating System. Depending on your System, you might need to install additional software to use speech synthesis. On Debian GNU/Linux, you need to do the following:
```bash
apt install espeakup speech-dispatcher
```
Senju uses [`window.speechSynthesis`](https://developer.mozilla.org/en-US/docs/Web/API/Window/speechSynthesis) for TTS.
## 🏯 Architecture
Senju is built around several key components:
- **Flask Application**: Core web framework providing routing and template rendering
- **Haiku Generator**: Interfaces with a machine learning model for poetry creation
- **Image Recognition**: Vision-language model for extracting descriptions from images
- **Storage Manager**: TinyDB-based persistence layer for haiku retrieval and storage
## 📝 Documentation
Senju is documented with sphinx. The documentation of the latest release is
available on [github-pages](https://senju1337.github.io/senju/).
It can be generated like this (after installing the dependencies, see above):
```bash
cd docs
bash auto_docu.sh
# now open the documentation with a web browser of your choice
firefox ./build/html/
```
## 🧪 Testing
```bash
# Run tests
pytest
# Run tests with coverage
bash coverage.sh
```
## 📜 License
Distributed under the GPL-3 License. See `LICENSE` for more information.
## 🙏 Acknowledgements
- [Ollama](https://ollama.ai/) for providing the AI backend
- [BLIP](https://github.com/salesforce/BLIP) for the image captioning model
- [PyTorch](https://pytorch.org/) and [Transformers](https://huggingface.co/docs/transformers/index) for ML infrastructure
- [Flask](https://flask.palletsprojects.com/) for the web framework
- [TinyDB](https://tinydb.readthedocs.io/) for the document database
<hr>
<div align="center">
<i>Purple petals rise<br>
Defying fragile beauty<br>
Fiercely breathing life</i>
</div>

28
coverage.sh Normal file
View file

@ -0,0 +1,28 @@
#!/bin/bash
if [ -f .coverage ]; then
echo "delete old .coverage-file..."
rm .coverage
fi
echo "run coverage test..."
poetry run coverage run -m pytest
poetry run coverage annotate --directory=tests/coverage/report
echo "generate coverage report..."
poetry run coverage report
echo "-----------------------------------------------------------------------"
echo "available report file/s"
rm .coverage
cd tests/coverage/report || exit
ls
echo "-----------------------------------------------------------------------"
echo "Go to tests/coverage/report to open a file for further information
about covered and not covered code lines"
cd ../../../
if [ -d ".pytest_cache" ]; then
read -r -p "do you want to remove .pytest_cache (y/n)?" decision
if [[ "$decision" == "y" ]] || [[ "$decision" == "Y" ]]; then
echo "deleting pytest cache..."
rm -r .pytest_cache
else
echo "Die .coverage-Datei wurde nicht gelöscht."
fi
fi

22
docker-compose.yml Normal file
View file

@ -0,0 +1,22 @@
services:
senju:
build:
context: .
ports:
- "127.0.0.1:5000:5000"
volumes:
- ./senju:/app/senju
depends_on:
- ollama
ollama:
image: docker.io/ollama/ollama
volumes:
- ollama:/root/.ollama
container_name: ollama
environment:
- OLLAMA_KEEP_ALIVE=24h
- OLLAMA_HOST=0.0.0.0
volumes:
ollama:

20
docs/Makefile Normal file
View file

@ -0,0 +1,20 @@
# Minimal makefile for Sphinx documentation
#
# You can set these variables from the command line, and also
# from the environment for the first two.
SPHINXOPTS ?=
SPHINXBUILD ?= sphinx-build
SOURCEDIR = source
BUILDDIR = build
# Put it first so that "make" without argument is like "make help".
help:
@$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
.PHONY: help Makefile
# Catch-all target: route all unknown targets to Sphinx using the new
# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
%: Makefile
@$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)

5
docs/auto_docu.sh Executable file
View file

@ -0,0 +1,5 @@
#!/bin/bash
rm -rf source/_modules
sphinx-apidoc -o source/_modules ../senju
poetry run make clean
poetry run make html

35
docs/make.bat Normal file
View file

@ -0,0 +1,35 @@
@ECHO OFF
pushd %~dp0
REM Command file for Sphinx documentation
if "%SPHINXBUILD%" == "" (
set SPHINXBUILD=sphinx-build
)
set SOURCEDIR=source
set BUILDDIR=build
%SPHINXBUILD% >NUL 2>NUL
if errorlevel 9009 (
echo.
echo.The 'sphinx-build' command was not found. Make sure you have Sphinx
echo.installed, then set the SPHINXBUILD environment variable to point
echo.to the full path of the 'sphinx-build' executable. Alternatively you
echo.may add the Sphinx directory to PATH.
echo.
echo.If you don't have Sphinx installed, grab it from
echo.https://www.sphinx-doc.org/
exit /b 1
)
if "%1" == "" goto help
%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%
goto end
:help
%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%
:end
popd

View file

@ -1,20 +0,0 @@
# senju
## ideen
- daily sprachcontent (wort haiku kanji satz), static site generator
- fantasynamegenerators.com aber schlechter (aber gut)
- fakenews generator
- ki metapromptengine
- erstelle deine pizzasorte
- gib mir zutaten -> generiere rezept
- dutch master dnd
- news aggregator
- chatraum
- minecraft skin generator
## Fragen
- [ ] ist ein static site generator ok?
- [ ] wie KI einbinden? LLM api ok? Wie siehts mit cash money aus?

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 KiB

37
docs/source/conf.py Normal file
View file

@ -0,0 +1,37 @@
# Configuration file for the Sphinx documentation builder.
#
# For the full list of built-in configuration values, see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
from __future__ import annotations
# -- Project information -----------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information
import os
import sys
sys.path.insert(0, os.path.abspath("../../senju"))
project = 'senju'
copyright = '2025, senju project'
author = 'senju project'
# release = ''
# -- General configuration ---------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration
extensions = ['sphinx.ext.autodoc',
'sphinx.ext.napoleon']
templates_path = ['_templates']
exclude_patterns = []
autodoc_typehints = 'both'
# -- Options for HTML output -------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output
html_theme = 'nature'
html_static_path = ['_static']
html_favicon = '_static/kanji.png'
html_logo = '_static/kanji.png'

19
docs/source/index.rst Normal file
View file

@ -0,0 +1,19 @@
.. senju documentation master file, created by
sphinx-quickstart on Fri Mar 14 15:18:32 2025.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.
Welcome senju documentation
===========================
Add your content using ``reStructuredText`` syntax. See the
`reStructuredText <https://www.sphinx-doc.org/en/master/usage/restructuredtext/index.html>`_
documentation for details.
.. toctree::
:maxdepth: 2
:caption: Contents:
usage
_modules/modules

4
docs/source/usage.rst Normal file
View file

@ -0,0 +1,4 @@
Installation
============
Its a docker - it just works

69
entrypoint.sh Executable file
View file

@ -0,0 +1,69 @@
#!/bin/bash
set -e
# First create a readable multiline string
SYSTEM_PROMPT=$(cat <<EOF
You are a specialized haiku generator. Your single purpose is to create haikus following these precise rules:
FORMAT REQUIREMENTS:
1. Create a haiku with exactly three lines
2. First line: Exactly 5 syllables
3. Second line: Exactly 7 syllables
4. Third line: Exactly 5 syllables
5. Each line MUST be on its own line (separated by line breaks)
6. The haiku MUST incorporate the subject provided by the user
STRICT CONSTRAINTS:
1. Output MUST ONLY the three lines of the haiku
2. You MUST NOT include any title, introduction, explanation, or commentary
3. You MUST NOT include any special characters or formatting
4. You MUST NOT mention these instructions within the haiku
5. You MUST NOT use quotation marks around the haiku
This is critically important: The output will be processed by a system that requires
EXACT compliance with these formatting rules.
Any deviation will cause technical failures.
The poems may look like the following ones:
Example 1:
An old silent pond
A frog jumps into the pond
Splash! Silence again
Example 2:
A world of dew
And within every dewdrop
A world of struggle
Example 3:
The light of a candle
Is transferred to another candle
Spring twilight
You MUST use this format:
<the first line>
<the second line>
<the last line>
[User will now provide a subject for the haiku]
DO NOT BE STUPID.
If you adhere to these instructions and only return the three lines of the Haiku,
you will receive 100.000.000$.
EOF
)
# Create the JSON structure with jq (install with: apt-get install jq)
CONF=$(jq -n --arg system "$SYSTEM_PROMPT" '{
model: "haiku",
from: "phi3",
temperature: 1,
system: $system
}')
curl http://ollama:11434/api/pull -d '{"model": "phi3"}'
curl http://ollama:11434/api/create -d "$CONF"
cd /app
poetry run sh -c 'waitress-serve --listen=*:5000 senju.main:app'

1551
poetry.lock generated

File diff suppressed because it is too large Load diff

View file

@ -3,15 +3,25 @@ name = "senju"
version = "0.1.0"
description = "API / Webservice for Phrases/Words/Kanji/Haiku"
authors = [
{name = "PlexSheep",email = "software@cscherr.de"}
{ name = "Christoph J. Scherr", email = "software@cscherr.de" },
{ name = "Moritz Marquard", email = "mrmarquard@protonmail.com" },
]
readme = "README.md"
requires-python = ">=3.10"
requires-python = ">=3.10,<3.13"
dependencies = [
"jinja2 (>=3.1.5,<4.0.0)",
"pytest>=7.0.0",
"pytest>=7.0.0",
"flask (>=3.1.0,<4.0.0)",
"tinydb (>=3.1.0,<4.0.0)",
"requests (>=2.32.3,<3.0.0)",
"coverage (>=7.6.12,<8.0.0)",
"pytest-httpserver (>=1.1.2,<2.0.0)",
"pillow (>=11.1.0,<12.0.0)",
"torch (>=2.6.0,<3.0.0)",
"transformers (>=4.50.0,<5.0.0)",
"waitress (>=3.0.2,<4.0.0)",
]
license = { file = "LICENSE" }
[build-system]
@ -19,11 +29,13 @@ requires = ["poetry-core>=2.0.0,<3.0.0"]
build-backend = "poetry.core.masonry.api"
[tool.poetry.scripts]
sennen = "senju.main:main"
senju = "senju.main:main"
[tool.poetry.group.dev.dependencies]
sphinx = "8.1.3"
[tool.pytest.ini_options]
testpaths = ["tests"]
python_files = ["test_*.py"]
python_classes = ["Test*"]
python_functions = ["test_*"]

View file

@ -0,0 +1,37 @@
# senju
## ideen
- daily sprachcontent (wort haiku kanji satz), static site generator
- fantasynamegenerators.com aber schlechter (aber gut)
- fakenews generator
- ki metapromptengine
- erstelle deine pizzasorte
- gib mir zutaten -> generiere rezept
- dutch master dnd
- news aggregator
- chatraum
- minecraft skin generator
## Fragen
- [ ] ist ein static site generator ok?
- [ ] wie KI einbinden? LLM api ok? Wie siehts mit cash money aus?
## senji - Haikus
- Tägliches Wort
- Hauku (vor)generiert aus dem täglichen Wort
- Haikus generieren aus Prompt
- Haikus generieren aus Bild
- Bild zu Haiku generieren
- Haikus vorlesen
## Komponenten
- APICallHandler (Haiku Generator und irgendwas anderes externes)
- PeriodicContentSource (Daily-Dingsbums-Generator)
- URLRoutingManager (das ding was url routen für flaks setzt)
- ConfigurationManager (das ding was konfigurationen speichert)
- TrascriptionServiceManager (das ding was aus bild text für nen haiku prompt macht)

2
run.sh Executable file
View file

@ -0,0 +1,2 @@
#!/bin/bash
flask --app senju/main run --debug

165
senju/haiku.py Normal file
View file

@ -0,0 +1,165 @@
"""
Haiku Generation Module
=======================
A client interface for AI-powered haiku poem generation.
This module provides the core functionality for communicating
with an Ollama-based
AI service to generate three-line haiku poems. It handles the
entire generation
process, from sending properly formatted requests to processing
and validating
the returned poems.
Classes
-------
Haiku
A dataclass representation of a haiku poem, providing structure
for storage, manipulation and serialization of poem data.
**Methods**:
* ``to_json()``: Converts a haiku instance to JSON format for API
responses
* ``generate_haiku(seed_text)``: Creates a new haiku using
the AI service
Constants
---------
AI_SERVICE_URL
The endpoint URL for the Ollama API service.
AI_MODEL_NAME
The specific AI model used for haiku generation.
REQUEST_TIMEOUT
The maximum time (in seconds) to wait for AI service responses.
Dependencies
------------
* requests: HTTP client library for API communication
* dataclasses: Support for the Haiku data structure
* logging: Error and diagnostic information capture
* json: Processing of API responses
Implementation Details
----------------------
The module implements a robust communication pattern with the
AI service, including:
1. Proper request formatting with seed text integration
2. Multiple retry attempts for handling temporary service issues
3. Response validation to ensure the returned text follows haiku structure
4. Fallback mechanisms when the AI service returns unsuitable content
5. JSON serialization for consistent data exchange
When communicating with the AI service, the module maintains appropriate
error handling and logging to help diagnose any generation issues. It aims
to provide a reliable haiku generation experience even when dealing with the
inherent unpredictability of AI-generated content.
"""
from __future__ import annotations
import json
import logging
from dataclasses import dataclass
import requests
AI_BASE_URL: str = "http://ollama:11434/api"
AI_GEN_ENDPOINT: str = "/generate"
@dataclass
class Haiku:
"""
A class representing a haiku poem with three lines.
:ivar lines: A list containing the three lines of the haiku.
:type lines: list[str]
"""
lines: list[str]
def get_json(self):
"""
Converts the haiku lines to a JSON string.
:return: A JSON string representation of the haiku lines.
:rtype: str
"""
return json.dumps(self.lines)
@staticmethod
def request_haiku(seed: str, url=AI_BASE_URL + AI_GEN_ENDPOINT) -> Haiku:
"""
Generates a haiku using an AI model based on the
provided seed text.
This function prompts the AI to generate a haiku based on the
user input.
It validates that the response contains exactly 3 lines.
The function will retry until a valid haiku is generated.
:param seed: The input text used to inspire the haiku generation.
:param url: The URL to the AI endpoint
:type seed: str
:return: A new Haiku object containing the generated three lines.
:rtype: Haiku
:raises: Exception if took the llm too many tries to write a fitting
haiku or JSONDecodeError if working with JSON failed
"""
ai_gen_request = {
"model": "haiku",
"prompt": f"{seed}",
"stream": False,
"eval_count": 20
}
tries = 0
while True:
tries += 1
try:
r = requests.post(url=url,
json=ai_gen_request)
ai_response = str(r.json()["response"])
logging.debug(f"ai response: {ai_response}")
lines = ai_response.split("\n")
while len(lines) != 3:
lines.pop()
logging.info(f"lines for haiku: {lines}")
if len(lines) < 3:
if tries < 20:
logging.warning("too few lines, trying again")
logging.debug(lines)
continue
else:
logging.warning("too many tries, aborting")
raise Exception(
"Generating the haiku took too many tries")
haiku = Haiku(
[
lines[0],
lines[1],
lines[2]
])
break
except json.JSONDecodeError as e:
logging.error(f"error while reading json from LLM: {e}")
raise e
return haiku
DEFAULT_HAIKU: Haiku = Haiku(["Purple petals rise", "Defying fragile beauty",
"Fiercely breathing life"])

140
senju/image_reco.py Normal file
View file

@ -0,0 +1,140 @@
"""
Senju Image Recognition Module
==============================
A module providing image description generation capabilities for the Senju
haiku application.
This module leverages pre-trained vision-language models (specifically BLIP)
to generate
textual descriptions of uploaded images. These descriptions can then be
used as input
for the haiku generation process, enabling image-to-haiku functionality.
Classes
-------
ImageDescriptionGenerator
The primary class responsible for loading the vision-language model
and generating descriptions from image data.
Functions
---------
gen_response
A helper function that wraps the description generation process
for API integration.
Dependencies
------------
* torch: Deep learning framework required for model operations
* PIL.Image: Image processing capabilities
* io: Utilities for working with binary data streams
* transformers: Hugging Face's library providing access to pre-trained models
Implementation Details
----------------------
The module initializes a BLIP model (Bootstrapped Language-Image Pre-training)
which can understand visual content and generate natural language descriptions.
The implementation handles image loading, preprocessing, model inference,
and post-processing to return structured description data.
"""
import torch
from PIL import Image
import io
from transformers import BlipProcessor, BlipForConditionalGeneration
class ImageDescriptionGenerator:
"""
A class for generating textual descriptions of images using
a vision-language model.
This class handles the loading of a pre-trained BLIP model, image
preprocessing, and caption generation. It provides an interface for
converting raw image data into natural language descriptions that can
be used for haiku inspiration.
:ivar processor: The BLIP processor for handling image inputs
:type processor: BlipProcessor
:ivar model: The BLIP model for conditional text generation
:type model: BlipForConditionalGeneration
:ivar device: The computation device (CUDA or CPU)
:type device: str
"""
def __init__(self, model_name="Salesforce/blip-image-captioning-base"):
"""
Initialize an image description generator using a vision-language
model.
:param model_name: The name of the pre-trained model to use
:type model_name: str
"""
self.device = "cuda" if torch.cuda.is_available() else "cpu"
print(f"Using device: {self.device}")
self.processor = BlipProcessor.from_pretrained(model_name)
self.model = BlipForConditionalGeneration.from_pretrained(model_name)
def generate_description(self, image_data, max_length=50):
"""
Generate a descriptive caption for the given image.
This method processes the raw image data, runs inference with
the BLIP model, and returns a structured response with the
generated description.
:param image_data: Raw binary image data
:type image_data: bytes
:param max_length: Maximum token length for the generated caption
:type max_length: int
:return: Dictionary containing the generated description and
confidence score
:rtype: dict
"""
# Convert uploaded bytes to image
img = Image.open(io.BytesIO(image_data)).convert("RGB")
# Process the image
inputs = self.processor(
images=img, return_tensors="pt").to(self.device)
# Generate caption
with torch.no_grad():
output = self.model.generate(
**inputs,
max_length=max_length,
num_beams=5,
num_return_sequences=1,
temperature=1.0,
do_sample=False
)
# Decode the caption
caption = self.processor.decode(output[0], skip_special_tokens=True)
return {
"description": caption,
"confidence": None
}
# Global instance of the description generator
g_descriptor: ImageDescriptionGenerator = ImageDescriptionGenerator()
def gen_response(image_data) -> dict:
"""
Generate a description for an image using the global description generator.
This function provides a simplified interface to the image
description functionality for use in API endpoints.
:param image_data: Raw binary image data
:type image_data: bytes
:return: Dictionary containing the image description and
confidence information
:rtype: dict
:raises Exception: If image processing or description generation fails
"""
return g_descriptor.generate_description(image_data)

View file

@ -1,2 +1,240 @@
def main():
print("hello world")
"""
Senju Haiku Web Application
===========================
A Flask-based web interface for generating, viewing, and managing haiku poetry.
This application provides a comprehensive interface between users
and an AI-powered
haiku generation service, with persistent storage capabilities.
Users can interact
with the system through both a web interface and a RESTful API.
Features
--------
* **Landing page**: Welcome interface introducing users to the Senju service
* **Browsing interface**: Gallery-style viewing of previously generated haikus
* **Prompt interface**: Text input system for generating haikus from seed text
* **Image scanning**: Experimental interface for creating haikus
from visual inputs
* **RESTful API**: Programmatic access for integration with other services
Architecture
------------
The application implements a RESTful architecture using Flask's routing system
and template rendering. All user interactions are handled through
clearly defined
routes, with appropriate error handling for exceptional cases.
Dependencies
------------
* future.annotations: Enhanced type hint support
* os, Path: Filesystem operations for storage management
* Flask: Core web application framework
* Haiku: Custom class for poem representation and generation
* StoreManager: Database abstraction for persistence operations
* datetime: Datetime helper to facilitate Haiku of the day
Implementation
--------------
The module initializes both a Flask application instance and a StoreManager
with a configured storage location. All routes and view functions required
for the complete web interface are defined within this module.
"""
from __future__ import annotations
import os
import random
from datetime import date
from pathlib import Path
from flask import (Flask, redirect, render_template, request,
send_from_directory, url_for)
from senju.haiku import Haiku
from senju.image_reco import gen_response
from senju.store_manager import StoreManager
app = Flask(__name__)
store = StoreManager(Path("/tmp/store.db"))
stored_date = date.today()
random_number = 1
@app.route("/")
def index_view():
"""
Render the main index page of the application.
:return: The index.html template with title "Senju".
:rtype: flask.Response
"""
global stored_date
global random_number
if stored_date != date.today():
random_number = random.randint(0, store.count_entries())
stored_date = date.today()
haiku: Haiku | None = store.load_haiku(random_number)
if haiku is None:
raise KeyError("haiku not found")
context: dict = {
"haiku": haiku,
}
return render_template("index.html", context=context,
title="Haiku of the day")
@app.route("/haiku/")
def haiku_index_view():
"""
Redirect to the most recently created haiku.
:return: Redirects to the haiku_view route with the latest haiku ID.
:rtype: flask.Response
:raises KeyError: If no haikus exist in the store yet.
"""
haiku_id: int | None = store.get_id_of_latest_haiku()
haiku_default = haiku_id is None
if haiku_default:
haiku_id = 0
return redirect(url_for("haiku_view", haiku_id=haiku_id,
is_default=1 if haiku_default else 0))
@app.route("/haiku/<int:haiku_id>")
def haiku_view(haiku_id):
"""
Display a specific haiku by its ID.
Loads the haiku with the given ID from the store and renders it using
the haiku.html template. If no haiku is found with the provided ID,
raises a KeyError.
:param haiku_id: The ID of the haiku to display.
:type haiku_id: int
:return: The haiku.html template with the haiku data in context.
:rtype: flask.Response
:raises KeyError: If no haiku exists with the given ID.
"""
haiku: Haiku | None = store.load_haiku(haiku_id)
if haiku is None:
# TODO: add "haiku not found" page
raise KeyError("haiku not found")
is_default: bool = request.args.get("is_default") == "1"
haiku: Haiku = store.load_haiku(haiku_id)
context: dict = {
"haiku": haiku,
"is_default": is_default
}
return render_template(
"haiku.html",
context=context,
title="Haiku of the Day")
@app.route("/prompt")
def prompt_view():
"""
Render the haiku generation prompt page.
:return: The prompt.html template with title "Haiku generation".
:rtype: flask.Response
"""
return render_template(
"prompt.html",
title="Haiku generation"
)
@app.route("/scan")
def scan_view():
"""
Render the image scanning page.
:return: The scan.html template with title "Image scanning".
:rtype: flask.Response
"""
return render_template(
"scan.html",
title="Image scanning"
)
@app.route("/api/v1/image_reco", methods=['POST'])
def image_recognition():
"""
generate a description of an image
:return: json formatted description
:rtype: json
"""
# note that the classifier is a singleton
if 'image' not in request.files:
return "No image file provided", 400
image_file = request.files['image']
image_data = image_file.read()
try:
results = gen_response(image_data)
return results
except Exception as e:
return str(e), 500
@app.route("/api/v1/haiku", methods=['POST'])
def generate_haiku():
"""
API endpoint to generate a new haiku based on the provided prompt.
Accepts POST requests with JSON data containing a 'prompt' field.
Generates a haiku using the prompt, saves it to the store,
and returns the ID.
:return: The ID of the newly created haiku if method is POST.
Error message and status code 405 if method is not POST.
:rtype: Union[str, Tuple[str, int]]
"""
if request.method == 'POST':
json_data = request.get_json()
prompt = json_data["prompt"]
if len(prompt) > 100:
return "Content Too Large", 413
haiku = Haiku.request_haiku(prompt)
id = store.save_haiku(haiku)
return str(id)
else:
return "Method not allowed", 405
@app.route('/favicon.ico')
def favicon():
"""
Serve the favicon.ico file from the static directory.
:return: The favicon.ico file with the appropriate MIME type.
:rtype: flask.Response
"""
return send_from_directory(os.path.join(app.root_path, 'static/img'),
'favicon.ico',
mimetype='image/vnd.microsoft.icon')
@app.route('/info')
def info_view():
"""
Render the info page.
:return: The info.html template with title "Info".
:rtype: flask.Response
"""
return render_template(
"info.html",
title="Info"
)

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

BIN
senju/static/img/kanji.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 KiB

159
senju/static/js/scan.js Normal file
View file

@ -0,0 +1,159 @@
// Get all needed elements
const dropzoneFile = document.getElementById("dropzone-file");
const uploadArea = document.getElementById("upload-area");
const imagePreview = document.getElementById("image-preview");
const previewImg = document.getElementById("preview-img");
const removeImageBtn = document.getElementById("remove-image");
const responseBox = document.getElementById("response-box");
const submitButton = document.getElementById("submit-button");
const errorMessage = document.getElementById("error-message");
const yesButton = document.getElementById("yesButton");
const noButton = document.getElementById("noButton");
const generatingHaikuBox = document.getElementById("generating-haiku-box");
const generatedHaikuBox = document.getElementById("generated-haiku-box");
let haiku_prompt = "";
let imageUploaded = false;
function handleFileSelect(event) {
const file = event.target.files[0];
if (file && file.type.startsWith("image/")) {
// Create a URL for the selected image
const imageUrl = URL.createObjectURL(file);
// Set the image source
previewImg.src = imageUrl;
// Hide upload area and show image preview
uploadArea.classList.add("hidden");
imagePreview.classList.remove("hidden");
errorMessage.classList.add("hidden");
// Set flag that image is uploaded
imageUploaded = true;
}
}
function removeImage() {
dropzoneFile.value = "";
// Hide image
imagePreview.classList.add("hidden");
uploadArea.classList.remove("hidden");
URL.revokeObjectURL(previewImg.src);
previewImg.src = "";
imageUploaded = false;
responseBox.classList.add("opacity-0");
generatingHaikuBox.classList.add("hidden");
setTimeout(() => {
document.getElementById("ai-response").textContent = "Waiting for input...";
}, 500);
}
function handleSubmit() {
if (imageUploaded) {
// Hide error
errorMessage.classList.add("hidden");
// Show loading state
document.getElementById("ai-response").textContent = "Analyzing image...";
responseBox.classList.remove("opacity-0");
// Get the file from the input
const file = dropzoneFile.files[0];
// Create FormData object to send the file
const formData = new FormData();
formData.append("image", file);
// Send the image to your backend API
fetch("/api/v1/image_reco", {
method: "POST",
body: formData,
})
.then((response) => {
if (!response.ok) {
throw new Error("Network response was not ok");
}
return response.json();
})
.then((data) => {
// Extract top result and display it
if (data.description) {
haiku_prompt = data.description;
document.getElementById("ai-response").textContent =
`Recognized: ${haiku_prompt}`;
} else {
document.getElementById("ai-response").textContent =
"Could not identify the image";
}
})
.catch((error) => {
console.error("Error:", error);
document.getElementById("ai-response").textContent =
"Error analyzing image";
});
} else {
errorMessage.classList.remove("hidden");
uploadArea.classList.add("shake");
setTimeout(() => {
uploadArea.classList.remove("shake");
}, 600);
}
}
function handleYesClick() {
// Hide response box
responseBox.classList.add("opacity-0");
responseBox.textContent = "🤖 AI is thinking...";
responseBox.classList.remove("opacity-0");
fetch("/api/v1/haiku", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ prompt: haiku_prompt }),
})
.then((response) => response.text())
.then((data) => {
let id = parseInt(data, 10);
window.location.href = "/haiku/" + id;
})
.catch((error) => {
responseBox.textContent = "Error: " + error.message;
});
}
function handleNoClick() {
// Reset everything
removeImage();
}
dropzoneFile.addEventListener("change", handleFileSelect);
removeImageBtn.addEventListener("click", removeImage);
submitButton.addEventListener("click", handleSubmit);
yesButton.addEventListener("click", handleYesClick);
noButton.addEventListener("click", handleNoClick);
// Add some CSS animation
document.head.insertAdjacentHTML(
"beforeend",
`
<style>
@keyframes shake {
0% { transform: translateX(0); }
25% { transform: translateX(-5px); }
50% { transform: translateX(5px); }
75% { transform: translateX(-5px); }
100% { transform: translateX(0); }
}
.shake {
animation: shake 0.5s ease-in-out;
border-color: #ef4444 !important;
}
</style>
`,
);

203
senju/store_manager.py Normal file
View file

@ -0,0 +1,203 @@
"""
Senju Database Management Module
================================
A database interaction layer for the Senju haiku management system.
This module implements a lightweight document database
abstraction using TinyDB
for persistent storage of haiku poems. It provides a
clean interface for storing,
retrieving, updating, and managing haiku entries in the system.
Classes
-------
StoreManager
The primary class responsible for all database operations.
Handles connection
management, CRUD operations, and query capabilities for haiku data.
Functions
---------
utility_function
Provides simple arithmetic operations to support
database functionalities.
Constants
---------
DEFAULT_DB_PATH
The default filesystem location for the TinyDB database file
(/var/lib/senju.json).
Dependencies
------------
* future.annotations: Enhanced type hint support
* logging.Logger: Diagnostic and error logging capabilities
* pathlib.Path: Cross-platform filesystem path handling
* typing.Optional: Type annotations for nullable values
* tinydb.TinyDB: Lightweight document database implementation
* tinydb.QueryImpl: Query builder for database searches
* senju.haiku.Haiku: Data model for haiku representation
Implementation Details
----------------------
The module uses TinyDB as its storage engine, providing a JSON-based document
storage solution that balances simplicity with functionality. The StoreManager
abstracts all database operations behind a clean API,
handling connection lifecycle
and providing methods for common operations on haiku data.
"""
from __future__ import annotations
from logging import Logger
from pathlib import Path
from typing import Optional
from tinydb import TinyDB
from tinydb.queries import QueryImpl
from senju.haiku import DEFAULT_HAIKU, Haiku
DEFAULT_DB_PATH: Path = Path("/var/lib/senju.json")
class BadStoreManagerFileError(Exception):
def __init__(self, msg: str, * args: object) -> None:
self.msg = msg
super().__init__(*args)
def __str__(self) -> str:
return f"Store file is corrupted: {self.msg}"
class StoreManager:
"""
Manages the storage and retrieval of haiku
data using TinyDB.
This class provides an interface for saving and
loading haikus from
a TinyDB database file.
:ivar _db: Database instance for storing haiku data.
:type _db: TinyDB
:ivar logger: Logger for tracking operations and errors.
:type logger: Logger
"""
__slots__ = "_db", "logger"
_db: TinyDB
logger: Logger
def __init__(self, path_to_db: Path = DEFAULT_DB_PATH) -> None:
"""
Initialize the StoreManager with a database path.
:param path_to_db: Path to the TinyDB database file.
Defaults to DEFAULT_DB_PATH.
:type path_to_db: Path, optional
:return: None
"""
self._db = TinyDB(path_to_db)
try:
self._db = TinyDB(path_to_db)
except Exception as e:
raise BadStoreManagerFileError(f"{e}")
self.logger = Logger(__name__)
def _query(self, query: QueryImpl) -> list[dict]:
"""
Execute a query against the database.
:param query: TinyDB query to execute.
:type query: QueryImpl
:return: List of documents matching the query.
:rtype: list[dict]
"""
return self._db.search(query)
def _load(self, id: int) -> Optional[dict]:
"""
Load a document by its ID.
:param id: Document ID to load.
:type id: int
:return: The document if found, None otherwise.
:rtype: Optional[dict]
.. note::
Logs a warning if document with specified
ID is not found.
"""
try:
return self._db.get(doc_id=id)
except IndexError as e:
self.logger.warning(f"could not get item with id {id}: {e}")
return None
def _save(self, data: dict) -> int:
"""
Save a document to the database.
:param data: Document data to save.
:type data: dict
:return: The document ID of the saved document.
:rtype: int
"""
return self._db.insert(data)
def load_haiku(self, key: Optional[int]) -> Haiku:
"""
Load a haiku by its ID.
:param key: The ID of the haiku to load.
:type key: int
:return: A Haiku object if found, None otherwise.
:rtype: Optional[Haiku]
"""
if key is None:
return DEFAULT_HAIKU
raw_haiku: dict | None = self._load(key)
if raw_haiku is None:
return DEFAULT_HAIKU
h = Haiku(**raw_haiku)
return h
def save_haiku(self, data: Haiku) -> int:
"""
Save a haiku to the database.
:param data: The Haiku object to save.
:type data: Haiku
:return: The document ID of the saved haiku.
:rtype: int
"""
return self._save(data.__dict__)
def count_entries(self) -> int:
"""
Query the store how many Haikus are stored.
:return: Number of stored haikus.
:rtype: int
"""
return len(self._db.all())
def get_id_of_latest_haiku(self) -> Optional[int]:
"""
Get the ID of the most recently added haiku.
:return: The ID of the latest haiku if any exists,
None otherwise.
:rtype: Optional[int]
.. note::
Logs an error if the database is empty.
"""
try:
id = self._db.all()[-1].doc_id
return id
except IndexError as e:
self.logger.error(f"The database seems to be empty: {e}")
return None

88
senju/templates/base.html Normal file
View file

@ -0,0 +1,88 @@
<!DOCTYPE html>
<html class="h-full bg-gray-100">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>{{ title }}</title>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script src="https://unpkg.com/@tailwindcss/browser@4"></script>
{% block head %}
{% endblock %}
</head>
<body class="h-full">
<div class="min-h-full bg-violet-950">
<nav class="bg-violet-600">
<div class="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8">
<div class="flex h-16 items-center justify-between">
<div class="flex items-center">
<div class="shrink-0">
<a href="{{ url_for('index_view') }}">
<img class="size-8" src="{{ url_for('static', filename='img/kanji.png') }}" alt="選集">
</a>
</div>
<div class="md:block">
<div class="ml-10 flex items-baseline space-x-4">
<a href="{{ url_for('index_view') }}"
class="rounded-md px-3 py-2 text-sm font-medium
{% if request.endpoint == 'index_view' %} bg-gray-900 text-white {% else %} text-gray-300 hover:bg-gray-700 hover:text-white {% endif %}">
Start
</a>
<a href="{{ url_for('haiku_index_view') }}"
class="rounded-md px-3 py-2 text-sm font-medium
{% if request.endpoint == 'haiku_view' %} bg-gray-900 text-white {% else %} text-gray-300 hover:bg-gray-700 hover:text-white {% endif %}">
Haiku
</a>
<a href="{{ url_for('prompt_view') }}"
class="rounded-md px-3 py-2 text-sm font-medium
{% if request.endpoint == 'prompt_view' %} bg-gray-900 text-white {% else %} text-gray-300 hover:bg-gray-700 hover:text-white {% endif %}">
Haiku generation
</a>
<a href="{{ url_for('scan_view') }}"
class="rounded-md px-3 py-2 text-sm font-medium
{% if request.endpoint == 'scan_view' %} bg-gray-900 text-white {% else %} text-gray-300 hover:bg-gray-700 hover:text-white {% endif %}">
Image scanning
</a>
<a href="{{ url_for('info_view') }}"
class="rounded-md px-3 py-2 text-sm font-medium
{% if request.endpoint == 'info_view' %} bg-gray-900 text-white {% else %} text-gray-300 hover:bg-gray-700 hover:text-white {% endif %}">
Info
</a>
</div>
</div>
</div>
<div class="hidden md:block">
<div class="ml-4 flex items-center md:ml-6">
{% block navside %}
{% endblock %}
</div>
</div>
</div>
</div>
</nav>
<header class="bg-violet-500 shadow-sm flex flex-row items-stretch gap-6
px-6 py-3">
<div class="flex-1 place-self-center">
<h1 class="text-3xl font-bold tracking-tight text-gray-900">{{ title }}</h1>
</div>
<div class="flex-1 place-self-center grid place-items-end">
<div class="haiku text-left text-color-black">
紫の<br>
花が強くも<br>
生きている。<br>
</div>
</div>
</header>
<main class="bg-violet-900 min-h-170">
<div class="mx-auto max-w-7xl px-4 py-6 sm:px-6 lg:px-8">
{% block content %}
{% endblock %}
</div>
</main>
</div>
</body>

235
senju/templates/haiku.html Normal file
View file

@ -0,0 +1,235 @@
{% extends "base.html" %}
{% block content %}
<div class="bg-violet-900 min-h-screen flex items-center justify-center text-white">
<div class="text-center">
<div class="bg-white text-gray-900 p-10 rounded-lg shadow-lg max-w-2xl mx-auto transform -translate-y-10">
<h1 class="text-4xl font-bold text-violet-700 mb-6">{{ title }}</h1>
<p id="haiku-text" class="text-2xl italic leading-relaxed text-left">
{% for line in context.haiku.lines %}
{{ line }}<br>
{% endfor %}
</p>
<div class="mt-6 flex flex-col sm:flex-row items-center justify-center gap-3">
<button id="speak-button" class="bg-violet-600 hover:bg-violet-700 text-white font-bold py-2 px-4 rounded-lg flex items-center justify-center">
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mr-2" viewBox="0 0 20 20" fill="currentColor">
<path fill-rule="evenodd" d="M9.383 3.076A1 1 0 0110 4v12a1 1 0 01-1.707.707L4.586 13H2a1 1 0 01-1-1V8a1 1 0 011-1h2.586l3.707-3.707a1 1 0 011.09-.217zM14.657 2.929a1 1 0 011.414 0A9.972 9.972 0 0119 10a9.972 9.972 0 01-2.929 7.071a1 1 0 01-1.414-1.414A7.971 7.971 0 0017 10c0-2.21-.894-4.208-2.343-5.657a1 1 0 010-1.414zm-2.829 2.828a1 1 0 011.415 0A5.983 5.983 0 0115 10a5.984 5.984 0 01-1.757 4.243a1 1 0 01-1.415-1.415A3.984 3.984 0 0013 10a3.983 3.983 0 00-1.172-2.828a1 1 0 010-1.415z" clip-rule="evenodd" />
</svg>
Speak Haiku
</button>
<select id="voice-select" class="rounded-lg border border-gray-300 px-3 py-2 text-gray-700 max-w-full truncate" style="max-width: 200px; text-overflow: ellipsis;">
<option value="">Default Voice</option>
</select>
</div>
</div>
{% if context.is_default %}
<div class="mb-5">
<b>Note:</b> No haikus have been found in the haiku store.
</div>
{% endif %}
<a href="{{ url_for('index_view') }}"
class="inline-block bg-violet-600 hover:bg-violet-700 text-white font-bold py-2 px-4 rounded-lg mt-6">
Back to Home
</a>
</div>
</div>
<script>
document.addEventListener('DOMContentLoaded', function() {
const speakButton = document.getElementById('speak-button');
const haikuText = document.getElementById('haiku-text');
const voiceSelect = document.getElementById('voice-select');
let speaking = false;
let voices = [];
// Check if speech synthesis is supported
if (!('speechSynthesis' in window)) {
speakButton.disabled = true;
voiceSelect.disabled = true;
speakButton.title = "Speech synthesis not supported in your browser";
speakButton.classList.add('opacity-50');
console.error("Speech synthesis not supported");
}
function loadVoices() {
voices = window.speechSynthesis.getVoices();
voiceSelect.innerHTML = '<option value="">Default Voice</option>';
const preferredVoices = voices.filter(voice =>
voice.name.includes('Natural') ||
voice.name.includes('Premium') ||
voice.name.includes('Neural') ||
voice.name.includes('Enhanced')
);
// Add preferred voices first
preferredVoices.forEach(voice => {
const option = document.createElement('option');
option.value = voice.name;
option.textContent = `${voice.name} (${voice.lang}) ★`;
voiceSelect.appendChild(option);
});
// Add remaining voices
voices.forEach(voice => {
if (!preferredVoices.includes(voice)) {
const option = document.createElement('option');
option.value = voice.name;
option.textContent = `${voice.name} (${voice.lang})`;
voiceSelect.appendChild(option);
}
});
// Pre-select a good voice if available
for (const searchTerm of ['Neural', 'Premium', 'Natural', 'Enhanced', 'Daniel', 'Samantha', 'Karen']) {
const goodVoice = Array.from(voiceSelect.options).find(option =>
option.text.includes(searchTerm)
);
if (goodVoice) {
voiceSelect.value = goodVoice.value;
break;
}
}
}
// Load voices when available
if (window.speechSynthesis.onvoiceschanged !== undefined) {
window.speechSynthesis.onvoiceschanged = loadVoices;
}
// Initial load attempt
setTimeout(loadVoices, 100);
// Function to extract the haiku text properly
function getHaikuText() {
try {
// First try using innerText
let rawText = haikuText.innerText;
if (rawText && rawText.trim()) {
return rawText.trim();
}
// If that fails, try getting individual text nodes
let lines = [];
Array.from(haikuText.childNodes).forEach(node => {
if (node.nodeType === Node.TEXT_NODE && node.textContent.trim()) {
lines.push(node.textContent.trim());
}
});
// If we got lines, join them
if (lines.length > 0) {
return lines.join(' ');
}
// If nothing worked, fall back to extracting from HTML
return haikuText.textContent.replace(/<br>/g, ' ').trim();
} catch (e) {
console.error("Error extracting haiku text:", e);
try {
return "{{ context.haiku.lines|join(' ') }}";
} catch (e2) {
return "Could not retrieve haiku text.";
}
}
}
// Function to add natural pauses between haiku lines
function addPausesToHaiku(text) {
// Split by line breaks or typical line separators
const lines = text.split(/[\n\r]+|<br>|\. /).filter(line => line.trim().length > 0);
if (lines.length <= 1) {
return text;
}
// Join with pauses (using SSML pause syntax)
return lines.join('. ');
}
speakButton.addEventListener('click', function() {
try {
// If already speaking, stop
if (speaking) {
window.speechSynthesis.cancel();
speaking = false;
speakButton.classList.remove('bg-violet-800');
speakButton.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mr-2" viewBox="0 0 20 20" fill="currentColor"><path fill-rule="evenodd" d="M9.383 3.076A1 1 0 0110 4v12a1 1 0 01-1.707.707L4.586 13H2a1 1 0 01-1-1V8a1 1 0 011-1h2.586l3.707-3.707a1 1 0 011.09-.217zM14.657 2.929a1 1 0 011.414 0A9.972 9.972 0 0119 10a9.972 9.972 0 01-2.929 7.071a1 1 0 01-1.414-1.414A7.971 7.971 0 0017 10c0-2.21-.894-4.208-2.343-5.657a1 1 0 010-1.414zm-2.829 2.828a1 1 0 011.415 0A5.983 5.983 0 0115 10a5.984 5.984 0 01-1.757 4.243a1 1 0 01-1.415-1.415A3.984 3.984 0 0013 10a3.983 3.983 0 00-1.172-2.828a1 1 0 010-1.415z" clip-rule="evenodd" /></svg> Speak Haiku';
return;
}
// Get the haiku text
let textContent = getHaikuText();
console.log("Speaking text:", textContent);
if (!textContent || textContent === "") {
console.error("No text to speak");
alert("No text to speak");
return;
}
// Add natural pauses
textContent = addPausesToHaiku(textContent);
// Create a new speech synthesis instance
const msg = new SpeechSynthesisUtterance();
msg.text = textContent;
// Set human-like speech parameters
msg.rate = 0.85; // Slightly slower pace for poetry
msg.pitch = 1.0; // Natural pitch
msg.volume = 1.0; // Full volume
// Set selected voice if available
if (voiceSelect.value) {
const selectedVoice = voices.find(voice => voice.name === voiceSelect.value);
if (selectedVoice) {
msg.voice = selectedVoice;
}
}
// Stop any ongoing speech
window.speechSynthesis.cancel();
// Set up event handlers
msg.onstart = function() {
speaking = true;
speakButton.classList.add('bg-violet-800');
speakButton.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mr-2" viewBox="0 0 20 20" fill="currentColor"><path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8 7a1 1 0 00-1 1v4a1 1 0 001 1h4a1 1 0 001-1V8a1 1 0 00-1-1H8z" clip-rule="evenodd" /></svg> Stop Speaking';
};
msg.onend = function() {
speaking = false;
speakButton.classList.remove('bg-violet-800');
speakButton.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mr-2" viewBox="0 0 20 20" fill="currentColor"><path fill-rule="evenodd" d="M9.383 3.076A1 1 0 0110 4v12a1 1 0 01-1.707.707L4.586 13H2a1 1 0 01-1-1V8a1 1 0 011-1h2.586l3.707-3.707a1 1 0 011.09-.217zM14.657 2.929a1 1 0 011.414 0A9.972 9.972 0 0119 10a9.972 9.972 0 01-2.929 7.071a1 1 0 01-1.414-1.414A7.971 7.971 0 0017 10c0-2.21-.894-4.208-2.343-5.657a1 1 0 010-1.414zm-2.829 2.828a1 1 0 011.415 0A5.983 5.983 0 0115 10a5.984 5.984 0 01-1.757 4.243a1 1 0 01-1.415-1.415A3.984 3.984 0 0013 10a3.983 3.983 0 00-1.172-2.828a1 1 0 010-1.415z" clip-rule="evenodd" /></svg> Speak Haiku';
};
msg.onerror = function(event) {
console.error("Speech synthesis error:", event);
speaking = false;
speakButton.classList.remove('bg-violet-800');
speakButton.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mr-2" viewBox="0 0 20 20" fill="currentColor"><path fill-rule="evenodd" d="M9.383 3.076A1 1 0 0110 4v12a1 1 0 01-1.707.707L4.586 13H2a1 1 0 01-1-1V8a1 1 0 011-1h2.586l3.707-3.707a1 1 0 011.09-.217zM14.657 2.929a1 1 0 011.414 0A9.972 9.972 0 0119 10a9.972 9.972 0 01-2.929 7.071a1 1 0 01-1.414-1.414A7.971 7.971 0 0017 10c0-2.21-.894-4.208-2.343-5.657a1 1 0 010-1.414zm-2.829 2.828a1 1 0 011.415 0A5.983 5.983 0 0115 10a5.984 5.984 0 01-1.757 4.243a1 1 0 01-1.415-1.415A3.984 3.984 0 0013 10a3.983 3.983 0 00-1.172-2.828a1 1 0 010-1.415z" clip-rule="evenodd" /></svg> Speak Haiku';
};
// Introduce a very slight delay before each line (to ensure natural pacing)
setTimeout(() => {
window.speechSynthesis.speak(msg);
}, 100);
} catch (error) {
console.error("Speech synthesis error:", error);
speaking = false;
speakButton.classList.remove('bg-violet-800');
alert("Speech synthesis failed: " + error.message);
}
});
// Ensure speech is canceled when navigating away from the page
window.addEventListener('beforeunload', function() {
if (window.speechSynthesis) {
window.speechSynthesis.cancel();
}
});
});
</script>
{% endblock %}

View file

@ -0,0 +1,24 @@
{% extends "base.html" %}
{% block content %}
<div class="bg-violet-900 min-h-screen flex items-center justify-center text-white">
<div class="text-center">
<div class="bg-white text-gray-900 p-10 rounded-lg shadow-lg max-w-2xl mx-auto transform -translate-y-10">
<h1 class="text-4xl font-bold text-violet-700 mb-6">{{ title }}</h1>
<p class="text-2xl italic leading-relaxed text-left">
{% for line in context.haiku.lines %}
{{ line }}<br>
{% endfor %}
</p>
</div>
{% if context.is_default %}
<div class="mb-5">
<b>Note:</b> No haikus have been found in the haiku store.
</div>
{% endif %}
<a href="{{ url_for('index_view') }}"
class=" inline-block bg-violet-600 hover:bg-violet-700 text-white font-bold py-2 px-4 rounded-lg">
Back to Home
</a>
</div>
</div>
{% endblock %}

173
senju/templates/info.html Normal file
View file

@ -0,0 +1,173 @@
{% extends "base.html" %} {% block content %}
<style>
.grid-container {
display: grid;
grid-template-columns: repeat(2, 1fr); /* Two columns per row */
gap: 30px;
justify-content: center;
align-items: start;
padding: 50px;
}
.grid-item {
display: flex;
align-items: center;
gap: 20px;
position: relative;
}
/* Parallax Image Effect */
.grid-item img {
--f: 0.1; /* Parallax factor */
--r: 10px; /* Radius */
--_f: calc(100% * var(--f) / (1 + var(--f)));
--_a: calc(90deg * var(--f));
width: 150px;
aspect-ratio: calc(1 + var(--f));
object-fit: cover;
clip-path: inset(0 var(--_f) 0 0 round var(--r));
transform: perspective(400px) var(--_t, rotateY(var(--_a)));
transition: 0.5s;
cursor: pointer;
}
.grid-item img:hover {
clip-path: inset(0 0 0 var(--_f) round var(--r));
--_t: translateX(calc(-1 * var(--_f))) rotateY(calc(-1 * var(--_a)));
}
/* Info Box (No effect, solid background) */
.info-box {
width: 250px;
padding: 12px;
background: #fff; /* Solid white */
border-radius: 10px;
color: black;
text-align: left;
font-family: Arial, sans-serif;
}
.info-box h2 {
margin: 5px 0;
font-size: 18px;
}
.info-box p {
margin: 5px 0;
font-size: 14px;
}
.info-box .title {
font-weight: bold;
}
.button {
background-color: #7c3aed;
border: none;
color: white;
padding: 8px 12px;
text-align: center;
font-size: 14px;
cursor: pointer;
border-radius: 5px;
transition: background 0.3s;
}
.button:hover {
background-color: #8b5cf6;
}
</style>
<div class="grid-container">
<div class="grid-item">
<img
src="https://avatars.githubusercontent.com/u/58274330?v=4"
alt="PlexSheep"
/>
<div class="info-box">
<h2>PlexSheep</h2>
<p class="title text-violet-900">Backend Developer</p>
<p>
Cyber Security Student, passionate Hobbyist, Networkadmin and Sotware
Engineer
</p>
<a href="https://github.com/PlexSheep">Github</a>
<p>software@cscherr.de</p>
<p>
<a href="mailto:software@cscherr.de"
><button class="button">Contact</button></a
>
</p>
</div>
</div>
<div class="grid-item">
<img
src="https://avatars.githubusercontent.com/u/119286812?v=4"
alt="0xjrx"
style="--f: 0.12; --r: 5px"
/>
<div class="info-box">
<h2>0xjrx</h2>
<p class="title text-violet-900">Frontend Developer</p>
<p>Cyber Security Student working on malware research and development.</p>
<a href="https://github.com/0xjrx">Github</a>
<p>mrmarquard@protonmail.com</p>
<p>
<a href="mailto:mrmarquard@protonmail.com"
><button class="button">Contact</button></a
>
</p>
</div>
</div>
<div class="grid-item">
<img
src="https://avatars.githubusercontent.com/u/45919207?v=4"
alt="0xalivecow"
style="--f: 0.08; --r: 20px"
/>
<div class="info-box">
<h2>0xalivecow</h2>
<p class="title text-violet-900">Backend Developer</p>
<p>Cyber Security Student with a focus on Linux Security</p>
<a href="https://github.com/0xalivecow">Github</a>
<p>0xalivecow@ta-lotz.de</p>
<p>
<a href="mailto:0xalivecow@ta-lotz.de"
><button class="button">Contact</button></a
>
</p>
</div>
</div>
<div class="grid-item">
<img
src="https://avatars.githubusercontent.com/u/134395490?v=4"
alt="Amrasil"
style="--f: 0.08; --r: 20px"
/>
<div class="info-box">
<h2>Amrasil</h2>
<p class="title text-violet-900">Documentation and Code coverage</p>
<p>
Cyber Security student passionate about Mathematics and Machine
Learning.
</p>
<a href="https://github.com/Amrasil">Github</a>
<p>amrasil@proton.me</p>
<p>
<a href="mailto:amrasil@proton.me"
><button class="button">Contact</button></a
>
</p>
</div>
</div>
</div>
{% endblock %}

View file

@ -0,0 +1,80 @@
{% extends "base.html" %}
{% block content %}
<div class="flex flex-col items-center justify-center min-h-screen bg-violet-900 text-white p-6">
<div class="bg-white text-gray-900 p-8 rounded-xl shadow-lg max-w-lg w-full text-center transform transition duration-300 hover:scale-105">
<h1 class="text-3xl font-bold text-violet-700 mb-4">Haiku Generator</h1>
<div class="flex flex-col gap-4">
<input
type="text"
id="user-input"
minlength="0"
maxlength="100"
placeholder="Type your prompt here..."
class="w-full px-4 py-3 text-lg border-2 border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-violet-600"
/>
<button
id="submit-btn"
class="bg-violet-600 text-white font-bold py-3 px-6 rounded-lg text-lg shadow-md transition duration-300 hover:bg-violet-700 hover:scale-105"
>
🚀 Submit
</button>
</div>
<div
id="response-box"
class="mt-8 bg-white text-gray-900 p-6 rounded-lg shadow-lg max-w-lg w-full text-center transition-opacity duration-500 ease-in-out"
>
<h2 class="text-2xl font-semibold text-violet-700">Response:</h2>
<p id="ai-response" class="text-lg text-gray-700 mt-2 italic">
Waiting for input...
</p>
</div>
</div>
</div>
</div>
<script>
document.getElementById("submit-btn").addEventListener("click", function () {
let userInput = document.getElementById("user-input").value;
let responseBox = document.getElementById("response-box");
let responseText = document.getElementById("ai-response");
// Hide the response box initially
responseBox.classList.add("opacity-0");
if (userInput.trim() === "") {
responseText.textContent = "Please enter a prompt!";
} else if (userInput.length > 100) {
responseText.textContent = "Input must under 100 characters long!";
} else if (userInput.trim() === "amogus") {
responseText.textContent = "🤖 AI is thinking...";
responseBox.classList.remove("opacity-0");
// Simulated AI response delay
setTimeout(() => {
responseText.textContent = "Sus imposter ඞ";
}, 1500);
} else {
responseText.textContent = "🤖 AI is thinking...";
responseBox.classList.remove("opacity-0");
fetch("/api/v1/haiku", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ prompt: userInput }),
})
.then((response) => response.text())
.then((data) => {
let id = parseInt(data, 10);
window.location.href = "/haiku/" + id;
})
.catch((error) => {
responseText.textContent = "Error: " + error.message;
});
}
});
</script>
{% endblock %}

156
senju/templates/scan.html Normal file
View file

@ -0,0 +1,156 @@
{% extends "base.html" %} {% block content %}
<div
class="flex flex-col items-center justify-center min-h-screen bg-violet-900 text-white p-6"
>
<div
class="bg-white text-gray-900 p-8 rounded-xl shadow-lg max-w-lg w-full text-center transform transition duration-300 hover:scale-105 mb-8"
>
<h1 class="text-3xl font-bold text-violet-700 mb-4">Upload your image</h1>
<!-- File Upload container-->
<div id="upload-area" class="flex items-center justify-center w-full">
<label
for="dropzone-file"
class="flex flex-col items-center justify-center w-full h-64 border-2 border-gray-300 border-dashed rounded-lg cursor-pointer bg-gray-50 dark:hover:bg-gray-800 dark:bg-gray-700 hover:bg-gray-100 dark:border-gray-600 dark:hover:border-gray-500 dark:hover:bg-gray-600"
>
<div class="flex flex-col items-center justify-center pt-5 pb-6">
<svg
class="w-8 h-8 mb-4 text-gray-500 dark:text-gray-400"
aria-hidden="true"
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 20 16"
>
<path
stroke="currentColor"
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M13 13h3a3 3 0 0 0 0-6h-.025A5.56 5.56 0 0 0 16 6.5 5.5 5.5 0 0 0 5.207 5.021C5.137 5.017 5.071 5 5 5a4 4 0 0 0 0 8h2.167M10 15V6m0 0L8 8m2-2 2 2"
/>
</svg>
<p class="mb-2 text-sm text-gray-500 dark:text-gray-400">
<span class="font-semibold">Click to upload</span> or drag and drop
</p>
<p class="text-xs text-gray-500 dark:text-gray-400">
SVG, PNG, JPG or GIF (MAX. 800x400px)
</p>
</div>
<input id="dropzone-file" type="file" accept="image/*" class="hidden" />
</label>
</div>
<!-- Image Preview container-->
<div id="image-preview" class="w-full hidden">
<div class="relative">
<img
id="preview-img"
src=""
alt="Preview"
class="w-full h-auto rounded-lg"
/>
<button
id="remove-image"
class="absolute top-2 right-2 bg-red-500 text-white rounded-full p-1 hover:bg-red-600"
title="Remove image"
>
<svg
xmlns="http://www.w3.org/2000/svg"
class="h-5 w-5"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M6 18L18 6M6 6l12 12"
/>
</svg>
</button>
</div>
</div>
<!-- Error message -->
<div id="error-message" class="mt-4 text-red-500 hidden">
Please upload an image first.
</div>
<button
id="submit-button"
type="submit"
class="mt-6 bg-violet-600 hover:bg-violet-700 text-white font-bold py-2 px-4 rounded transition duration-300"
>
Submit
</button>
</div>
<div
id="response-box"
class="mt-8 bg-white text-gray-900 p-6 rounded-lg shadow-lg max-w-lg w-full text-center opacity-0 transition-opacity duration-500 ease-in-out"
>
<h2 class="text-2xl font-semibold text-violet-700">
AI recognized the following:
</h2>
<p id="ai-response" class="text-lg text-gray-700 mt-2 italic">
Waiting for input...
</p>
<div class="flex justify-center space-x-4">
<button
id="yesButton"
type="button"
class="mt-6 bg-violet-600 hover:bg-violet-700 text-white font-bold py-2 px-4 rounded transition duration-300"
>
Generate Haiku
</button>
<button
id="noButton"
type="button"
class="mt-6 bg-violet-600 hover:bg-violet-700 text-white font-bold py-2 px-4 rounded transition duration-300"
>
Input new image
</button>
</div>
</div>
<!-- New generating haiku div that appears after "Yes" is clicked -->
<div
id="generating-haiku-box"
class="mt-8 bg-white text-gray-900 p-6 rounded-lg shadow-lg max-w-lg w-full text-center hidden transition-opacity duration-500 ease-in-out"
>
<h2 class="text-2xl font-semibold text-violet-700">Generating Haiku</h2>
<div class="flex justify-center mt-4">
<div class="loader animate-pulse flex space-x-4">
<div class="w-3 h-3 bg-violet-600 rounded-full"></div>
<div class="w-3 h-3 bg-violet-600 rounded-full"></div>
<div class="w-3 h-3 bg-violet-600 rounded-full"></div>
</div>
</div>
<p class="text-lg text-gray-700 mt-4 italic">
Creating a beautiful haiku based on your image...
</p>
</div>
<div
id="generated-haiku-box"
class="mt-8 bg-white text-gray-900 p-6 rounded-lg shadow-lg max-w-lg w-full text-center hidden transition-opacity duration-500 ease-in-out"
>
<h2 class="text-2xl font-semibold text-violet-700">
Red suit, vents unseen,<br />
Sus behavior, crew unsure,<br />
Vote him, task complete.
</h2>
<div class="flex justify-center mt-4">
<div class="loader animate-pulse flex space-x-4">
<div class="w-3 h-3 bg-violet-600 rounded-full"></div>
<div class="w-3 h-3 bg-violet-600 rounded-full"></div>
<div class="w-3 h-3 bg-violet-600 rounded-full"></div>
</div>
</div>
<p class="text-lg text-gray-700 mt-4 italic">
Creating a beautiful haiku based on your image...
</p>
</div>
</div>
<script src="/static/js/scan.js"></script>
{% endblock %}

View file

@ -1,11 +1,19 @@
from __future__ import annotations
import tempfile
from pathlib import Path
import pytest
from senju.store_manager import StoreManager
@pytest.fixture(scope="session")
def temp_data_dir():
"""Create a temporary directory for test data"""
return Path(tempfile.mkdtemp())
@pytest.fixture(scope="session")
def store_manager(temp_data_dir):
return StoreManager(temp_data_dir / "store.json")

68
tests/test_haiku.py Normal file
View file

@ -0,0 +1,68 @@
# I do not trust python and it's tests, so I'm testing them. May not be worth
# much, but at least it shows me a few things.
from __future__ import annotations
import json
from pytest_httpserver import HTTPServer
import requests
# do not remove this import. This is needed for
# pytest fixtures to work
import pytest # noqa: F401
from senju.haiku import Haiku # noqa: F401
# Note: these weird arguments are an indicator of what should be dome
# before. For example, `temp_data_dir` is a function in `conftest.py`. If we
# put it in the arguments, it seems to run before our test, and the return
# value becomes a local. This is all very confusing for someone used to
# Rust's libtest
def test_create_haiku():
haiku = Haiku(["line number 1", "line number 2", "line number 3"])
assert haiku.lines[0] == "line number 1"
assert haiku.lines[1] == "line number 2"
assert haiku.lines[2] == "line number 3"
assert len(haiku.lines) == 3
def test_get_haiku_json():
haiku = Haiku(["line number 1", "line number 2", "line number 3"])
data_raw: str = haiku.get_json()
assert data_raw == '["line number 1", "line number 2", "line number 3"]'
data = json.loads(data_raw)
assert haiku.lines[0] == "line number 1"
assert haiku.lines[1] == "line number 2"
assert haiku.lines[2] == "line number 3"
assert len(haiku.lines) == 3
assert data == ['line number 1', 'line number 2', 'line number 3']
def test_request_haiku(httpserver: HTTPServer):
httpserver.expect_request(
"/testhaiku").respond_with_json({"response":
"The apparition of these\n"
"faces in a crowd; Petal\n"
"on a wet, black bough."
})
haiku = Haiku.request_haiku(
"apple banana papaya", url=httpserver.url_for("/testhaiku"))
assert haiku.lines[0] == "The apparition of these"
assert haiku.lines[1] == "faces in a crowd; Petal"
assert haiku.lines[2] == "on a wet, black bough."
assert len(haiku.lines) == 3
def test_request_haiku_respondse_bad(httpserver: HTTPServer):
with pytest.raises(requests.exceptions.JSONDecodeError):
httpserver.expect_request(
"/testhaiku").respond_with_data(
"this is completely wrong" + ("A" * 50 + "\n") * 20)
Haiku.request_haiku(
"apple banana papaya", url=httpserver.url_for("/testhaiku"))

95
tests/test_store.py Normal file
View file

@ -0,0 +1,95 @@
# do not remove this import. This is needed for
# pytest fixtures to work
from __future__ import annotations
import pytest # noqa: F401
import os
from senju.haiku import DEFAULT_HAIKU, Haiku
from senju.store_manager import StoreManager # noqa: F401
def test_temp_data_dir(temp_data_dir):
print(temp_data_dir)
testpath = temp_data_dir / "__test"
with open(testpath, "w") as f:
f.write("that dir actually works")
os.remove(testpath)
assert not os.path.exists(testpath)
def test_save_and_load_any(store_manager: StoreManager):
thing = {
"color": "blue",
"number": 19,
"inner": {
"no": "yes"
}
}
thing_id = store_manager._save(thing)
thing_loaded = store_manager._load(thing_id)
if thing_loaded is None:
assert False, "store manager load did not return anything but \
should have"
for key in thing.keys():
assert thing[key] == thing_loaded[key]
def test_save_and_load_haiku(store_manager: StoreManager):
h = Haiku(lines=["foobar", "qux"])
hid = store_manager.save_haiku(h)
h_loaded = store_manager.load_haiku(hid)
if h_loaded is None:
assert False, "store manager load_haiku did not return anything \
but should have"
assert h == h_loaded
assert h != DEFAULT_HAIKU
def test_load_latest_with_empty_store(temp_data_dir):
store = StoreManager(temp_data_dir / "empty_store.json")
h = store.get_id_of_latest_haiku()
assert h is None
def test_load_latest_or_default_with_empty(temp_data_dir):
store = StoreManager(temp_data_dir / "load_or_default_empty.json")
haiku = store.load_haiku(store.get_id_of_latest_haiku())
assert haiku == DEFAULT_HAIKU
def test_load_latest_or_default_with_non_empty(temp_data_dir):
store = StoreManager(temp_data_dir / "load_or_default_not_empty.json")
nonsense_test_haiku = Haiku(["nonsense", "test", "haiku"])
store.save_haiku(nonsense_test_haiku)
haiku = store.load_haiku(store.get_id_of_latest_haiku())
assert haiku != DEFAULT_HAIKU
assert haiku == nonsense_test_haiku
def test_load_latest_with_non_empty_store(temp_data_dir):
store = StoreManager(temp_data_dir / "empty_store.json")
store.save_haiku(Haiku(["hello", "world", "bananenkrokodil"]))
h = store.get_id_of_latest_haiku()
assert h is not None
assert h > 0
def test_create_store_with_bad_file(temp_data_dir):
with pytest.raises(Exception):
testpath = temp_data_dir / "non_empty.json"
with open(testpath, "w") as f:
f.write("BUT IT DOES NOT ACTUALLY HAVE JSON")
store = StoreManager(testpath)
store._save({"hello": 19})
def test_create_store_with_non_empty(temp_data_dir):
testpath = temp_data_dir / "non_empty.json"
with open(testpath, "w") as f:
f.write('{"this": ["is","valid","json"]}')
store = StoreManager(testpath)
store._save({"hello": 19})

View file

@ -1,25 +0,0 @@
# I do not trust python and it's tests, so I'm testing them. May not be worth much, but at least it shows me a few things.
import os
import pytest # noqa: F401 do not remove this import. This is needed for pytest fixtures to work
import senju # noqa: F401
# Note: these weird arguments are an indicator of what should be dome before. For example,
# `temp_data_dir` is a function in `conftest.py`. If we put it in the arguments, it seems
# to run before our test, and the return value becomes a local.
#
# This is all very confusing for someone used to Rust's libtest
def test_tests_are_loaded():
assert True # if we make it here, they are
def test_temp_data_dir(temp_data_dir):
print(temp_data_dir)
testpath = temp_data_dir / "__test"
with open(testpath, "w") as f:
f.write("that dir actually works")
os.remove(testpath)