Compare commits

..

No commits in common. "f58f55f68b7907db3c1f606a57df81b9f18f5dce" and "1fd1de2f82761d56b4fc579c9f4d6eb62aef3263" have entirely different histories.

22 changed files with 733 additions and 1166 deletions

156
Programming/ERSMS-project/analytics/analytics.py Executable file → Normal file
View File

@ -1,79 +1,39 @@
#!/usr/bin/env python3
"""Read-only rating statistics over the shared Postgres database.
Every route is cached, because these are dashboard numbers that nobody needs
to the second and each one is a full table scan.
"""
from __future__ import annotations
import logging
import os
import time
from configparser import ConfigParser
from dataclasses import dataclass
from typing import TYPE_CHECKING
import psycopg2
from flask import Flask, jsonify
from flask_caching import Cache
if TYPE_CHECKING:
from flask.typing import ResponseReturnValue
logger = logging.getLogger(__name__)
HTTP_OK = 200
# The database container may still be starting when this one is ready.
DB_RETRY_SECONDS = 1
@dataclass
class Database:
"""The Postgres connection the routes share, opened once at start-up."""
conn: psycopg2.extensions.connection | None = None
def cursor(self) -> psycopg2.extensions.cursor:
"""Return a cursor, or fail loudly if start-up never connected."""
if self.conn is None:
msg = "the database connection was never opened"
raise RuntimeError(msg)
return self.conn.cursor()
app = Flask(__name__)
cache = Cache(config={"CACHE_TYPE": "SimpleCache"})
DB = Database()
db_connector = None
conn = None
@app.route("/api/get_number_of_ratings", methods=["GET"])
@cache.cached(timeout=500)
def get_number_of_ratings() -> ResponseReturnValue:
"""Return how many ratings exist in total."""
cursor = DB.cursor()
def get_number_of_ratings():
cursor = conn.cursor()
cursor.execute("select count(*) as num_of_ratings from ratings")
res = cursor.fetchall()
cursor.close()
return jsonify(res[0]), HTTP_OK
return jsonify(res[0]), 200
@app.route("/api/get_movie_ratings/<string:movie_id>", methods=["GET"])
@cache.cached(timeout=50)
def get_movie_ratings(movie_id: str) -> ResponseReturnValue:
"""Return how many one- to five-star ratings one film has."""
cursor = DB.cursor()
def get_movie_ratings(movie_id):
cursor = conn.cursor()
ratings = {}
rating_values = [5, 4, 3, 2, 1]
for rating in rating_values:
cursor.execute(
"""
SELECT COUNT(*) as count
FROM ratings
SELECT COUNT(*) as count
FROM ratings
WHERE rating = %s AND movie_ID = %s;
""",
(rating, movie_id),
@ -83,31 +43,29 @@ def get_movie_ratings(movie_id: str) -> ResponseReturnValue:
cursor.close()
return jsonify(ratings), HTTP_OK
return jsonify(ratings), 200
@app.route("/api/get_users_number", methods=["GET"])
@cache.cached(timeout=50)
def get_number_of_users() -> ResponseReturnValue:
"""Return how many users are registered."""
cursor = DB.cursor()
def get_number_of_users():
cursor = conn.cursor()
cursor.execute("select count(*) as num_of_users from users")
res = cursor.fetchall()
cursor.close()
return jsonify(res[0]), HTTP_OK
return jsonify(res[0]), 200
@app.route("/api/get_movie_rating_avg/<string:movie_id>", methods=["GET"])
@cache.cached(timeout=50)
def get_movie_rating_avg(movie_id: str) -> ResponseReturnValue:
"""Return one film's mean rating."""
cursor = DB.cursor()
def get_movie_rating_avg(movie_id):
cursor = conn.cursor()
cursor.execute(
"""
SELECT AVG(rating) as avg_rating
FROM ratings
SELECT AVG(rating) as avg_rating
FROM ratings
WHERE movie_ID = %s;
""",
(movie_id,),
@ -116,18 +74,17 @@ def get_movie_rating_avg(movie_id: str) -> ResponseReturnValue:
cursor.close()
return jsonify(res[0]), HTTP_OK
return jsonify(res[0]), 200
@app.route("/api/get_user_ratings/<string:user_id>", methods=["GET"])
@cache.cached(timeout=50)
def get_user_ratings(user_id: str) -> ResponseReturnValue:
"""Return every rating one user has given."""
cursor = DB.cursor()
def get_user_ratings(user_id):
cursor = conn.cursor()
cursor.execute(
"""
SELECT movie_ID, rating
FROM ratings
SELECT movie_ID, rating
FROM ratings
WHERE oauth_ID = %s;
""",
(user_id,),
@ -136,51 +93,30 @@ def get_user_ratings(user_id: str) -> ResponseReturnValue:
cursor.close()
return jsonify(res), HTTP_OK
def try_connect(config: ConfigParser) -> psycopg2.extensions.connection | None:
"""Return a connection, or None if the database is not accepting them yet."""
try:
return psycopg2.connect(
host=config["postgres"]["host"],
database=config["postgres"]["database"],
user=config["postgres"]["user"],
password=config["postgres"]["password"],
port=int(config["postgres"]["port"]),
)
except psycopg2.OperationalError:
return None
def connect_with_retry(config: ConfigParser) -> psycopg2.extensions.connection:
"""Block until Postgres accepts a connection, then return it."""
connection = try_connect(config)
while connection is None:
logger.info("Trying to connect with database")
time.sleep(DB_RETRY_SECONDS)
connection = try_connect(config)
return connection
def main() -> None:
"""Connect to the database and serve until stopped."""
config = ConfigParser()
config.read("init_scripts/constants.ini")
DB.conn = connect_with_retry(config)
cache.init_app(app)
try:
# docker-compose sets ERSMS_HOST; see backend/app.py for why.
app.run(
host=os.environ.get("ERSMS_HOST", "127.0.0.1"),
port=8082,
debug=os.environ.get("FLASK_DEBUG") == "1",
)
finally:
DB.conn.close()
return jsonify(res), 200
if __name__ == "__main__":
logging.basicConfig(format="%(message)s", level=logging.INFO)
main()
config = ConfigParser()
config.read("init_scripts/constants.ini")
while True:
try:
conn = psycopg2.connect(
host=config["postgres"]["host"],
database=config["postgres"]["database"],
user=config["postgres"]["user"],
password=config["postgres"]["password"],
port=int(config["postgres"]["port"]),
)
except Exception:
print("Trying to connect with database")
continue
else:
break
cache.init_app(app)
app.run(host="localhost", port=8082, debug=True)
conn.close()

168
Programming/ERSMS-project/backend/app.py Executable file → Normal file
View File

@ -1,45 +1,16 @@
#!/usr/bin/env python3
"""The Firebase-authenticated API: log in, rate a movie, look films up on TMDB.
Every route takes a Firebase ID token in the request body, verifies it, and
uses the uid inside it as the identity. Ratings live in a local SQLite file;
film metadata is proxied from TMDB.
"""
from __future__ import annotations
import logging
import os
from typing import TYPE_CHECKING
import firebase_admin
import requests
from dotenv import load_dotenv
from firebase_admin import auth, credentials, exceptions
from firebase_admin import auth, credentials
from flask import Flask, jsonify, request
from flask_cors import CORS
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.exc import SQLAlchemyError
if TYPE_CHECKING:
from flask.typing import ResponseReturnValue
logger = logging.getLogger(__name__)
load_dotenv()
TMDB_BEARER_TOKEN = os.getenv("TMDB_BEARER_TOKEN")
# TMDB is a third party over the internet; never wait on it indefinitely.
TMDB_TIMEOUT_SECONDS = 10
HTTP_OK = 200
HTTP_CREATED = 201
HTTP_UNAUTHORIZED = 401
HTTP_INTERNAL_SERVER_ERROR = 500
# A token that will not verify, and a request the token owner may not make.
AUTH_ERRORS = (exceptions.FirebaseError, ValueError, KeyError)
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///app.sqlite3"
app.config["SQLALCHEY_TRACK_MODIFICATIONS"] = False
@ -53,8 +24,6 @@ firebase_admin.initialize_app(cred)
class User(db.Model):
"""One Firebase account, remembered so ratings have an owner."""
id = db.Column(db.Integer, primary_key=True)
uid = db.Column(db.String(80), unique=True, nullable=False)
email = db.Column(db.String(80), unique=True, nullable=False)
@ -62,8 +31,6 @@ class User(db.Model):
class Rating(db.Model):
"""One user's score for one film."""
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey("user.uid"), nullable=False)
movie_id = db.Column(db.Integer, nullable=False)
@ -75,13 +42,12 @@ with app.app_context():
@app.route("/login", methods=["POST"])
def login() -> ResponseReturnValue:
"""Verify the token and create the user row if this is their first visit."""
def login():
token = request.json.get("token")
try:
decoded_token = auth.verify_id_token(token)
uid = decoded_token["uid"]
logger.info("login: %s", uid)
print(uid)
email = decoded_token.get("email")
user = User.query.filter_by(uid=uid).first()
@ -90,17 +56,17 @@ def login() -> ResponseReturnValue:
db.session.add(user)
db.session.commit()
except (*AUTH_ERRORS, SQLAlchemyError):
logger.exception("Login failed")
return jsonify({"message": "Login failed"}), HTTP_UNAUTHORIZED
return jsonify(
{"message": "Login successful!", "email": email, "is_admin": user.is_admin}
), HTTP_OK
return jsonify(
{"message": "Login successful!", "email": email, "is_admin": user.is_admin}
), 200
except Exception as e:
print(e)
return jsonify({"message": "Login failed"}), 401
@app.route("/count_user_ratings", methods=["POST"])
def count_user_ratings() -> ResponseReturnValue:
"""Return how many films this user has rated."""
def count_user_ratings():
token = request.json.get("token")
try:
decoded_token = auth.verify_id_token(token)
@ -108,36 +74,34 @@ def count_user_ratings() -> ResponseReturnValue:
user = User.query.filter_by(uid=user_id).first()
if user is None:
return jsonify({"message": "Error"}), HTTP_INTERNAL_SERVER_ERROR
return jsonify({"message": "Error"}), 500
rating_count = Rating.query.filter_by(user_id=user_id).count()
except (*AUTH_ERRORS, SQLAlchemyError) as exc:
logger.exception("Could not count ratings")
return jsonify({"message": str(exc)}), HTTP_INTERNAL_SERVER_ERROR
return jsonify(
{"message": "Ratings counted!", "rating_count": rating_count}
), HTTP_OK
return jsonify(
{"message": "Ratings counted!", "rating_count": rating_count}
), 200
except Exception as e:
print(e)
return jsonify({"message": str(e)}), 500
@app.route("/movie/<int:movie_id>", methods=["GET"])
def get_tmdb_data_movie_id(movie_id: int) -> ResponseReturnValue:
"""Proxy one film's TMDB record."""
def get_tmdb_data_movie_id(movie_id):
url = f"https://api.themoviedb.org/3/movie/{movie_id}"
headers = {"Authorization": f"Bearer {TMDB_BEARER_TOKEN}"}
try:
response = requests.get(url, headers=headers, timeout=TMDB_TIMEOUT_SECONDS)
response = requests.get(url, headers=headers)
response.raise_for_status()
except requests.RequestException as exc:
logger.exception("TMDB lookup failed for %s", movie_id)
return jsonify({"message": str(exc)}), HTTP_INTERNAL_SERVER_ERROR
return jsonify(response.json()), HTTP_OK
return jsonify(response.json()), 200
except Exception as e:
print(e)
return jsonify({"message": str(e)}), 500
@app.route("/movie", methods=["GET"])
def get_tmdb_data_query() -> ResponseReturnValue:
"""Search TMDB, or return what is trending today when there is no query."""
def get_tmdb_data_query():
query = request.args.get("query")
if query:
@ -148,17 +112,16 @@ def get_tmdb_data_query() -> ResponseReturnValue:
headers = {"Authorization": f"Bearer {TMDB_BEARER_TOKEN}"}
try:
response = requests.get(url, headers=headers, timeout=TMDB_TIMEOUT_SECONDS)
response = requests.get(url, headers=headers)
response.raise_for_status()
except requests.RequestException as exc:
logger.exception("TMDB search failed")
return jsonify({"message": str(exc)}), HTTP_INTERNAL_SERVER_ERROR
return jsonify(response.json()), HTTP_OK
return jsonify(response.json()), 200
except Exception as e:
print(e)
return jsonify({"message": str(e)}), 500
@app.route("/rating", methods=["POST"])
def add_rating() -> ResponseReturnValue:
"""Record this user's score for a film, or update it if they had one."""
def add_rating():
token = request.json.get("token")
movie = request.json.get("movie")
value = request.json.get("value")
@ -166,6 +129,10 @@ def add_rating() -> ResponseReturnValue:
decoded_token = auth.verify_id_token(token)
user_id = decoded_token["uid"]
# user = User.query.filter_by(uid=user_id).first()
# if user is None:
# return jsonify({'message': 'Error'}), 500
rating = Rating.query.filter_by(user_id=user_id, movie_id=movie).first()
if rating is None:
rating = Rating(user_id=user_id, movie_id=movie, value=value)
@ -173,64 +140,67 @@ def add_rating() -> ResponseReturnValue:
db.session.add(rating)
db.session.commit()
return jsonify({"message": "Rating added successfully!"}), HTTP_CREATED
return jsonify({"message": "Rating added successfully!"}), 201
rating.value = value
db.session.commit()
except (*AUTH_ERRORS, SQLAlchemyError) as exc:
logger.exception("Could not add rating")
return jsonify({"message": str(exc)}), HTTP_INTERNAL_SERVER_ERROR
return jsonify({"message": "Rating updated successfully!"}), HTTP_OK
return jsonify({"message": "Rating updated successfully!"}), 200
except Exception as e:
print(e)
return jsonify({"message": str(e)}), 500
@app.route("/rating", methods=["DELETE"])
def remove_rating() -> ResponseReturnValue:
"""Delete this user's score for a film."""
def remove_rating():
token = request.json.get("token")
movie = request.json.get("movie")
try:
decoded_token = auth.verify_id_token(token)
user_id = decoded_token["uid"]
# user = User.query.filter_by(uid=user_id).first()
# if user is None:
# return jsonify({'message': 'Error'}), 500
rating = Rating.query.filter_by(user_id=user_id, movie_id=movie).first()
if rating is None:
return jsonify({"message": "Error"}), HTTP_INTERNAL_SERVER_ERROR
return jsonify({"message": "Error"}), 500
db.session.delete(rating)
db.session.commit()
except (*AUTH_ERRORS, SQLAlchemyError) as exc:
logger.exception("Could not remove rating")
return jsonify({"message": str(exc)}), HTTP_INTERNAL_SERVER_ERROR
return jsonify({"message": "Rating removed successfully!"}), HTTP_OK
return jsonify({"message": "Rating removed successfully!"}), 200
except Exception as e:
print(e)
return jsonify({"message": str(e)}), 500
@app.route("/get_rating", methods=["POST"])
def get_rating() -> ResponseReturnValue:
"""Return this user's score for a film, if they have given one."""
def get_rating():
token = request.json.get("token")
movie = request.json.get("movie")
try:
decoded_token = auth.verify_id_token(token)
user_id = decoded_token["uid"]
# user = User.query.filter_by(uid=user_id).first()
# if user is None:
# return jsonify({'message': 'Error'}), 500
rating = Rating.query.filter_by(user_id=user_id, movie_id=movie).first()
if rating is None:
return jsonify({"message": "Rating not found!"}), HTTP_OK
except (*AUTH_ERRORS, SQLAlchemyError) as exc:
logger.exception("Could not read rating")
return jsonify({"message": str(exc)}), HTTP_INTERNAL_SERVER_ERROR
return jsonify(
{
"message": "Rating found!",
"movie": rating.movie_id,
"value": rating.value,
}
), HTTP_OK
return jsonify({"message": "Rating not found!"}), 200
return jsonify(
{
"message": "Rating found!",
"movie": rating.movie_id,
"value": rating.value,
}
), 200
except Exception as e:
print(e)
return jsonify({"message": str(e)}), 500
if __name__ == "__main__":
logging.basicConfig(format="%(message)s", level=logging.INFO)
# Inside a container the service must bind every interface or the
# published port is unreachable, so docker-compose sets ERSMS_HOST. The
# default is loopback, which is the safe thing to do outside Docker.
app.run(host=os.environ.get("ERSMS_HOST", "127.0.0.1"), port=8084)
app.run(host="0.0.0.0", port=8084)

View File

@ -1,279 +1,170 @@
#!/usr/bin/env python3
"""The API the frontend talks to: users, ratings, and film metadata.
Every query is parameterised. They used to be f-strings holding a username or
an OAuth id straight out of the URL, which meant any caller could end the
statement and append their own.
"""
from __future__ import annotations
import json
import logging
import os
import time
from configparser import ConfigParser
from dataclasses import dataclass
from datetime import datetime, timezone
from typing import TYPE_CHECKING
from datetime import datetime
import pandas as pd
import pandas
import psycopg2
import requests
from flask import Flask, jsonify
from flask_caching import Cache
if TYPE_CHECKING:
from flask.typing import ResponseReturnValue
logger = logging.getLogger(__name__)
HTTP_OK = 200
HTTP_NOT_FOUND = 404
HTTP_CONFLICT = 409
HTTP_BAD_REQUEST = 400
HTTP_INTERNAL_SERVER_ERROR = 500
MIN_RATING = 1
MAX_RATING = 5
# The recommender is a sibling container; never wait on it indefinitely.
RECOMMENDER_TIMEOUT_SECONDS = 30
# The database container may still be starting when this one is ready.
DB_RETRY_SECONDS = 1
@dataclass
class Database:
"""The Postgres connection the routes share, opened once at start-up."""
conn: psycopg2.extensions.connection | None = None
def cursor(self) -> psycopg2.extensions.cursor:
"""Return a cursor, or fail loudly if start-up never connected."""
if self.conn is None:
msg = "the database connection was never opened"
raise RuntimeError(msg)
return self.conn.cursor()
def commit(self) -> None:
"""Commit the current transaction."""
if self.conn is None:
msg = "the database connection was never opened"
raise RuntimeError(msg)
self.conn.commit()
@dataclass
class Movies:
"""The film metadata table, read from CSV once at start-up."""
frame: pd.DataFrame | None = None
def rows(self) -> pd.DataFrame:
"""Return the table, or fail loudly if start-up never loaded it."""
if self.frame is None:
msg = "the movie list was never loaded"
raise RuntimeError(msg)
return self.frame
app = Flask(__name__)
cache = Cache(config={"CACHE_TYPE": "SimpleCache"})
DB = Database()
MOVIES = Movies()
db_connector = None
conn = None
movie_list = None
def error_decorator(fun):
def inner1(*args, **kwargs):
try:
fun(*args, **kwargs)
except psycopg2.DatabaseError:
return jsonify(
{"status": "Something... unexpected has occurred :sweat_smile:"}
), 500
return inner1
@app.route("/", methods=["GET"])
@cache.cached(timeout=69)
def hello() -> ResponseReturnValue:
"""Liveness check."""
return jsonify(
{"response": "Hello there", "time": datetime.now(tz=timezone.utc)}
), HTTP_OK
def hello():
return jsonify({"response": "Hello there", "time": datetime.now()}), 200
# endpoint do wyciągania danych o userze
@app.route("/api/v3/get/<string:username>", methods=["GET"])
def access_user(username: str) -> ResponseReturnValue:
"""Return the row for one username."""
cursor = DB.cursor()
cursor.execute("select * from users where username=%s;", (username,))
def access_user(username):
cursor = conn.cursor()
cursor.execute(f"select * from users where username='{username}';")
res = cursor.fetchall()
cursor.close()
return jsonify(res[0]), HTTP_OK
return jsonify(res[0]), 200
# endpoint służący do zapisu danych nowo stworzonego użytkownika, podajemy mu
# id z oautha oraz login
@app.route("/api/v3/add/<string:oauth_id>/<string:username>", methods=["POST"])
def add_user(oauth_id: str, username: str) -> ResponseReturnValue:
"""Create a user, unless that username is taken."""
cursor = DB.cursor()
cursor.execute("select * from users where username=%s;", (username,))
@app.route("/api/v3/add/<string:oauth_ID>/<string:username>", methods=["POST"])
def add_user(oauth_ID, username):
cursor = conn.cursor()
cursor.execute(f"select * from users where username='{username}';")
res = cursor.fetchall()
if len(res):
cursor.close()
return jsonify({"status": "User already exists"}), HTTP_CONFLICT
return jsonify({"status": "User already exists"}), 409
cursor.execute(
"INSERT INTO users (username, oauth_ID) VALUES (%s, %s);",
(username, oauth_id),
f"INSERT INTO users (username, oauth_ID) VALUES ('{username}','{oauth_ID}');"
)
DB.commit()
conn.commit()
cursor.close()
return jsonify({"status": "success"}), HTTP_OK
return jsonify({"status": "success"}), 200
# roboczy endpoint służący do wyciąganiu rekomendacji
@app.route("/api/v3/ai/<string:oauth_id>", methods=["GET"])
def get_recommendations(oauth_id: str) -> ResponseReturnValue:
"""Ask the recommender for films to suggest to this user."""
cursor = DB.cursor()
cursor.execute("select movie_ID from ratings where oauth_ID=%s;", (oauth_id,))
@app.route("/api/v3/ai/<string:oauth_ID>", methods=["GET"])
def get_recommendations(oauth_ID):
cursor = conn.cursor()
cursor.execute("select movie_ID from ratings where oauth_ID='{}'", oauth_ID)
res = cursor.fetchall()
cursor.close()
movies = [int(row[0]) for row in res]
movies = [int(i) for i in res[0]]
url = "http://localhost:8081/api/v3/AI_recommendations"
try:
response = requests.post(
url,
json=movies,
headers={"Content-Type": "application/json"},
timeout=RECOMMENDER_TIMEOUT_SECONDS,
)
response.raise_for_status()
except requests.RequestException as exc:
logger.exception("Recommender call failed")
return jsonify({"status": str(exc)}), HTTP_INTERNAL_SERVER_ERROR
return jsonify(response.json()), HTTP_OK
response = requests.post(
url, json=movies, headers={"Content-Type": "application/json"}
)
return jsonify(response.json()), 200
@app.route("/api/v3/get_movie/<int:movie_id>", methods=["GET"])
def get_movie(movie_id: int) -> ResponseReturnValue:
"""Return one film's title, cast and crew."""
rows = MOVIES.rows()
movie_info = rows.loc[rows["movie_id"] == movie_id]
@app.route("/api/v3/get_movie/<int:movie_ID>", methods=["GET"])
def get_movie(movie_ID):
movie_info = movie_list.loc[movie_list["movie_id"] == movie_ID]
if movie_info.empty:
return jsonify(
{"status": f"Movie with ID {movie_id} doesn't exist"}
), HTTP_NOT_FOUND
return jsonify({"status": f"Movie with ID {movie_ID} doesn't exist"}), 404
cast = json.loads(movie_info["cast"][0].replace('\\"', '"'))
crew = json.loads(movie_info["crew"][0].replace('\\"', '"'))
output_json = {
"movie_id": movie_id,
"movie_id": movie_ID,
"title": movie_info["title"][0],
"cast": cast,
"crew": crew,
}
return jsonify(output_json), HTTP_OK
return jsonify(output_json), 200
@app.route(
"/api/v3/rate_movie/<string:user_id>/<string:movie_id>/<int:rating>",
methods=["POST"],
"/api/v3/rate_movie/<string:uID>/<string:movie_ID>/<int:rating>", methods=["POST"]
)
def rate_movie(user_id: str, movie_id: str, rating: int) -> ResponseReturnValue:
"""Record or update this user's rating for a film."""
rows = MOVIES.rows()
movie_info = rows.loc[rows["movie_id"] == int(movie_id)]
def rate_movie(uID, movie_ID, rating):
movie_info = movie_list.loc[movie_list["movie_id"] == int(movie_ID)]
if movie_info.empty:
return jsonify(
{"status": f"Movie with ID {movie_id} doesn't exist"}
), HTTP_NOT_FOUND
return jsonify({"status": f"Movie with ID {movie_ID} doesn't exist"}), 404
if rating < MIN_RATING or rating > MAX_RATING:
return jsonify({"status": "Incorrect rating"}), HTTP_BAD_REQUEST
if rating < 1 or rating > 5:
return jsonify({"status": "Incorrect rating"}), 400
cursor = DB.cursor()
cursor.execute("select * from users where oauth_ID=%s;", (user_id,))
cursor = conn.cursor()
cursor.execute(f"select * from users where oauth_ID='{uID}';")
res = cursor.fetchall()
if not len(res):
cursor.close()
return jsonify({"status": "User doesn't exists"}), HTTP_NOT_FOUND
return jsonify({"status": "User doesn't exists"}), 404
cursor.execute(
"select * from ratings where oauth_ID=%s AND movie_ID=%s;",
(user_id, movie_id),
f"select * from ratings where oauth_ID='{uID}' AND movie_ID='{movie_ID}';"
)
res = cursor.fetchall()
if len(res):
cursor.execute(
"""UPDATE ratings
SET rating = %s,
rdate = CURRENT_TIMESTAMP
WHERE oauth_ID = %s AND
movie_ID = %s
""",
(rating, user_id, movie_id),
)
sql = """ UPDATE ratings
SET rating = {},
rdate = CURRENT_TIMESTAMP
WHERE oauth_ID = '{}' AND
movie_ID = '{}'
"""
cursor.execute(sql.format(rating, uID, movie_ID))
else:
cursor.execute(
"INSERT INTO ratings (movie_ID, oauth_ID, rating) VALUES (%s, %s, %s);",
(movie_id, user_id, rating),
f"INSERT INTO ratings (movie_ID, oauth_ID, rating) VALUES ('{movie_ID}','{uID}',{rating});"
)
DB.commit()
conn.commit()
cursor.close()
return jsonify({"status": "success"}), HTTP_OK
def try_connect(config: ConfigParser) -> psycopg2.extensions.connection | None:
"""Return a connection, or None if the database is not accepting them yet."""
try:
return psycopg2.connect(
host=config["postgres"]["host"],
database=config["postgres"]["database"],
user=config["postgres"]["user"],
password=config["postgres"]["password"],
port=int(config["postgres"]["port"]),
)
except psycopg2.OperationalError:
return None
def connect_with_retry(config: ConfigParser) -> psycopg2.extensions.connection:
"""Block until Postgres accepts a connection, then return it."""
connection = try_connect(config)
while connection is None:
logger.info("Trying to connect with database")
time.sleep(DB_RETRY_SECONDS)
connection = try_connect(config)
return connection
def main() -> None:
"""Connect, load the film table, and serve until stopped."""
config = ConfigParser()
config.read("init_scripts/constants.ini")
DB.conn = connect_with_retry(config)
MOVIES.frame = pd.read_csv(config["movie"]["csv_path"])
cache.init_app(app)
try:
# docker-compose sets ERSMS_HOST; see backend/app.py for why.
app.run(
host=os.environ.get("ERSMS_HOST", "127.0.0.1"),
port=8090,
debug=os.environ.get("FLASK_DEBUG") == "1",
)
finally:
DB.conn.close()
return jsonify({"status": "success"}), 200
if __name__ == "__main__":
logging.basicConfig(format="%(message)s", level=logging.INFO)
main()
config = ConfigParser()
config.read("init_scripts/constants.ini")
while True:
try:
conn = psycopg2.connect(
host=config["postgres"]["host"],
database=config["postgres"]["database"],
user=config["postgres"]["user"],
password=config["postgres"]["password"],
port=int(config["postgres"]["port"]),
)
except Exception:
print("Trying to connect with database")
continue
else:
break
movie_list = pandas.read_csv(config["movie"]["csv_path"])
cache.init_app(app)
app.run(host="localhost", port=8090, debug=True)
conn.close()

View File

@ -3,8 +3,6 @@ version: '3.8'
services:
app:
build: ./connector
environment:
ERSMS_HOST: 0.0.0.0
ports:
- "5000:8090" # Adjust if your app uses a different port
depends_on:
@ -64,8 +62,6 @@ services:
movie_rec:
container_name: movie_rec
build: ./movie_recommendations
environment:
ERSMS_HOST: 0.0.0.0
ports:
- "8081:8081"
depends_on:
@ -75,8 +71,6 @@ services:
analitics:
container_name: analytics
build: ./analytics
environment:
ERSMS_HOST: 0.0.0.0
ports:
- "8082:8082"
depends_on:
@ -86,8 +80,6 @@ services:
firebase:
container_name: firebase
build: .
environment:
ERSMS_HOST: 0.0.0.0
ports:
- "8084:8084"
depends_on:

View File

@ -1,22 +1,7 @@
#!/usr/bin/env python3
"""Content-based film recommendations from the TMDB 5000 dataset.
Each film is reduced to a "soup" of its keywords, top three cast members,
director and genres; the recommender then scores films by the cosine
similarity of those soups.
"""
from __future__ import annotations
import hashlib
import json
import logging
import os
import time
from ast import literal_eval
from configparser import ConfigParser
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, cast
import numpy as np
import pandas as pd
@ -26,73 +11,55 @@ from flask_caching import Cache
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.metrics.pairwise import cosine_similarity
if TYPE_CHECKING:
from flask.typing import ResponseReturnValue
logger = logging.getLogger(__name__)
# Only the top few cast members say anything useful about a film.
MAX_CAST_MEMBERS = 3
# How many similar films one input film contributes to the pool.
RECOMMENDATION_POOL = 100
# The database container may still be starting when this one is ready.
DB_RETRY_SECONDS = 1
app = Flask(__name__)
cache = Cache(config={"CACHE_TYPE": "SimpleCache"})
db_connector = None
conn = None
def get_director(crew: list[dict[str, Any]]) -> str | float:
"""Return the director's name, or NaN when the crew list has no director."""
for member in crew:
if member["job"] == "Director":
return cast("str", member["name"])
def get_director(x):
for i in x:
if i["job"] == "Director":
return i["name"]
return np.nan
def get_list(values: object) -> list[str]:
"""Return at most the first three names from a TMDB list column."""
if isinstance(values, list):
names = [item["name"] for item in values]
if len(names) > MAX_CAST_MEMBERS:
names = names[:MAX_CAST_MEMBERS]
def get_list(x):
if isinstance(x, list):
names = [i["name"] for i in x]
if len(names) > 3:
names = names[:3]
return names
return []
def clean_data(value: object) -> list[str] | str:
"""Lowercase and de-space a name so "Tom Hanks" cannot match "Tom Hardy"."""
if isinstance(value, list):
return [str.lower(item.replace(" ", "")) for item in value]
if isinstance(value, str):
return str.lower(value.replace(" ", ""))
def clean_data(x):
if isinstance(x, list):
return [str.lower(i.replace(" ", "")) for i in x]
if isinstance(x, str):
return str.lower(x.replace(" ", ""))
return ""
def create_soup(row: pd.Series) -> str:
"""Join one film's keywords, cast, director and genres into one string."""
return cast(
"str",
" ".join(row["keywords"])
def create_soup(x):
return (
" ".join(x["keywords"])
+ " "
+ " ".join(row["cast"])
+ " ".join(x["cast"])
+ " "
+ row["director"]
+ x["director"]
+ " "
+ " ".join(row["genres"]),
+ " ".join(x["genres"])
)
class MovieRecommender:
"""Holds the film table and the film-by-film cosine similarity matrix."""
def __init__(self) -> None:
"""Start empty; `fit` fills both."""
self.df: pd.DataFrame | None = None
self.cosine_sim: np.ndarray | None = None
def fit(self, credits_file: str, movies_file: str) -> None:
"""Fittuje AI do przekazanych danych.
def __init__(self):
self.df = None
self.cosine_sim = None
def fit(self, credits_file, movies_file):
"""Fittuje AI do przekazanych danych
:param credits_file: csv z creditsami
:param movies_file: csv z filmami
:return: Nic.
@ -126,124 +93,84 @@ class MovieRecommender:
self.df = df2.reset_index()
def _get_recommendations_one_input(
self, movie_id: int
) -> tuple[np.ndarray, np.ndarray]:
"""Tworzy rekomendacje, bazując na jednym filmie.
def _get_recommendations_one_input(self, movie_id):
"""Tworzy rekomendacje, bazując na jednym filmie
:param movie_id: id filmu, dla którego ma zrobić rekomendację
:return: Para (movie_ids, similarity_scores), obie jako np.array.
:return: Zwraca listę [movie_ids, similarity_scores] gdzie oba argumenty są np.array.
"""
if self.df is None or self.cosine_sim is None:
msg = "call fit() before asking for recommendations"
raise RuntimeError(msg)
indices = pd.Series(self.df.index, index=self.df["id"]).drop_duplicates()
idx = indices[movie_id]
sim_scores = sorted(
enumerate(self.cosine_sim[idx]), key=lambda pair: pair[1], reverse=True
)
sim_scores = sim_scores[1 : RECOMMENDATION_POOL + 1]
movie_indices = [pair[0] for pair in sim_scores]
scores = np.array([pair[1] for pair in sim_scores])
return (self.df["id"].iloc[movie_indices].to_numpy(), scores)
sim_scores = list(enumerate(self.cosine_sim[idx]))
sim_scores = sorted(sim_scores, key=lambda x: x[1], reverse=True)
sim_scores = sim_scores[1:101]
movie_indices = [i[0] for i in sim_scores]
sim_scores = np.array([t[1] for t in sim_scores])
return [self.df["id"].iloc[movie_indices].values, sim_scores]
def get_recommendations(self, movie_ids: list[int]) -> dict[int, float]:
"""Tworzy listę rekomendacji bazującą na id podanych filmów.
:param movie_ids: id filmów, na podstawie których wybiera rekomendacje
:return: Dict {movie_id: similarity_score}.
def get_recommendations(self, movie_ids: list) -> {}:
"""Tworzy listę rekomendacji bazującą na id podanych filmów
:param movie_ids: id filmów, na podstawie których ma wybrać rekomendowane filmy
:return: Zwraca dicta {movie_id: similarity_scores}.
"""
recommended_movies: dict[int, float] = {}
recommended_movies = {}
for movie_id in movie_ids:
recommended_ids, sim_scores = self._get_recommendations_one_input(movie_id)
for recommended_id, sim_score in zip(
recommended_ids, sim_scores, strict=True
):
for recommended_id, sim_score in zip(recommended_ids, sim_scores):
if recommended_id in movie_ids:
continue
share = float(round(sim_score / len(movie_ids), 4))
key = int(recommended_id)
recommended_movies[key] = recommended_movies.get(key, 0.0) + share
if recommended_movies.get(int(recommended_id)) is None:
recommended_movies[int(recommended_id)] = float(
round((sim_score / len(movie_ids)), 4)
)
else:
recommended_movies[int(recommended_id)] += float(
round((sim_score / len(movie_ids)), 4)
)
return recommended_movies
@dataclass
class Database:
"""The Postgres connection, opened once at start-up."""
conn: psycopg2.extensions.connection | None = None
app = Flask(__name__)
cache = Cache(config={"CACHE_TYPE": "SimpleCache"})
DB = Database()
recommender = MovieRecommender()
recommender.fit("datasets/tmdb_5000_credits.csv", "datasets/tmdb_5000_movies.csv")
def make_cache_key() -> str:
"""Key the cache on the sorted request body, so order does not matter."""
def make_cache_key():
data = request.get_json()
if isinstance(data, list):
data = sorted(data)
# Not a security hash: this only has to be short and stable.
return hashlib.md5(
json.dumps(data).encode("utf-8"), usedforsecurity=False
).hexdigest()
key = hashlib.md5(json.dumps(data).encode("utf-8")).hexdigest()
return key
@app.route("/api/v3/AI_recommendations", methods=["POST"])
@cache.cached(timeout=300, key_prefix=make_cache_key)
def ai_recommendations() -> ResponseReturnValue:
"""Return {movie_id: score} for the film ids posted in the body."""
def AI_recommendations():
ids = request.get_json()
return jsonify(recommender.get_recommendations(ids))
def try_connect(config: ConfigParser) -> psycopg2.extensions.connection | None:
"""Return a connection, or None if the database is not accepting them yet."""
try:
return psycopg2.connect(
host=config["postgres"]["host"],
database=config["postgres"]["database"],
user=config["postgres"]["user"],
password=config["postgres"]["password"],
port=int(config["postgres"]["port"]),
)
except psycopg2.OperationalError:
return None
def connect_with_retry(config: ConfigParser) -> psycopg2.extensions.connection:
"""Block until Postgres accepts a connection, then return it."""
connection = try_connect(config)
while connection is None:
logger.info("Trying to connect with database")
time.sleep(DB_RETRY_SECONDS)
connection = try_connect(config)
return connection
def main() -> None:
"""Fit the recommender, connect to the database, and serve until stopped."""
recommender.fit("datasets/tmdb_5000_credits.csv", "datasets/tmdb_5000_movies.csv")
config = ConfigParser()
config.read("init_scripts/constants.ini")
DB.conn = connect_with_retry(config)
cache.init_app(app)
try:
# docker-compose sets ERSMS_HOST; see backend/app.py for why.
app.run(
host=os.environ.get("ERSMS_HOST", "127.0.0.1"),
port=8081,
debug=os.environ.get("FLASK_DEBUG") == "1",
)
finally:
DB.conn.close()
recommendations = recommender.get_recommendations(ids)
return jsonify(recommendations)
if __name__ == "__main__":
logging.basicConfig(format="%(message)s", level=logging.INFO)
main()
config = ConfigParser()
config.read("init_scripts/constants.ini")
while True:
try:
conn = psycopg2.connect(
host=config["postgres"]["host"],
database=config["postgres"]["database"],
user=config["postgres"]["user"],
password=config["postgres"]["password"],
port=int(config["postgres"]["port"]),
)
except Exception:
print("Trying to connect with database")
continue
else:
break
cache.init_app(app)
app.run(host="localhost", port=8081, debug=True)
conn.close()

View File

@ -13,8 +13,6 @@
"metadata": {},
"outputs": [],
"source": [
"import sys\n",
"\n",
"import pandas as pd"
]
},
@ -98,9 +96,7 @@
}
],
"source": [
"sys.stdout.write(\n",
" f\"{df_dofinansowanie['Program operacyjny'].drop_duplicates().to_numpy()}\\n\"\n",
")"
"print(df_dofinansowanie[\"Program operacyjny\"].drop_duplicates().values)"
]
},
{
@ -110,8 +106,7 @@
"outputs": [],
"source": [
"# Wybór programu operacyjnego...\n",
"# Filtering to a single operational programme happens downstream, in\n",
"# pbad.ipynb and main.ipynb; this notebook builds the full table.\n"
"# df_dofinansowanie = df_dofinansowanie.loc[df_dofinansowanie['Program operacyjny'] == 'Program Operacyjny Infrastruktura i ?rodowisko 2014-2020'].reset_index(drop=True)\n"
]
},
{
@ -135,12 +130,8 @@
" \"Dofinansowanie UE (PLN)\": \"Suma\",\n",
" }\n",
")\n",
"# A full TERYT gmina code is seven digits; anything shorter is a county\n",
"# or voivodeship row that does not belong in this table.\n",
"TERYT_GMINA_DIGITS = 7\n",
"\n",
"df_dofinansowanie_agg = df_dofinansowanie_agg.loc[\n",
" df_dofinansowanie_agg[\"Kod\"].str.len() == TERYT_GMINA_DIGITS\n",
" df_dofinansowanie_agg[\"Kod\"].str.len() == 7\n",
"].reset_index(drop=True)"
]
},
@ -181,10 +172,7 @@
"df_wyna = df_wyna.rename(\n",
" columns={\n",
" \"ogółem\": \"Wynagrodzenie_ogolem\",\n",
" (\n",
" \"przeciętne miesięczne wynagrodzenia brutto w relacji do średniej krajowej \"\n",
" \"(Polska=100)\"\n",
" ): \"Wynagrodzenie_w_relacji_do_sredniej\",\n",
" \"przeciętne miesięczne wynagrodzenia brutto w relacji do średniej krajowej (Polska=100)\": \"Wynagrodzenie_w_relacji_do_sredniej\",\n",
" }\n",
")"
]
@ -508,26 +496,13 @@
"df_fina_1 = df_fina_1.rename(\n",
" columns={\n",
" \"dochody podatkowe - podatek leśny\": \"Dochody_podatek_lesny\",\n",
" (\n",
" \"dochody podatkowe - podatek od czynności cywilnoprawnych\"\n",
" ): \"Dochody_podatek_PCC\",\n",
" (\n",
" \"dochody podatkowe - podatek od działalności gospodarczej osób fizycznych, \"\n",
" \"opłacany w formie karty podatkowej\"\n",
" ): \"Dochody_podatek_od_dzialalnosci_gospodarczej\",\n",
" (\n",
" \"dochody podatkowe - podatek od nieruchomości\"\n",
" ): \"Dochody_podatek_od_nieruchomosci\",\n",
" (\n",
" \"dochody podatkowe - podatek od spadków i darowizn\"\n",
" ): \"Dochody_podatek_od_spadkow\",\n",
" (\n",
" \"dochody podatkowe - podatek od środków transportowych\"\n",
" ): \"Dochody_podatek_od_srodkow_transportowych\",\n",
" \"dochody podatkowe - podatek od czynności cywilnoprawnych\": \"Dochody_podatek_PCC\",\n",
" \"dochody podatkowe - podatek od działalności gospodarczej osób fizycznych, opłacany w formie karty podatkowej\": \"Dochody_podatek_od_dzialalnosci_gospodarczej\",\n",
" \"dochody podatkowe - podatek od nieruchomości\": \"Dochody_podatek_od_nieruchomosci\",\n",
" \"dochody podatkowe - podatek od spadków i darowizn\": \"Dochody_podatek_od_spadkow\",\n",
" \"dochody podatkowe - podatek od środków transportowych\": \"Dochody_podatek_od_srodkow_transportowych\",\n",
" \"dochody podatkowe - podatek rolny\": \"Dochody_podatek_rolny\",\n",
" (\n",
" \"dochody podatkowe - ustalone i pobierane na podstawie odrębnych ustaw\"\n",
" ): \"Dochody_podatek_odrebne_ustawy\",\n",
" \"dochody podatkowe - ustalone i pobierane na podstawie odrębnych ustaw\": \"Dochody_podatek_odrebne_ustawy\",\n",
" \"razem\": \"Dochody_razem\",\n",
" }\n",
")\n",
@ -929,34 +904,14 @@
"df_fina_2 = df_fina_2.rename(\n",
" columns={\n",
" \"dochody z majątku\": \"Dochody_z_majatku\",\n",
" (\n",
" \"dochody z majątku - dochody z najmu i dzierżawy składników majątkowych \"\n",
" \"JST oraz innych umów o podobnym charakterze\"\n",
" ): \"Dochody_z_najmu_i_dzierzawy\",\n",
" \"dochody z majątku - dochody z najmu i dzierżawy składników majątkowych JST oraz innych umów o podobnym charakterze\": \"Dochody_z_najmu_i_dzierzawy\",\n",
" \"pozostałe dochody - wpływy z usług\": \"Dochody_z_uslug\",\n",
" (\n",
" \"pozostałe dochody - środki na dofinansowanie własnych zadań pozyskane z \"\n",
" \"innych źródeł - inwestycyjne\"\n",
" ): \"Dochody_dofinansowanie_inwestycyjne\",\n",
" (\n",
" \"pozostałe dochody - środki na dofinansowanie własnych zadań pozyskane z \"\n",
" \"innych źródeł - razem\"\n",
" ): \"Dochody_dofinansowanie_razem\",\n",
" (\n",
" \"udziały w podatkach stanowiących dochody budżetu państwa podatek \"\n",
" \"dochodowy od osób fizycznych\"\n",
" ): \"Udzialy_w_podatkach_dochodowych_od_osob_fizycznych\",\n",
" (\n",
" \"udziały w podatkach stanowiących dochody budżetu państwa podatek \"\n",
" \"dochodowy od osób prawnych\"\n",
" ): \"Udzialy_w_podatkach_dochodowych_od_osob_prywatnych\",\n",
" (\n",
" \"udziały w podatkach stanowiących dochody budżetu państwa razem\"\n",
" ): \"Udzialy_w_podatkach_dochodowych_razem\",\n",
" (\n",
" \"wpływy z innych lokalnych opłat pobieranych przez jednostki samorządu \"\n",
" \"terytorialnego na podstawie odrębnych ustaw\"\n",
" ): \"Wplywy_z_innych_lokalnych_oplat\",\n",
" \"pozostałe dochody - środki na dofinansowanie własnych zadań pozyskane z innych źródeł - inwestycyjne\": \"Dochody_dofinansowanie_inwestycyjne\",\n",
" \"pozostałe dochody - środki na dofinansowanie własnych zadań pozyskane z innych źródeł - razem\": \"Dochody_dofinansowanie_razem\",\n",
" \"udziały w podatkach stanowiących dochody budżetu państwa podatek dochodowy od osób fizycznych\": \"Udzialy_w_podatkach_dochodowych_od_osob_fizycznych\",\n",
" \"udziały w podatkach stanowiących dochody budżetu państwa podatek dochodowy od osób prawnych\": \"Udzialy_w_podatkach_dochodowych_od_osob_prywatnych\",\n",
" \"udziały w podatkach stanowiących dochody budżetu państwa razem\": \"Udzialy_w_podatkach_dochodowych_razem\",\n",
" \"wpływy z innych lokalnych opłat pobieranych przez jednostki samorządu terytorialnego na podstawie odrębnych ustaw\": \"Wplywy_z_innych_lokalnych_oplat\",\n",
" \"wpływy z opłaty eksploatacyjnej\": \"Wplywy_z_oplaty_eksploatacyjnej\",\n",
" \"wpływy z opłaty skarbowej\": \"Wplywy_z_oplaty_skarbowej\",\n",
" \"wpływy z opłaty targowej\": \"Wplywy_z_oplaty_targowej\",\n",
@ -1479,12 +1434,8 @@
" \"ogółem\": \"Ludnosc_mezczyzni\",\n",
" \"w wieku poprodukcyjnym\": \"Ludnosc_mezczyzni_w_wieku_poprodukcyjnym\",\n",
" \"w wieku produkcyjnym\": \"Ludnosc_mezczyzni_w_wieku_produkcyjnym\",\n",
" (\n",
" \"w wieku produkcyjnym mobilnym\"\n",
" ): \"Ludnosc_mezczyzni_w_wieku_produkcyjnym_mobilnym\",\n",
" (\n",
" \"w wieku produkcyjnym niemobilnym\"\n",
" ): \"Ludnosc_mezczyzni_w_wieku_produkcyjnym_niemobilnym\",\n",
" \"w wieku produkcyjnym mobilnym\": \"Ludnosc_mezczyzni_w_wieku_produkcyjnym_mobilnym\",\n",
" \"w wieku produkcyjnym niemobilnym\": \"Ludnosc_mezczyzni_w_wieku_produkcyjnym_niemobilnym\",\n",
" \"w wieku przedprodukcyjnym\": \"Ludnosc_mezczyzni_w_wieku_przedprodukcyjnym\",\n",
" }\n",
")\n",
@ -1744,12 +1695,8 @@
" \"ogółem\": \"Ludnosc_kobiety\",\n",
" \"w wieku poprodukcyjnym\": \"Ludnosc_kobiety_w_wieku_poprodukcyjnym\",\n",
" \"w wieku produkcyjnym\": \"Ludnosc_kobiety_w_wieku_produkcyjnym\",\n",
" (\n",
" \"w wieku produkcyjnym mobilnym\"\n",
" ): \"Ludnosc_kobiety_w_wieku_produkcyjnym_mobilnym\",\n",
" (\n",
" \"w wieku produkcyjnym niemobilnym\"\n",
" ): \"Ludnosc_kobiety_w_wieku_produkcyjnym_niemobilnym\",\n",
" \"w wieku produkcyjnym mobilnym\": \"Ludnosc_kobiety_w_wieku_produkcyjnym_mobilnym\",\n",
" \"w wieku produkcyjnym niemobilnym\": \"Ludnosc_kobiety_w_wieku_produkcyjnym_niemobilnym\",\n",
" \"w wieku przedprodukcyjnym\": \"Ludnosc_kobiety_w_wieku_przedprodukcyjnym\",\n",
" }\n",
")\n",
@ -1774,9 +1721,7 @@
").reset_index()\n",
"df_ludn_4 = df_ludn_4.rename(\n",
" columns={\n",
" (\n",
" \"gęstość zaludnienia powierzchni zabudowanej i zurbanizowanej (osoby/km2)\"\n",
" ): \"Gestosc_zaludnienia\",\n",
" \"gęstość zaludnienia powierzchni zabudowanej i zurbanizowanej (osoby/km2)\": \"Gestosc_zaludnienia\",\n",
" \"ludność na 1 km2\": \"Ludnosc_na_1_km2\",\n",
" \"ludność w tysiącach\": \"Ludnosc\",\n",
" \"ludność w tysiącach kobiety\": \"Ludnosc_kobiety\",\n",
@ -2567,9 +2512,7 @@
" \"obiekty całoroczne lipiec\": \"Obiekty_caloroczne\",\n",
" \"obiekty ogółem lipiec\": \"Obiekty_ogolem\",\n",
" \"turyści (korzystający) ogółem styczeń-grudzień\": \"Turysci_ogolem\",\n",
" (\n",
" \"turyści zagraniczni (korzystający) - nierezydenci styczeń-grudzień\"\n",
" ): \"Turysci_zagraniczni\",\n",
" \"turyści zagraniczni (korzystający) - nierezydenci styczeń-grudzień\": \"Turysci_zagraniczni\",\n",
" }\n",
")\n",
"\n",
@ -2858,7 +2801,7 @@
],
"source": [
"df_data = df_dofinansowanie_agg.copy()\n",
"sys.stdout.write(f\"{len(df_data)}\\n\")"
"print(len(df_data))"
]
},
{
@ -2943,7 +2886,7 @@
" suffixes=(None, \"_podz\"),\n",
")\n",
"df_data = df_data.drop([\"key_0\", \"Kod_podz\"], axis=1)\n",
"sys.stdout.write(f\"{len(df_data)}\\n\")"
"print(len(df_data))"
]
},
{
@ -2968,7 +2911,7 @@
" suffixes=(None, \"_wyna\"),\n",
")\n",
"df_data = df_data.drop([\"key_0\", \"Kod_wyna\"], axis=1)\n",
"sys.stdout.write(f\"{len(df_data)}\\n\")"
"print(len(df_data))"
]
},
{
@ -2994,7 +2937,7 @@
" suffixes=(None, \"_fina_1\"),\n",
")\n",
"df_data = df_data.drop([\"key_0\", \"Kod_fina_1\"], axis=1)\n",
"sys.stdout.write(f\"{len(df_data)}\\n\")\n",
"print(len(df_data))\n",
"\n",
"df_data = df_data.merge(\n",
" df_fina_2,\n",
@ -3004,7 +2947,7 @@
" suffixes=(None, \"_fina_2\"),\n",
")\n",
"df_data = df_data.drop([\"key_0\", \"Kod_fina_2\"], axis=1)\n",
"sys.stdout.write(f\"{len(df_data)}\\n\")"
"print(len(df_data))"
]
},
{
@ -3025,9 +2968,7 @@
}
],
"source": [
"# Each of these merges was first written joining on Kod directly, next to a\n",
"# df_data['Kod'].value_counts() probe. These tables are published at coarser\n",
"# TERYT levels, so the key is a sliced code instead.\n",
"# df_data = df_data.merge(df_ludn_1, left_on=['Kod', 'Rok'], right_on=['Kod', 'Rok'], how='left', suffixes=(None, '_ludn_1'))\n",
"df_data = df_data.merge(\n",
" df_ludn_1,\n",
" left_on=[df_data[\"Kod\"].str.slice(stop=-1), \"Rok\"],\n",
@ -3036,8 +2977,9 @@
" suffixes=(None, \"_ludn_1\"),\n",
")\n",
"df_data = df_data.drop([\"key_0\", \"Kod_ludn_1\"], axis=1)\n",
"sys.stdout.write(f\"{len(df_data)}\\n\")\n",
"print(len(df_data))\n",
"\n",
"# df_data = df_data.merge(df_ludn_2, left_on=['Kod', 'Rok'], right_on=['Kod', 'Rok'], how='left', suffixes=(None, '_ludn_2'))\n",
"df_data = df_data.merge(\n",
" df_ludn_2,\n",
" left_on=[df_data[\"Kod\"].str.slice(stop=-1), \"Rok\"],\n",
@ -3046,8 +2988,9 @@
" suffixes=(None, \"_ludn_2\"),\n",
")\n",
"df_data = df_data.drop([\"key_0\", \"Kod_ludn_2\"], axis=1)\n",
"sys.stdout.write(f\"{len(df_data)}\\n\")\n",
"print(len(df_data))\n",
"\n",
"# df_data = df_data.merge(df_ludn_3, left_on=['Kod', 'Rok'], right_on=['Kod', 'Rok'], how='left', suffixes=(None, '_ludn_3'))\n",
"df_data = df_data.merge(\n",
" df_ludn_3,\n",
" left_on=[df_data[\"Kod\"].str.slice(stop=-1), \"Rok\"],\n",
@ -3056,8 +2999,9 @@
" suffixes=(None, \"_ludn_3\"),\n",
")\n",
"df_data = df_data.drop([\"key_0\", \"Kod_ludn_3\"], axis=1)\n",
"sys.stdout.write(f\"{len(df_data)}\\n\")\n",
"print(len(df_data))\n",
"\n",
"# df_data = df_data.merge(df_ludn_4, left_on=['Kod', 'Rok'], right_on=['Kod', 'Rok'], how='left', suffixes=(None, '_ludn_4'))\n",
"df_data = df_data.merge(\n",
" df_ludn_4,\n",
" left_on=[df_data[\"Kod\"].str.slice(stop=-1), \"Rok\"],\n",
@ -3066,8 +3010,9 @@
" suffixes=(None, \"_ludn_4\"),\n",
")\n",
"df_data = df_data.drop([\"key_0\", \"Kod_ludn_4\"], axis=1)\n",
"sys.stdout.write(f\"{len(df_data)}\\n\")\n",
"print(len(df_data))\n",
"\n",
"# df_data = df_data.merge(df_ludn_5, left_on=['Kod', 'Rok'], right_on=['Kod', 'Rok'], how='left', suffixes=(None, '_ludn_5'))\n",
"df_data = df_data.merge(\n",
" df_ludn_5,\n",
" left_on=[df_data[\"Kod\"].str.slice(stop=-1), \"Rok\"],\n",
@ -3076,7 +3021,9 @@
" suffixes=(None, \"_ludn_5\"),\n",
")\n",
"df_data = df_data.drop([\"key_0\", \"Kod_ludn_5\"], axis=1)\n",
"sys.stdout.write(f\"{len(df_data)}\\n\")"
"print(len(df_data))\n",
"\n",
"# df_data['Kod'].value_counts()"
]
},
{
@ -3093,9 +3040,6 @@
}
],
"source": [
"# This table is published at gmina level, so the merge joins on Kod\n",
"# directly. pandas therefore creates no key_0 column and there is nothing\n",
"# to drop afterwards.\n",
"df_data = df_data.merge(\n",
" df_tury,\n",
" left_on=[\"Kod\", \"Rok\"],\n",
@ -3103,7 +3047,8 @@
" how=\"left\",\n",
" suffixes=(None, \"_tury\"),\n",
")\n",
"sys.stdout.write(f\"{len(df_data)}\\n\")"
"# df_data = df_data.drop(['key_0', 'Kod_tury'], axis=1)\n",
"print(len(df_data))"
]
},
{
@ -3120,9 +3065,6 @@
}
],
"source": [
"# This table is published at gmina level, so the merge joins on Kod\n",
"# directly. pandas therefore creates no key_0 column and there is nothing\n",
"# to drop afterwards.\n",
"df_data = df_data.merge(\n",
" df_ryne,\n",
" left_on=[\"Kod\", \"Rok\"],\n",
@ -3130,7 +3072,8 @@
" how=\"left\",\n",
" suffixes=(None, \"_ryne\"),\n",
")\n",
"sys.stdout.write(f\"{len(df_data)}\\n\")"
"# df_data = df_data.drop(['key_0', 'Kod_ryne'], axis=1)\n",
"print(len(df_data))"
]
},
{
@ -3192,9 +3135,57 @@
"metadata": {},
"outputs": [],
"source": [
"# An earlier pass filled the tourism columns and dropped a long explicit\n",
"# column list here. Both are done above now, against df_data's real\n",
"# columns rather than a hand-maintained list."
"# # df_data[[\n",
"# # 'Miejsca_noclegowe_caloroczne',\n",
"# # 'Miejsca_noclegowe_ogolem',\n",
"# # 'Obiekty_caloroczne',\n",
"# # 'Obiekty_ogolem',\n",
"# # 'Turysci_ogolem',\n",
"# # 'Turysci_zagraniczni']] = df_data[[\n",
"# # 'Miejsca_noclegowe_caloroczne',\n",
"# # 'Miejsca_noclegowe_ogolem',\n",
"# # 'Obiekty_caloroczne',\n",
"# # 'Obiekty_ogolem',\n",
"# # 'Turysci_ogolem',\n",
"# # 'Turysci_zagraniczni']].fillna(0)\n",
"# df_data.drop(columns=[\n",
"# 'Program_operacyjny',\n",
"# 'Wymeldowania_za_granice_kobiety',\n",
"# 'Wymeldowania_za_granice_mezczyzni',\n",
"# 'Wymeldowania_za_granice_ogolem',\n",
"# 'Bezrobotni_do_30_roku_zycia',\n",
"\n",
"# 'Wojewodztwo_Dolnoslaskie', # 43\n",
"# 'Wojewodztwo_Kujawsko_Pomorskie', # 44\n",
"# 'Wojewodztwo_Lubelskie', # 45\n",
"# 'Wojewodztwo_Lubuskie', # 46\n",
"# 'Wojewodztwo_Lodzkie', # 47\n",
"# 'Wojewodztwo_Malopolskie', # 48\n",
"# 'Wojewodztwo_Mazowieckie', # 49\n",
"# 'Wojewodztwo_Opolskie', # 50\n",
"# 'Wojewodztwo_Podkarpackie', # 51\n",
"# 'Wojewodztwo_Podlaskie', # 52\n",
"# 'Wojewodztwo_Pomorskie', # 53\n",
"# 'Wojewodztwo_Slaskie', # 54\n",
"# 'Wojewodztwo_Swietokrzyskie', # 55\n",
"# 'Wojewodztwo_Warminsko_Mazurskie', # 56\n",
"# 'Wojewodztwo_Wielkopolskie', # 57\n",
"# 'Wojewodztwo_Zachodniopomorskie', # 58\n",
"# 'Gmina_miejska', # 98\n",
"# 'Gmina_miejsko_wiejska', # 99\n",
"# 'Gmina_wiejska',\n",
"# 'Wynagrodzenie_ogolem','Wynagrodzenie_w_relacji_do_sredniej','Dochody_podatek_lesny','Dochody_podatek_PCC','Dochody_podatek_od_dzialalnosci_gospodarczej','Dochody_podatek_od_nieruchomosci',\n",
"# 'Dochody_podatek_od_spadkow','Dochody_podatek_od_srodkow_transportowych','Dochody_podatek_rolny','Dochody_podatek_odrebne_ustawy','Dochody_razem','Dochody_z_majatku',\n",
"# 'Dochody_z_najmu_i_dzierzawy','Dochody_z_uslug','Dochody_dofinansowanie_inwestycyjne','Dochody_dofinansowanie_razem','Udzialy_w_podatkach_dochodowych_od_osob_fizycznych','Udzialy_w_podatkach_dochodowych_od_osob_prywatnych',\n",
"# 'Miejsca_noclegowe_caloroczne',\n",
"# 'Miejsca_noclegowe_ogolem',\n",
"# 'Obiekty_caloroczne',\n",
"# 'Obiekty_ogolem',\n",
"# 'Turysci_ogolem',\n",
"# 'Turysci_zagraniczni',\n",
"# 'Udzialy_w_podatkach_dochodowych_razem','Wplywy_z_innych_lokalnych_oplat','Wplywy_z_oplaty_eksploatacyjnej','Wplywy_z_oplaty_skarbowej','Wplywy_z_oplaty_targowej'], inplace=True, errors='ignore')\n",
"\n",
"# df_data[(df_data.isna().any(axis=1)) & (df_data['Rok'] != 2023)].columns # ['Rok'].drop_duplicates().reset_index(drop=True)"
]
},
{
@ -3203,9 +3194,7 @@
"metadata": {},
"outputs": [],
"source": [
"# pbad.ipynb divides Suma by Ludnosc to get a per-head figure. This\n",
"# notebook writes the raw total to dane1.csv and leaves that choice to\n",
"# whoever reads it."
"# df_data['Suma'] = df_data['Suma'] / df_data['Ludnosc']"
]
},
{
@ -3333,22 +3322,22 @@
],
"source": [
"# Usunięcie niepotrzebnych kolumn...\n",
"# Program_operacyjny is kept here and dropped later, once the per-programme\n",
"# split has been made.\n",
"df_data = df_data.drop(\n",
"df_data.drop(\n",
" columns=[\n",
" # 'Program_operacyjny',\n",
" \"Wymeldowania_za_granice_kobiety\",\n",
" \"Wymeldowania_za_granice_mezczyzni\",\n",
" \"Wymeldowania_za_granice_ogolem\",\n",
" \"Bezrobotni_do_30_roku_zycia\",\n",
" ],\n",
" inplace=True,\n",
" errors=\"ignore\",\n",
")\n",
"\n",
"df_data.to_csv(\"dane1.csv\", index=False)\n",
"\n",
"for c in df_data.columns:\n",
" sys.stdout.write(f\"{c}\\n\")"
" print(c)"
]
},
{
@ -3542,7 +3531,7 @@
" \"Gmina_wiejska\",\n",
"] # 100\n",
"\n",
"df_data = df_data.drop(\n",
"df_data.drop(\n",
" columns=[\n",
" \"Program_operacyjny\",\n",
" \"Wymeldowania_za_granice_kobiety\",\n",
@ -3550,22 +3539,20 @@
" \"Wymeldowania_za_granice_ogolem\",\n",
" \"Bezrobotni_do_30_roku_zycia\",\n",
" ],\n",
" inplace=True,\n",
" errors=\"ignore\",\n",
")\n",
"\n",
"sys.stdout.write(f\"{len(df_data)}\\n\")\n",
"df_data = df_data.dropna()\n",
"print(len(df_data))\n",
"df_data.dropna(inplace=True)\n",
"df_data = df_data[df_data[\"Suma\"] > 0]\n",
"sys.stdout.write(f\"{len(df_data)}\\n\")\n",
"print(len(df_data))\n",
"\n",
"X = df_data[feature_names]\n",
"y = df_data[\"Suma\"]\n",
"\n",
"# Above this population density a gmina is coloured as the dense group\n",
"# in the scatter below.\n",
"DENSE_GMINA_THRESHOLD = 1.5\n",
"\n",
"color_column = (df_data[\"Gestosc_zaludnienia\"] > DENSE_GMINA_THRESHOLD).astype(int)\n",
"color_column = df_data[\"Gestosc_zaludnienia\"]\n",
"color_column = (df_data[\"Gestosc_zaludnienia\"] > 1.5).astype(int)\n",
"\n",
"X_train, X_test, y_train, y_test, color_column_train, color_column_test = (\n",
" train_test_split(X, y, color_column, test_size=0.2, random_state=1)\n",
@ -3576,7 +3563,7 @@
"\n",
"y_pred = model.predict(X_test)\n",
"mse = mean_squared_error(y_test, y_pred)\n",
"sys.stdout.write(f\"Mean Squared Error: {mse}\\n\")"
"print(\"Mean Squared Error:\", mse)"
]
},
{
@ -3622,7 +3609,7 @@
],
"source": [
"correlation_matrix = df_data.corr()\n",
"sys.stdout.write(f\"{correlation_matrix['Suma'].sort_values(ascending=False)[1:29]}\\n\")"
"print(correlation_matrix[\"Suma\"].sort_values(ascending=False)[1:29])"
]
},
{
@ -3647,9 +3634,8 @@
"plt.ylabel(\"Predicted\")\n",
"plt.title(\"Actual vs Predicted\")\n",
"\n",
"axis_max = max(*y_test, *y_pred)\n",
"plt.xlim(0, axis_max)\n",
"plt.ylim(0, axis_max)\n",
"plt.xlim(0, max(max(y_test), max(y_pred)))\n",
"plt.ylim(0, max(max(y_test), max(y_pred)))\n",
"\n",
"plt.show()"
]
@ -4019,7 +4005,7 @@
}
],
"source": [
"sys.stdout.write(f\"{export_text(model, feature_names=feature_names)}\\n\")"
"print(export_text(model, feature_names=feature_names))"
]
},
{
@ -4133,11 +4119,11 @@
}
],
"source": [
"feature_importance = dict(zip(feature_names, model.feature_importances_, strict=True))\n",
"feature_importance = dict(zip(feature_names, model.feature_importances_))\n",
"for feature, importance in sorted(\n",
" feature_importance.items(), key=lambda x: x[1], reverse=True\n",
"):\n",
" sys.stdout.write(f\"{importance:.5f} \\u2014 {feature}\\n\")"
" print(f\"{importance:.5f} \\u2014 {feature}\")"
]
},
{

View File

@ -18,7 +18,6 @@
}
],
"source": [
"import sys\n",
"from statistics import median\n",
"\n",
"import matplotlib.pyplot as plt\n",
@ -133,7 +132,7 @@
" \"Odleglosc_od_centrum_decyzyjnego\",\n",
"] # 100\n",
"\n",
"all_columns = [\"Kod\", \"Rok\", *feature_names]\n",
"all_columns = [\"Kod\", \"Rok\"] + feature_names\n",
"\n",
"df_data = pd.read_csv(\"dane1.csv\", encoding=\"ISO-8859-2\", converters={\"Kod\": str})\n",
"\n",
@ -152,7 +151,7 @@
"\n",
"df_data = df_data.merge(df_odl, on=[\"Kod\"], how=\"left\")\n",
"\n",
"sys.stdout.write(f\"{df_data['Program_operacyjny'].drop_duplicates().to_numpy()}\\n\")"
"print(df_data[\"Program_operacyjny\"].drop_duplicates().values)"
]
},
{
@ -209,16 +208,16 @@
"].fillna(0)\n",
"\n",
"# Usunięcie niepotrzebnych rzędów...\n",
"df_data = df_data.dropna()\n",
"df_data.dropna(inplace=True)\n",
"df_data = df_data[df_data[\"Suma\"] > 0]\n",
"\n",
"df_data = df_data.groupby(all_columns)[\"Suma\"].sum().reset_index()\n",
"\n",
"# pbad.ipynb divides Suma by Ludnosc at this point to get a per-head\n",
"# figure. This notebook deliberately keeps the raw total.\n",
"# ...\n",
"# df_data['Suma'] = df_data['Suma'] / df_data['Ludnosc']\n",
"\n",
"sys.stdout.write(f\"Median {median(df_data['Suma'])}\\n\")\n",
"sys.stdout.write(f\"Mean {sum(df_data['Suma']) / len(df_data['Suma'])}\\n\")\n",
"print(\"Median\", median(df_data[\"Suma\"]))\n",
"print(\"Mean\", sum(df_data[\"Suma\"]) / len(df_data[\"Suma\"]))\n",
"\n",
"X = df_data[feature_names]\n",
"y = df_data[\"Suma\"]\n",
@ -824,18 +823,18 @@
" best_model = (model, selector)\n",
" best_params = (params[\"max_depth\"], params[\"n_features_to_select\"])\n",
"\n",
" sys.stdout.write(\n",
" print(\n",
" f\"max_depth: {params['max_depth']:>{2}}, \"\n",
" f\"n_features: {params['n_features_to_select']:>{2}}, \"\n",
" f\"mse_train: {mse_train:>{20}.1f}, \"\n",
" f\"mse_test: {mse_test:>{20}.1f} <-\\n\"\n",
" f\"mse_test: {mse_test:>{20}.1f} <-\"\n",
" )\n",
" else:\n",
" sys.stdout.write(\n",
" print(\n",
" f\"max_depth: {params['max_depth']:>{2}}, \"\n",
" f\"n_features: {params['n_features_to_select']:>{2}}, \"\n",
" f\"mse_train: {mse_train:>{20}.1f}, \"\n",
" f\"mse_test: {mse_test:>{20}.1f}\\n\"\n",
" f\"mse_test: {mse_test:>{20}.1f}\"\n",
" )"
]
},
@ -853,7 +852,7 @@
}
],
"source": [
"sys.stdout.write(f\"{best_params}\\n\")"
"print(best_params)"
]
},
{
@ -960,8 +959,8 @@
" color_column, test_size=0.2, random_state=0\n",
")\n",
"\n",
"min_val = min(*y_test, *y_pred_test)\n",
"max_val = max(*y_test, *y_pred_test)\n",
"min_val = min(min(y_test), min(y_pred_test))\n",
"max_val = max(max(y_test), max(y_pred_test))\n",
"plt.plot([min_val, max_val], [min_val, max_val], \"r--\")\n",
"\n",
"plt.scatter(y_test, y_pred_test, alpha=0.5, c=color_column_test, cmap=\"rainbow\")\n",
@ -996,7 +995,7 @@
" results_train, columns=[\"max_depth\", \"n_features_to_select\", \"mse_train\"]\n",
")\n",
"\n",
"heatmap_data = results_train_df.pivot_table(\n",
"heatmap_data = results_train_df.pivot(\n",
" index=\"max_depth\", columns=\"n_features_to_select\", values=\"mse_train\"\n",
")\n",
"\n",
@ -1029,7 +1028,7 @@
" results_test, columns=[\"max_depth\", \"n_features_to_select\", \"mse_test\"]\n",
")\n",
"\n",
"heatmap_data = results_test_df.pivot_table(\n",
"heatmap_data = results_test_df.pivot(\n",
" index=\"max_depth\", columns=\"n_features_to_select\", values=\"mse_test\"\n",
")\n",
"\n",
@ -1067,13 +1066,11 @@
}
],
"source": [
"feature_importance = dict(\n",
" zip(feature_names, best_model[0].feature_importances_, strict=True)\n",
")\n",
"feature_importance = dict(zip(feature_names, best_model[0].feature_importances_))\n",
"for feature, importance in sorted(\n",
" feature_importance.items(), key=lambda x: x[1], reverse=True\n",
"):\n",
" sys.stdout.write(f\"{importance:.4f} \\u2014 {feature}\\n\")"
" print(f\"{importance:.4f} \\u2014 {feature}\")"
]
},
{
@ -1609,11 +1606,11 @@
"model = DecisionTreeRegressor(random_state=0, max_depth=best_params[0])\n",
"model.fit(X_selected, y)\n",
"\n",
"feature_importance = dict(zip(feature_names, model.feature_importances_, strict=True))\n",
"feature_importance = dict(zip(feature_names, model.feature_importances_))\n",
"for feature, importance in sorted(\n",
" feature_importance.items(), key=lambda x: x[1], reverse=True\n",
"):\n",
" sys.stdout.write(f\"{importance:.4f} \\u2014 {feature}\\n\")"
" print(f\"{importance:.4f} \\u2014 {feature}\")"
]
},
{
@ -1622,9 +1619,7 @@
"metadata": {},
"outputs": [],
"source": [
"# The fitted tree was also inspected graphically here, with\n",
"# sklearn.tree.plot_tree(model, fontsize=5). At this depth the render is\n",
"# unreadable, so the report uses the feature importances above instead."
"# plot_tree(model, fontsize=5)"
]
}
],

View File

@ -6,8 +6,6 @@
"metadata": {},
"outputs": [],
"source": [
"import sys\n",
"\n",
"import matplotlib.pyplot as plt\n",
"import pandas as pd\n",
"from sklearn.metrics import mean_squared_error\n",
@ -124,7 +122,7 @@
" \"Odleglosc_od_centrum_decyzyjnego\",\n",
"] # 100\n",
"\n",
"all_columns = [\"Kod\", \"Rok\", *feature_names]"
"all_columns = [\"Kod\", \"Rok\"] + feature_names"
]
},
{
@ -183,7 +181,7 @@
}
],
"source": [
"sys.stdout.write(f\"{df_data['Program_operacyjny'].drop_duplicates().to_numpy()}\\n\")"
"print(df_data[\"Program_operacyjny\"].drop_duplicates().values)"
]
},
{
@ -210,9 +208,10 @@
" df_data[\"Program_operacyjny\"]\n",
" == \"Program Operacyjny Infrastruktura i ?rodowisko 2014-2020\"\n",
"].reset_index(drop=True)\n",
"# The other four programmes were each run the same way by swapping the\n",
"# name above: Inteligentny Rozwoj, Polska Cyfrowa, Wiedza Edukacja\n",
"# Rozwoj, and Polska Wschodnia.\n",
"# df_data = df_data.loc[df_data['Program_operacyjny'] == 'Program Operacyjny Inteligentny RozwĂłj'].reset_index(drop=True)\n",
"# df_data = df_data.loc[df_data['Program_operacyjny'] == 'Program Operacyjny Polska Cyfrowa'].reset_index(drop=True)\n",
"# df_data = df_data.loc[df_data['Program_operacyjny'] == 'Program Operacyjny Wiedza Edukacja RozwĂłj'].reset_index(drop=True)\n",
"# df_data = df_data.loc[df_data['Program_operacyjny'] == 'Program Operacyjny Polska Wschodnia'].reset_index(drop=True)\n",
"\n",
"# Uzupełnienie brakujących danych...\n",
"df_data[\n",
@ -236,7 +235,7 @@
"].fillna(0)\n",
"\n",
"# Usunięcie niepotrzebnych rzędów...\n",
"df_data = df_data.dropna()\n",
"df_data.dropna(inplace=True)\n",
"df_data = df_data[df_data[\"Suma\"] > 0]\n",
"\n",
"df_data = df_data.groupby(all_columns)[\"Suma\"].sum().reset_index()\n",
@ -259,18 +258,14 @@
}
],
"source": [
"# Above this population density a gmina is coloured as the dense group\n",
"# in the scatter below.\n",
"DENSE_GMINA_THRESHOLD = 1.5\n",
"\n",
"X = df_data[feature_names]\n",
"\n",
"# Scaling the features with MinMaxScaler was tried here and made no\n",
"# difference to the tree, which splits on order rather than magnitude.\n",
"# scaler = MinMaxScaler()\n",
"# X = scaler.fit_transform(X)\n",
"\n",
"y = df_data[\"Suma\"]\n",
"\n",
"color_column = (df_data[\"Gestosc_zaludnienia\"] > DENSE_GMINA_THRESHOLD).astype(int)\n",
"color_column = (df_data[\"Gestosc_zaludnienia\"] > 1.5).astype(int)\n",
"\n",
"X_train, X_test, y_train, y_test, color_column_train, color_column_test = (\n",
" train_test_split(X, y, color_column, test_size=0.2, random_state=99)\n",
@ -281,7 +276,7 @@
"\n",
"y_pred = model.predict(X_test)\n",
"mse = mean_squared_error(y_test, y_pred)\n",
"sys.stdout.write(f\"Mean Squared Error: {mse}\\n\")"
"print(\"Mean Squared Error:\", mse)"
]
},
{
@ -306,9 +301,17 @@
"plt.ylabel(\"Predicted\")\n",
"plt.title(\"Actual vs Predicted\")\n",
"\n",
"# The plot was also read zoomed in, by capping both axes at the data\n",
"# maximum and then at 3e7, 3e6 and 3e5 in turn. Full range is what the\n",
"# report uses.\n",
"# plt.xlim(0, max(max(y_test), max(y_pred)))\n",
"# plt.ylim(0, max(max(y_test), max(y_pred)))\n",
"\n",
"# plt.xlim(0, 3*10**7)\n",
"# plt.ylim(0, 3*10**7)\n",
"\n",
"# plt.xlim(0, 3*10**6)\n",
"# plt.ylim(0, 3*10**6)\n",
"\n",
"# plt.xlim(0, 3*10**5)\n",
"# plt.ylim(0, 3*10**5)\n",
"\n",
"plt.show()"
]
@ -356,7 +359,7 @@
],
"source": [
"correlation_matrix = df_data.corr()\n",
"sys.stdout.write(f\"{correlation_matrix['Suma'].sort_values(ascending=False)[1:29]}\\n\")"
"print(correlation_matrix[\"Suma\"].sort_values(ascending=False)[1:29])"
]
},
{
@ -680,7 +683,7 @@
}
],
"source": [
"sys.stdout.write(f\"{export_text(model, feature_names=feature_names)}\\n\")"
"print(export_text(model, feature_names=feature_names))"
]
},
{
@ -796,11 +799,11 @@
}
],
"source": [
"feature_importance = dict(zip(feature_names, model.feature_importances_, strict=True))\n",
"feature_importance = dict(zip(feature_names, model.feature_importances_))\n",
"for feature, importance in sorted(\n",
" feature_importance.items(), key=lambda x: x[1], reverse=True\n",
"):\n",
" sys.stdout.write(f\"{importance:.4f} \\u2014 {feature}\\n\")"
" print(f\"{importance:.4f} \\u2014 {feature}\")"
]
}
],

44
Programming/PSD/flink/anomaly_detector.py Executable file → Normal file
View File

@ -1,41 +1,23 @@
#!/usr/bin/env python3
"""Flink job skeleton: read `transactions` and print each one back out.
The detection itself was never written; the job exists to prove the Kafka
source and the pyflink environment are wired up.
"""
from __future__ import annotations
import json
from typing import Any, cast
from pyflink.common.serialization import SimpleStringSchema
from pyflink.datastream import StreamExecutionEnvironment
from pyflink.datastream.connectors.kafka import FlinkKafkaConsumer
def detect_anomalies(transaction: str) -> dict[str, Any]:
"""Parse one transaction. Anomaly detection would go here."""
return cast("dict[str, Any]", json.loads(transaction))
def detect_anomalies(transaction):
transaction_data = json.loads(transaction)
# Add anomaly detection logic here
return transaction_data
def main() -> None:
"""Wire the Kafka source to the parser and run the job."""
env = StreamExecutionEnvironment.get_execution_environment()
kafka_consumer = FlinkKafkaConsumer(
topics="transactions",
deserialization_schema=SimpleStringSchema(),
properties={
"bootstrap.servers": "localhost:9092",
"group.id": "anomaly_detection",
},
)
env = StreamExecutionEnvironment.get_execution_environment()
kafka_consumer = FlinkKafkaConsumer(
topics="transactions",
deserialization_schema=SimpleStringSchema(),
properties={"bootstrap.servers": "localhost:9092", "group.id": "anomaly_detection"},
)
data_stream = env.add_source(kafka_consumer).map(detect_anomalies)
data_stream.print()
env.execute("Anomaly Detection")
if __name__ == "__main__":
main()
data_stream = env.add_source(kafka_consumer).map(detect_anomalies)
data_stream.print()
env.execute("Anomaly Detection")

71
Programming/PSD/kafka/generate_and_send.py Executable file → Normal file
View File

@ -1,62 +1,41 @@
#!/usr/bin/env python3
"""Push made-up card transactions to the `transactions` topic once a second."""
from __future__ import annotations
import json
import logging
import random
import time
from secrets import SystemRandom
from typing import Any
from confluent_kafka import Message, Producer
from confluent_kafka import Producer
logger = logging.getLogger(__name__)
_random = SystemRandom()
# Configuration for Kafka Producer
conf = {"bootstrap.servers": "localhost:9092"}
producer = Producer(**conf)
def generate_transaction() -> dict[str, Any]:
"""Return one transaction with a random card, place and amount."""
def generate_transaction():
return {
"card_id": _random.randint(1000, 9999),
"user_id": _random.randint(100, 999),
"card_id": random.randint(1000, 9999),
"user_id": random.randint(100, 999),
"location": {
"latitude": round(_random.uniform(-90, 90), 6),
"longitude": round(_random.uniform(-180, 180), 6),
"latitude": round(random.uniform(-90, 90), 6),
"longitude": round(random.uniform(-180, 180), 6),
},
"transaction_value": round(_random.uniform(1, 1000), 2),
"spending_limit": round(_random.uniform(1000, 5000), 2),
"transaction_value": round(random.uniform(1, 1000), 2),
"spending_limit": round(random.uniform(1000, 5000), 2),
}
def delivery_report(err: object, msg: Message) -> None:
"""Log whether one message made it to the broker."""
def delivery_report(err, msg):
if err is not None:
logger.error("Message delivery failed: %s", err)
print(f"Message delivery failed: {err}")
else:
logger.info("Message delivered to %s [%s]", msg.topic(), msg.partition())
print(f"Message delivered to {msg.topic()} [{msg.partition()}]")
def main() -> None:
"""Produce transactions until interrupted."""
# Configuration for Kafka Producer
conf = {"bootstrap.servers": "localhost:9092"}
producer = Producer(**conf)
while True:
transaction = generate_transaction()
producer.produce(
"transactions",
key=str(transaction["card_id"]),
value=json.dumps(transaction),
callback=delivery_report,
)
producer.poll(1)
# Adjust the sleep time to control the frequency of transactions
time.sleep(1)
if __name__ == "__main__":
logging.basicConfig(format="%(message)s", level=logging.INFO)
main()
while True:
transaction = generate_transaction()
producer.produce(
"transactions",
key=str(transaction["card_id"]),
value=json.dumps(transaction),
callback=delivery_report,
)
producer.poll(1)
time.sleep(1) # Adjust the sleep time to control the frequency of transactions

66
Programming/PSD/kafka/kafka_consumer.py Executable file → Normal file
View File

@ -1,49 +1,23 @@
#!/usr/bin/env python3
"""Print everything on the `transactions` topic until the partition ends."""
from confluent_kafka import Consumer, KafkaError
from __future__ import annotations
conf = {
"bootstrap.servers": "localhost:9092",
"group.id": "test_group",
"auto.offset.reset": "earliest",
}
import logging
consumer = Consumer(**conf)
consumer.subscribe(["transactions"])
from confluent_kafka import Consumer
logger = logging.getLogger(__name__)
# confluent-kafka names this error _PARTITION_EOF, leading underscore and all.
# `KafkaError.name()` is the public way to ask for it without reaching into a
# private attribute; it returns exactly this string.
PARTITION_EOF = "_PARTITION_EOF"
def main() -> None:
"""Consume until a broker error other than end-of-partition arrives."""
conf = {
"bootstrap.servers": "localhost:9092",
"group.id": "test_group",
"auto.offset.reset": "earliest",
}
consumer = Consumer(**conf)
consumer.subscribe(["transactions"])
try:
while True:
msg = consumer.poll(timeout=1.0)
if msg is None:
continue
error = msg.error()
if error is not None:
if error.name() == PARTITION_EOF:
continue
logger.error("%s", error)
break
value = msg.value()
if value is not None:
logger.info("Received message: %s", value.decode("utf-8"))
finally:
consumer.close()
if __name__ == "__main__":
logging.basicConfig(format="%(message)s", level=logging.INFO)
main()
while True:
msg = consumer.poll(timeout=1.0)
if msg is None:
continue
if msg.error():
if msg.error().code() == KafkaError._PARTITION_EOF:
continue
else:
print(msg.error())
break
print("Received message: {}".format(msg.value().decode("utf-8")))
consumer.close()

39
Programming/PSD/webinterface/webinterface.py Executable file → Normal file
View File

@ -1,31 +1,11 @@
#!/usr/bin/env python3
"""A one-route Flask app that drains the `alarms` topic and returns it as JSON."""
from __future__ import annotations
import json
import os
from typing import TYPE_CHECKING
from confluent_kafka import Consumer
from confluent_kafka import Consumer, KafkaError
from flask import Flask, jsonify
if TYPE_CHECKING:
from flask.typing import ResponseReturnValue
app = Flask(__name__)
# confluent-kafka names this error _PARTITION_EOF, leading underscore and all.
# `KafkaError.name()` is the public way to ask for it without reaching into a
# private attribute; it returns exactly this string.
PARTITION_EOF = "_PARTITION_EOF"
HTTP_INTERNAL_SERVER_ERROR = 500
@app.route("/alarms", methods=["GET"])
def get_alarms() -> ResponseReturnValue:
"""Return every alarm currently on the topic, oldest first."""
def get_alarms():
alarms = []
conf = {
"bootstrap.servers": "localhost:9092",
@ -40,20 +20,15 @@ def get_alarms() -> ResponseReturnValue:
msg = consumer.poll(timeout=1.0)
if msg is None:
break
error = msg.error()
if error is not None:
if error.name() == PARTITION_EOF:
if msg.error():
if msg.error().code() == KafkaError._PARTITION_EOF:
continue
return str(error), HTTP_INTERNAL_SERVER_ERROR
value = msg.value()
if value is not None:
alarms.append(json.loads(value.decode("utf-8")))
return str(msg.error()), 500
alarms.append(json.loads(msg.value().decode("utf-8")))
consumer.close()
return jsonify(alarms)
if __name__ == "__main__":
# Debug mode serves a console that executes arbitrary code, so it is opt-in
# rather than the default it used to be here.
app.run(debug=os.environ.get("FLASK_DEBUG") == "1")
app.run(debug=True)

23
Programming/PSD/zin1/konsument.py Executable file → Normal file
View File

@ -1,23 +1,13 @@
#!/usr/bin/env python3
"""Read the temperature_readings topic and shout about the extremes."""
from __future__ import annotations
import json
import logging
from typing import Any
from kafka import KafkaConsumer
logger = logging.getLogger(__name__)
# Thresholds
TEMP_TOO_COLD = -10
TEMP_TOO_HOT = 35
def process_temperature_reading(reading: dict[str, Any]) -> str:
"""Return the line to print for one reading."""
def process_temperature_reading(reading):
temperature = reading["temperature"]
if temperature < TEMP_TOO_COLD:
alert = f"WARNING: Temperature is too cold! ({temperature}°C)"
@ -28,8 +18,7 @@ def process_temperature_reading(reading: dict[str, Any]) -> str:
return alert
def main() -> None:
"""Consume readings until interrupted."""
if __name__ == "__main__":
consumer = KafkaConsumer(
"temperature_readings",
bootstrap_servers="localhost:9092",
@ -38,9 +27,5 @@ def main() -> None:
for message in consumer:
reading = json.loads(message.value)
logger.info("%s", process_temperature_reading(reading))
if __name__ == "__main__":
logging.basicConfig(format="%(message)s", level=logging.INFO)
main()
alert_message = process_temperature_reading(reading)
print(alert_message)

41
Programming/PSD/zin1/producent.py Executable file → Normal file
View File

@ -1,43 +1,22 @@
#!/usr/bin/env python3
"""Send a simulated reading to the temperature_readings topic, now and then."""
from __future__ import annotations
import json
import logging
import random
import time
from secrets import SystemRandom
from typing import Any
from kafka import KafkaProducer
from simulate_temperature_sensor import generate_temperature_reading
logger = logging.getLogger(__name__)
MIN_INTERVAL_SECONDS = 1
MAX_INTERVAL_SECONDS = 5
_random = SystemRandom()
def serializer(message: dict[str, Any]) -> bytes:
"""Encode one message as UTF-8 JSON for Kafka."""
def serializer(message):
return json.dumps(message).encode("utf-8")
def main() -> None:
"""Produce readings until interrupted."""
producer = KafkaProducer(
bootstrap_servers=["localhost:9092"], value_serializer=serializer
)
while True:
reading = generate_temperature_reading()
logger.info("Sending reading: %s", reading)
producer.send("temperature_readings", reading)
# Simulate readings sent at random intervals
time.sleep(_random.randint(MIN_INTERVAL_SECONDS, MAX_INTERVAL_SECONDS))
producer = KafkaProducer(
bootstrap_servers=["localhost:9092"], value_serializer=serializer
)
if __name__ == "__main__":
logging.basicConfig(format="%(message)s", level=logging.INFO)
main()
while True:
reading = generate_temperature_reading()
print(f"Sending reading: {reading}")
producer.send("temperature_readings", reading)
time.sleep(random.randint(1, 5)) # Simulate readings sent at random intervals

23
Programming/PSD/zin1/simulate_temperature_sensor.py Executable file → Normal file
View File

@ -1,24 +1,11 @@
#!/usr/bin/env python3
"""Stand-in for the sensors: one reading from one of ten made-up locations."""
from __future__ import annotations
import random
import time
from secrets import SystemRandom
from typing import Any
LOCATION_COUNT = 10
MIN_TEMPERATURE = -20
MAX_TEMPERATURE = 40
_random = SystemRandom()
def generate_temperature_reading() -> dict[str, Any]:
"""Return one reading: a location, a temperature and a Unix timestamp."""
location_id = _random.randint(1, LOCATION_COUNT) # Simulate 10 different locations
temperature = _random.uniform(
MIN_TEMPERATURE, MAX_TEMPERATURE
def generate_temperature_reading():
location_id = random.randint(1, 10) # Simulate 10 different locations
temperature = random.uniform(
-20, 40
) # Temperature range from -20 to 40 degrees Celsius
timestamp = time.time() # Current Unix timestamp
return {

View File

@ -1,53 +1,37 @@
#!/usr/bin/env python3
"""Publish a simulated reading from each of five thermometers, once a second.
The readings go to the Temperatura topic, where the Flink job in
`../processor/` picks them up and republishes the below-zero ones as alarms.
"""
import json
import logging
import os
import random
import sys
import time
from pathlib import Path
from secrets import SystemRandom
from confluent_kafka import Message, Producer
from confluent_kafka import Producer
# Add parent directory to path to import model
sys.path.append(str(Path(__file__).resolve().parent.parent))
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from model.temperature_reading import TemperatureReading
logger = logging.getLogger(__name__)
# Readings are drawn from this range, so roughly a quarter of them alarm.
MIN_TEMPERATURE = -10
MAX_TEMPERATURE = 30
THERMOMETER_IDS = ["Therm-1", "Therm-2", "Therm-3", "Therm-4", "Therm-5"]
_random = SystemRandom()
def delivery_report(err: object, _msg: Message) -> None:
"""Report a failed delivery; successful ones are not worth a line each."""
def delivery_report(err, msg):
"""Callback for message delivery reports."""
if err is not None:
logger.error("Message delivery failed: %s", err)
print(f"Message delivery failed: {err}")
else:
pass # Successfully delivered
def main() -> None:
"""Produce readings until interrupted."""
def main():
# Set up Kafka producer with confluent-kafka
producer_config = {"bootstrap.servers": "localhost:9092"}
producer = Producer(producer_config)
# Generate a fixed number of thermometer IDs
thermometer_ids = ["Therm-1", "Therm-2", "Therm-3", "Therm-4", "Therm-5"]
try:
while True:
for thermometer_id in THERMOMETER_IDS:
for thermometer_id in thermometer_ids:
# Generate a random temperature between -10 and 30 degrees
temperature = _random.uniform(MIN_TEMPERATURE, MAX_TEMPERATURE)
temperature = random.uniform(-10, 30)
# Create reading object
reading = TemperatureReading(
@ -68,18 +52,17 @@ def main() -> None:
callback=delivery_report,
)
producer.flush(timeout=1)
logger.debug("Sent: %s", json.dumps(reading_dict))
# print(f"Sent: {json.dumps(reading_dict)}")
# Sleep for a second
time.sleep(1)
except KeyboardInterrupt:
logger.info("Stopping temperature generator")
print("Stopping temperature generator")
finally:
# Wait for any outstanding messages to be delivered
producer.flush()
if __name__ == "__main__":
logging.basicConfig(format="%(message)s", level=logging.INFO)
main()

View File

@ -1,27 +1,10 @@
#!/usr/bin/env python3
"""The alarm the detector publishes to the Alarm topic."""
from __future__ import annotations
from typing import Any
class TemperatureAlarm:
"""One below-zero reading: who reported it, when, and how cold."""
def __init__(
self,
thermometer_id: str | None = None,
timestamp: int | None = None,
temperature: float | None = None,
) -> None:
"""Store the three fields, all optional so a partial message still parses."""
def __init__(self, thermometer_id=None, timestamp=None, temperature=None):
self.thermometer_id = thermometer_id
self.timestamp = timestamp
self.temperature = temperature
def to_dict(self) -> dict[str, Any]:
"""Return the camelCase form that goes on the wire."""
def to_dict(self):
return {
"thermometerId": self.thermometer_id,
"timestamp": self.timestamp,
@ -29,8 +12,7 @@ class TemperatureAlarm:
}
@classmethod
def from_dict(cls, data: dict[str, Any]) -> TemperatureAlarm:
"""Build an alarm from the camelCase form that came off the wire."""
def from_dict(cls, data):
return cls(
thermometer_id=data.get("thermometerId"),
timestamp=data.get("timestamp"),

View File

@ -1,27 +1,10 @@
#!/usr/bin/env python3
"""The reading the generator publishes to the Temperatura topic."""
from __future__ import annotations
from typing import Any
class TemperatureReading:
"""One thermometer sample: who reported it, when, and how warm."""
def __init__(
self,
thermometer_id: str | None = None,
timestamp: int | None = None,
temperature: float | None = None,
) -> None:
"""Store the three fields, all optional so a partial message still parses."""
def __init__(self, thermometer_id=None, timestamp=None, temperature=None):
self.thermometer_id = thermometer_id
self.timestamp = timestamp
self.temperature = temperature
def to_dict(self) -> dict[str, Any]:
"""Return the camelCase form that goes on the wire."""
def to_dict(self):
return {
"thermometerId": self.thermometer_id,
"timestamp": self.timestamp,
@ -29,8 +12,7 @@ class TemperatureReading:
}
@classmethod
def from_dict(cls, data: dict[str, Any]) -> TemperatureReading:
"""Build a reading from the camelCase form that came off the wire."""
def from_dict(cls, data):
return cls(
thermometer_id=data.get("thermometerId"),
timestamp=data.get("timestamp"),

View File

@ -1,18 +1,6 @@
#!/usr/bin/env python3
"""Flink job: read the Temperatura topic and republish below-zero readings.
Run it against a local Kafka on 9092. The connector JARs are not bundled with
pyflink, so `add_kafka_dependencies` points the environment at a Kafka and a
Flink install and reports precisely which JAR is missing when one is.
"""
from __future__ import annotations
import json
import logging
import os
import sys
from pathlib import Path
from typing import TYPE_CHECKING
from pyflink.common.serialization import SimpleStringSchema
from pyflink.common.typeinfo import Types
@ -21,48 +9,25 @@ from pyflink.datastream import StreamExecutionEnvironment
from pyflink.datastream.connectors import FlinkKafkaConsumer, FlinkKafkaProducer
from pyflink.datastream.functions import KeyedProcessFunction, MapFunction
if TYPE_CHECKING:
from collections.abc import Iterator
# Add parent directory to path to import model
sys.path.append(str(Path(__file__).resolve().parent.parent))
logger = logging.getLogger(__name__)
# A reading at or below this temperature is what the job is looking for.
ALARM_TEMPERATURE = 0.0
# Where the Kafka and Flink installs live on the lab machine.
KAFKA_LIB_PATH = Path("/home/psd/Downloads/kafka_2.13-3.4.0/libs")
FLINK_LIB_PATH = Path("/home/psd/Downloads/flink-1.17.0/lib")
KAFKA_CLIENTS_JAR = "kafka-clients-3.4.0.jar"
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
class ReadingMapFunction(MapFunction):
"""Turn a JSON reading into the (id, timestamp, temperature) tuple."""
def map(self, value: str) -> tuple[str, int, float]:
"""Parse one message off the Temperatura topic."""
def map(self, value):
data = json.loads(value)
return (data["thermometerId"], data["timestamp"], data["temperature"])
class AnomalyDetectionFunction(KeyedProcessFunction):
"""Emit an alarm for every reading below zero."""
def __init__(self) -> None:
"""Set the window the job was written around."""
def __init__(self):
self.window_size = 10 * 1000 # 10 seconds in milliseconds
def process_element(
self, value: tuple[str, int, float], ctx: object
) -> Iterator[str]:
"""Yield a JSON alarm when `value` is below zero, otherwise nothing."""
del ctx
def process_element(self, value, ctx):
thermometer_id, timestamp, temperature = value
# Check if temperature is below zero (anomaly)
if temperature < ALARM_TEMPERATURE:
if temperature < 0.0:
# Create alarm
alarm = {
"thermometerId": thermometer_id,
@ -72,40 +37,50 @@ class AnomalyDetectionFunction(KeyedProcessFunction):
yield json.dumps(alarm)
def add_kafka_dependencies(env: StreamExecutionEnvironment) -> None:
def add_kafka_dependencies(env):
"""Add Kafka connector dependencies to the environment."""
# User-specific paths where JAR files are located
kafka_path = "/home/psd/Downloads/kafka_2.13-3.4.0/libs"
flink_path = "/home/psd/Downloads/flink-1.17.0/lib"
# Required JAR files
kafka_jars = {
"kafka-clients": "kafka-clients-3.4.0.jar",
"flink-connector-kafka": None, # Will be detected or reported as missing
}
jar_paths = []
# Add kafka-clients JAR
clients_jar = KAFKA_LIB_PATH / KAFKA_CLIENTS_JAR
if clients_jar.exists():
clients_jar = os.path.join(kafka_path, kafka_jars["kafka-clients"])
if os.path.exists(clients_jar):
jar_paths.append(f"file://{clients_jar}")
else:
logger.warning("Could not find Kafka clients JAR at %s", clients_jar)
print(f"Warning: Could not find Kafka clients JAR at {clients_jar}")
# Try to find Flink Kafka connector JAR
connector = next(
(p for p in sorted(FLINK_LIB_PATH.glob("flink-connector-kafka*"))), None
)
if connector is not None:
jar_paths.append(f"file://{connector}")
else:
logger.warning(
"No Flink Kafka connector JAR found. Download one named like "
"'flink-connector-kafka-1.17.0.jar' from Maven Central or the "
"Apache Flink website and place it in %s",
FLINK_LIB_PATH,
)
connector_found = False
for file in os.listdir(flink_path):
if file.startswith("flink-connector-kafka"):
kafka_jars["flink-connector-kafka"] = file
jar_paths.append(f"file://{os.path.join(flink_path, file)}")
connector_found = True
break
if not connector_found:
print("Warning: No Flink Kafka connector JAR found! You need to download it.")
print("You can download it from Maven Central or the Apache Flink website.")
print("The JAR should be named like 'flink-connector-kafka-1.17.0.jar'")
print(f"Place it in: {flink_path}")
if jar_paths:
env.get_config().get_configuration().set_string(
"pipeline.jars", ";".join(jar_paths)
)
logger.info("Added JAR files: %s", jar_paths)
print(f"Added JAR files: {jar_paths}")
def main() -> None:
"""Wire the Kafka source to the detector to the Kafka sink, and run it."""
def main():
# Create execution environment
env = StreamExecutionEnvironment.get_execution_environment()
@ -141,17 +116,16 @@ def main() -> None:
output_type=Types.TUPLE([Types.STRING(), Types.LONG(), Types.DOUBLE()]),
).assign_timestamps_and_watermarks(
WatermarkStrategy.for_monotonous_timestamps().with_timestamp_assigner(
lambda event, _timestamp: event[1]
lambda event, timestamp: event[1]
)
).key_by(lambda x: x[0]).process(AnomalyDetectionFunction()).add_sink(producer)
# Print the execution plan
logger.info("%s", env.get_execution_plan())
print(env.get_execution_plan())
# Execute
env.execute("Temperature Anomaly Detector with Time Windows")
if __name__ == "__main__":
logging.basicConfig(format="%(message)s", level=logging.INFO)
main()

View File

@ -1,40 +1,21 @@
#!/usr/bin/env python3
"""A Tk window listing the alarms as they arrive on the Alarm topic.
The Kafka consumer runs on a daemon thread and hands each alarm back to the Tk
main loop with `root.after`, because Tk widgets may only be touched from the
thread that created them.
"""
from __future__ import annotations
import json
import logging
import os
import sys
import threading
import tkinter as tk
from collections import Counter
from datetime import datetime, timezone
from pathlib import Path
from datetime import datetime
from tkinter import ttk
from confluent_kafka import Consumer
# Add parent directory to path to import model
sys.path.append(str(Path(__file__).resolve().parent.parent))
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from model.temperature_alarm import TemperatureAlarm
logger = logging.getLogger(__name__)
# Milliseconds per second, for turning the wire timestamp into a datetime.
MILLISECONDS = 1000
class AlarmVisualizer:
"""The window: a scrolling list of alarms and a per-thermometer tally."""
def __init__(self, root: tk.Tk) -> None:
"""Build the widgets and start consuming."""
def __init__(self, root):
self.root = root
self.root.title("Temperature Alarm Visualizer")
self.root.geometry("600x400")
@ -58,15 +39,14 @@ class AlarmVisualizer:
self.stats_label.pack(pady=5)
# Stats tracking
self.thermometer_alarm_count: Counter[str] = Counter()
self.thermometer_alarm_count = Counter()
self.max_alarms = 100
# Start Kafka consumer in a separate thread
self.consumer_thread = threading.Thread(target=self.consume_alarms, daemon=True)
self.consumer_thread.start()
def consume_alarms(self) -> None:
"""Poll the Alarm topic forever, handing each alarm to the Tk thread."""
def consume_alarms(self):
# Set up Kafka consumer with confluent-kafka
consumer_config = {
"bootstrap.servers": "localhost:9092",
@ -82,39 +62,29 @@ class AlarmVisualizer:
if msg is None:
continue
if msg.error():
logger.error("Consumer error: %s", msg.error())
print(f"Consumer error: {msg.error()}")
continue
# Parse the alarm message
value = msg.value()
if value is None:
continue
alarm_data = json.loads(value.decode("utf-8"))
alarm_data = json.loads(msg.value().decode("utf-8"))
alarm = TemperatureAlarm.from_dict(alarm_data)
if alarm.timestamp is None or alarm.thermometer_id is None:
logger.warning("Skipping malformed alarm: %s", alarm_data)
continue
# Format the timestamp
timestamp_dt = datetime.fromtimestamp(
alarm.timestamp / MILLISECONDS, tz=timezone.utc
).astimezone()
timestamp_dt = datetime.fromtimestamp(alarm.timestamp / 1000)
formatted_date = timestamp_dt.strftime("%Y-%m-%d %H:%M:%S")
# Create alarm message
alarm_message = (
f"⚠️ ALARM: Thermometer {alarm.thermometer_id} "
f"reported {alarm.temperature:.2f}°C at {formatted_date}"
)
alarm_message = f"⚠️ ALARM: Thermometer {alarm.thermometer_id} reported {alarm.temperature:.2f}°C at {formatted_date}"
# Update the UI
self.root.after(0, self.update_ui, alarm_message, alarm.thermometer_id)
except Exception as e:
print(f"Error in Kafka consumer: {e}")
finally:
consumer.close()
def update_ui(self, alarm_message: str, thermometer_id: str) -> None:
"""Insert one alarm at the top of the list and refresh the tally."""
def update_ui(self, alarm_message, thermometer_id):
# Add new alarm to the top of the list
self.alarm_list.insert(0, alarm_message)
@ -128,20 +98,17 @@ class AlarmVisualizer:
# Format stats string
if self.thermometer_alarm_count:
stats_parts = [
f"{name}={count}"
for name, count in self.thermometer_alarm_count.items()
f"{id}={count}" for id, count in self.thermometer_alarm_count.items()
]
stats_text = "Alarm Counts: " + ", ".join(stats_parts)
self.stats_label.config(text=stats_text)
def main() -> None:
"""Open the window and run the Tk main loop."""
def main():
root = tk.Tk()
AlarmVisualizer(root)
app = AlarmVisualizer(root)
root.mainloop()
if __name__ == "__main__":
logging.basicConfig(format="%(message)s", level=logging.INFO)
main()

View File

@ -32,10 +32,133 @@ own docs and the rest of this fleet carry. A test asserts by raising.
|---|---|
| Baseline, before any of this | 9,281 |
| After the format + safe-fix pass and excluding `TRAK/sightpy` | 3,686 |
| **Now** | **0** |
| **Now** | **423** |
**Every course is at zero.** 9,281 findings to 0.
Courses at zero: `WDWR`, `SPD`, `MOM`, `ECRYPT`, `ECRYPT_PROJECT`, `ECOTE`,
`NLP`, `EARIN`, `PORR`, `TRAK`, `twm_4`. What is left, by course:
What that cost, and what it bought, is in the commit messages; the standing
rules for the next pass are below.
| Course | ruff | Can it be verified by running? |
|---|---|---|
| `ERSMS-project` | 156 | No: docker-compose course |
| `PSD` | 152 | No: `run.sh` predates the harness and installs packages with sudo |
| `PBAD` | 115 | No: same dead jupyter shim |
`course_run.sh`'s notebook branch is fixed: it executes to a temp
`--output-dir`, probes jupyter by running it rather than by `command -v`, and
`course_main` now fails if a run changed anything git can see under the course
root. `PBAD` is still blocked on jupyter itself -- the binary on PATH is a
pipx shim whose interpreter is gone, so `--probe` reports "needs jupyter".
**A notebook does not need to be executed to be linted.** ruff reads `.ipynb`
natively and rewrites `source` only, so the check that the deliverable is
intact is a hash of everything EXCEPT `source`:
```python
stripped = {k: v for k, v in nb.items() if k != "cells"}
stripped["cells"] = [{k: v for k, v in c.items() if k != "source"} for c in nb["cells"]]
```
That hash was identical across all four passes on `twm_4`. The notebook also
round-trips byte-for-byte through
`json.dumps(nb, indent=1, ensure_ascii=False) + "\n"`, which is what makes
editing cells programmatically safe -- check that before touching PBAD's three.
## mypy has NOT been run against any of this
`pyproject.toml` sets `strict = true` and `CLAUDE.md` says the repo runs mypy.
mypy IS installed now (`~/.local/bin/mypy`) -- the earlier note here saying it
was not is out of date. **"Zero findings" in a commit message still means zero
RUFF findings unless it says otherwise**; only `TRAK` has been type-checked.
| Course | mypy --strict errors |
|---|---|
| `WDWR`, `SPD`, `MOM`, `ECRYPT_PROJECT` | 0 |
| `ECOTE` | 14 |
| `NLP` | 29 |
| `EARIN/lab1` alone | 46 |
| `TRAK` | **0** -- cleared 2026-08-29 |
| `twm_4` | **0** -- cleared 2026-08-29 |
| `PSD/zin1` | 5 |
Two structural notes for whoever runs it next:
- It cannot be pointed at the whole repo. There are many `main.py` files and
mypy stops at `Duplicate module named "main"`. Run it per directory.
- Most errors are `Returning Any` from untyped third-party calls (openai,
pandas) and genuinely-wrong unions this pass introduced by hand, e.g.
`str | bool` returns in `gpt_chunks.reformat`. They are real.
- Point it at the course's own venv or every import is unresolvable:
`mypy --strict --python-executable Programming/<course>/.venv/bin/python <dir>`.
Without that, TRAK reported 4 phantom `matplotlib` import errors on top of
the real ones.
- `pyproject.toml` now carries a `[[tool.mypy.overrides]]` block with
`ignore_missing_imports` for `Imath`, `OpenEXR`, `OpenGL` and `matplotlib`.
Those four ship neither stubs nor `py.typed`; without it mypy cannot import
them at all and reports nothing else about the file. It is not a suppression
of our own code -- do not extend it to anything we wrote.
## Still open
### 1. The 250-line cap: 50 files
| Type | Count | Note |
|---|---|---|
| `.txt` | 27 | Blocked -- see `TODO-file-length-250.md` |
| `.py` | 10 | Several GREW during the lint pass, because docstrings and annotations are lines: `NLP/gpt_chunks.py` 911 -> 973, `EARIN/lab2/main.py` 581 -> 647, `PORR/.../linear_algebra_utils.py` 422 -> 553. Split them AFTER the lint work, not during. TRAK is already clear: its three over-cap files were split in the same pass that linted them, each verified by a byte-identical render. `twm_4/TWM_KerasIntro.py` joined the list at 407 lines and should NOT be split: it is an nbconvert export, and a partial one |
| `.cpp` | 9 | |
| `.c` | 4 | |
| `.java` | 2 | |
| `.tex` | 1 | `ELAC/.../03-building-nfa-...tex`, 418 lines of consecutive tikz figures with no subsection to split on |
### 2. Coverage
`gates/coverage.tsv` is designed but not written, and there are 125 tests for
~28k lines. The largest remaining item by a wide margin.
### 3. Dependency freshness
9 `requirements.txt`, 5 `package.json`, 7 `pom.xml`, 1 `.csproj`, none pinned.
**The upgrade and the gate must land in the SAME commit.**
### 4. File-rewriting hooks
`trailing-whitespace` and `end-of-file-fixer` are deliberately absent; they
want their own reviewed commit.
### 5. Three checks that must be run on every future pass
`scripts/check_refactor_safety.py` exists because ruff and a smoke run BOTH
missed three regressions this campaign introduced. Run it before and after any
automated rewrite:
```bash
cp -r <course> /tmp/before
# ...do the pass...
./scripts/check_refactor_safety.py --signatures /tmp/before <course>
./scripts/check_refactor_safety.py --logging --print-keywords <course>
```
And run mypy per directory afterwards: it found 12 latent TypeErrors in EARIN
that ruff could not see -- call sites still passing positionally to arguments
the pass had made keyword-only.
Prefer a check the program itself settles. TRAK's `ray_tracing0` path has no
RNG at all, so `main.py --algorithm ray_tracing0 --output ../build/x.png`
renders byte-identically every time: refactoring 109 findings out of
`rendering.py` and splitting it in two was verified by one md5 comparison. The
cornell_box path is stochastic and cannot be used that way -- its ray count
drifts by ~20 between runs on its own. Where an RNG is unavoidable, do the
restructure and the `NPY002` swap as SEPARATE steps: the first must be
bit-identical under an external seed, only the second may move the pixels.
### 6. Disk
`Programming/PORR/code/` holds 3.8 GB of generated .npz caches (poli3 alone is
2.3 GB). All gitignored, all regenerable, none of it needed unless the full
benchmark is re-run.
## Standing rule
A gate lands only once the thing it gates is clean, so `pre-commit run
--all-files` is green at every commit. Every hook still missing from
`.pre-commit-config.yaml` is listed there with what blocks it.

View File

@ -86,11 +86,6 @@ module = [
"tensorflow.*",
"sklearn.*",
"seaborn.*",
"kafka.*",
"pyflink.*",
"pandas.*",
"psycopg2.*",
"firebase_admin.*",
]
ignore_missing_imports = true