This commit is contained in:
Michael S. 2024-06-17 17:13:32 +02:00
commit ba3e29d955
8 changed files with 372 additions and 0 deletions

160
.gitignore vendored Normal file
View file

@ -0,0 +1,160 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
.pybuilder/
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock
# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/#use-with-ide
.pdm.toml
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# pytype static type analyzer
.pytype/
# Cython debug symbols
cython_debug/
# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/

9
README.md Normal file
View file

@ -0,0 +1,9 @@
# Nahrung Analysierung
An example of a minimal Flet app.
To run the app:
```
flet run [app_directory]
```

BIN
assets/icon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.6 KiB

16
file_handler.py Normal file
View file

@ -0,0 +1,16 @@
import json
def save(jsettings,jhisory):
with open("saves/settings.json", "w") as data:
data.write(json.dumps(jsettings,indent=4))
with open("saves/history.json", "w") as data:
data.write(json.dumps(jhisory,indent=4))
def load(self) -> list:
with open("saves/settings.json", "r") as data:
jsettings = json.load(data)
with open("saves/history.json", "r") as data:
jhistory = json.load(data)
return jsettings,jhistory

182
main.py Normal file
View file

@ -0,0 +1,182 @@
import flet as ft
import file_handler
from datetime import datetime
from random import choice
def get_time():
t = datetime.now()
return [t.year, t.month, t.day, t.hour, t.minute, t.second]
def random_emoji():
return choice("🍎🍐🍊🍋🍌🍉🍇🍓🍈🍒🍑🍍🥝🥭🥑🍅🍆🥒🥕🥬🌽🥔🍠🌰🥜🍯🥐🍞🥖🥨🥯🧀🥚🍳🥓🧄🧅🥞🧇🍤🍗🍖🍕🌭🍔🍟🥙🌮🌯🥗🥘🍝🍜🦪🍲🍥🍣🍱🍛🍚🧆🍙🍘🍢🍡🍧🍨🍦🍰🎂🍮🍭🍬🍫🍿🍩🍪🥮🧁🥛🧈🍼☕🍵🍶🍺🍻🥂🍷🥃🍸🍹🍾🧉🧃🧊🧂🥄🍴")
class Nahrung(ft.UserControl):
def __init__(self) -> None:
super().__init__()
self.settings, self.history = file_handler.load(self)
self.kjtext = ft.Text("0", size=25)
self.kcaltext = ft.Text("0", size=30)
self.kcaltextfield = ft.TextField(keyboard_type="NUMBER",expand=True,autofocus=True,on_change=self.reseterrorinkcaltextfield,on_submit=self.editkcal)
# Initialize history list
self.historylist = []
self.update_history()
# Initialize controls
self.main_container = ft.Container(
content=ft.Column(
[
ft.Row(
[
ft.Text("kjoule:", size=20),
self.kjtext,
ft.Text(f"/{round(self.settings['kcal_max'] * 4.184, 0)}", size=10)
]
),
ft.Row(
[
ft.Text("kcal:", size=25),
self.kcaltext,
ft.Text(f"/{self.settings['kcal_max']}", size=10)
]
),
ft.Row(
[
self.kcaltextfield,
ft.FloatingActionButton(icon="add", on_click=self.editkcal)
]
),
]
),
bgcolor=ft.colors.INDIGO_400,
border_radius=10,
padding=15,
)
self.history_container = ft.Container(
content=ft.Column([ft.Text("Verlauf:"),
ft.Column(controls=self.historylist)
]),
)
self.controls = [self.main_container, self.history_container]
self.load_todays_kcal()
def reseterrorinkcaltextfield(self):
self.kcaltextfield.error_text = ""
def build(self):
self.kjtext.value = str(round(int(self.kcaltext.value) * 4.184, 0))
return ft.Column(self.controls)
def editkcal(self, e):
try:
emoji = random_emoji()
print(emoji,ord(emoji))
new_kcal = int(self.kcaltext.value) + int(self.kcaltextfield.value)
self.kcaltext.value = str(new_kcal)
self.kjtext.value = str(round(new_kcal * 4.184, 0))
self.history.append([emoji, self.kcaltextfield.value, get_time()])
file_handler.save(self.settings, self.history) # Save the updated kcal value
self.update_history()
self.reseterrorinkcaltextfield()
self.kcaltextfield.value = ""
self.update() # Update the controls to reflect changes
except ValueError:
print("error")
self.kcaltextfield.error_text = "\\(*O*)/ nicht verschreiben!!"
self.update()
#pass # Handle invalid input gracefully
def create_appbar(self):
return ft.AppBar(
title=ft.Text("Nahrungstracker"),
actions=[
ft.PopupMenuButton(
items=[ft.PopupMenuItem(text="Reset", on_click=self.resethistory)]
)
],
)
def update_history(self):
self.historylist.clear()
for h in self.history:
self.historylist.insert(0,
ft.Container(content=
ft.Column(controls=[
ft.Row(
[ft.Text(str(f"{h[2][3]}:{h[2][4]}:{h[2][5]} {h[2][2]}.{h[2][1]}.{h[2][0]}"))],
alignment=ft.MainAxisAlignment.END
),
ft.Row(
[ft.Text(str(f"({h[1]} kcal) {h[0]}"), size=20)],
alignment=ft.MainAxisAlignment.START,
)]),
bgcolor=ft.colors.INDIGO_600, # "#226666",
border_radius=5,
padding=6
)
)
def resethistory(self, e):
print("pressed")
def reset(e):
self.kcaltext.value = "0"
self.kjtext.value = "0"
self.history = []
file_handler.save(self.settings, self.history)
self.update_history()
self.history_container.content = ft.Column(self.historylist)
self.dialog.open = False
# beide updaten
self.page.update()
self.update()
def close(e):
self.dialog.open = False
# beide updaten
self.page.update()
self.update()
self.dialog = ft.AlertDialog(
modal=True,
title=ft.Text("Wirklich?"),
content=ft.Text("Alle Daten werden aus deinem Verlauf gelöscht!!!"),
actions=[
ft.TextButton("ja", on_click=reset),
ft.TextButton("nein", on_click=close),
],
actions_alignment=ft.MainAxisAlignment.END,
on_dismiss=lambda e: print("Modal dialog dismissed!"),
)
self.page.dialog = self.dialog
self.dialog.open = True
self.page.update()
def load_todays_kcal(self):
today_date = get_time()[:3]
print(today_date)
todays_kcal = 0
for entry in self.history:
entry_date = entry[2][:3] # Year, Month, Day part of the entry's timestamp
if entry_date == today_date:
todays_kcal += int(entry[1])
self.kcaltext.value = str(todays_kcal)
def main(page: ft.Page):
page.title = "Nahrungstracker"
page.scroll = True
nahrung = Nahrung()
nahrung.page = page # Store reference to the page in Nahrung instance
page.appbar = nahrung.create_appbar()
page.add(nahrung)
page.update() # Ensure the initial UI is updated
if __name__ == "__main__":
ft.app(target=main)

1
requirements.txt Normal file
View file

@ -0,0 +1 @@
flet==0.22.*

1
saves/history.json Normal file
View file

@ -0,0 +1 @@
[]

3
saves/settings.json Normal file
View file

@ -0,0 +1,3 @@
{
"kcal_max": 2000
}