This commit is contained in:
2026-03-03 11:27:29 +07:00
parent 0339f178cd
commit 078c91283d
7 changed files with 707 additions and 1 deletions

View File

@@ -1,2 +1,3 @@
paho-mqtt>=1.6.1
schedule>=1.2.0
schedule>=1.2.0
flask>=2.0.0

29
run_web.sh Executable file
View File

@@ -0,0 +1,29 @@
#!/bin/bash
# Start the Flask web application
cd "$(dirname "$0")"
# Check if virtual environment exists, if not create it
if [ ! -d "venv" ]; then
echo "Creating virtual environment..."
python3 -m venv venv
fi
# Activate virtual environment
source venv/bin/activate
# Install dependencies
echo "Installing dependencies..."
pip install -q -r requirements.txt
# Check if database exists
if [ ! -f "karung_counts.db" ]; then
echo "Error: Database karung_counts.db not found!"
echo "Please run the frigate_counter.py first to initialize the database."
exit 1
fi
# Run the Flask application
echo "Starting Flask web application..."
echo "Access the dashboard at: http://localhost:5000"
python web_app.py

222
templates/base.html Normal file
View File

@@ -0,0 +1,222 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{% block title %}Frigate Counter Dashboard{% endblock %}</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif;
background: #f5f5f5;
color: #333;
line-height: 1.6;
}
.container {
max-width: 1200px;
margin: 0 auto;
padding: 20px;
}
header {
background: #2c3e50;
color: white;
padding: 20px 0;
margin-bottom: 30px;
}
header h1 {
text-align: center;
font-size: 1.8rem;
}
header nav {
text-align: center;
margin-top: 10px;
}
header nav a {
color: white;
text-decoration: none;
margin: 0 15px;
padding: 5px 10px;
border-radius: 4px;
transition: background 0.3s;
}
header nav a:hover {
background: rgba(255,255,255,0.2);
}
.card {
background: white;
border-radius: 8px;
padding: 20px;
margin-bottom: 20px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.card h2 {
margin-bottom: 15px;
color: #2c3e50;
border-bottom: 2px solid #3498db;
padding-bottom: 10px;
}
table {
width: 100%;
border-collapse: collapse;
margin-top: 10px;
}
th, td {
padding: 12px;
text-align: left;
border-bottom: 1px solid #ddd;
}
th {
background: #3498db;
color: white;
font-weight: 600;
}
tr:hover {
background: #f8f9fa;
}
.badge {
display: inline-block;
padding: 4px 8px;
border-radius: 4px;
font-size: 0.85em;
font-weight: 600;
}
.badge-primary {
background: #3498db;
color: white;
}
.badge-success {
background: #27ae60;
color: white;
}
.badge-info {
background: #17a2b8;
color: white;
}
a {
color: #3498db;
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
.stats-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 20px;
margin-bottom: 20px;
}
.stat-card {
background: white;
border-radius: 8px;
padding: 20px;
text-align: center;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.stat-card h3 {
font-size: 2rem;
color: #3498db;
margin-bottom: 5px;
}
.stat-card p {
color: #666;
font-size: 0.9rem;
}
.empty-state {
text-align: center;
padding: 40px;
color: #666;
}
.empty-state h3 {
margin-bottom: 10px;
color: #999;
}
.date-selector {
margin-bottom: 20px;
}
.date-selector select {
padding: 8px 12px;
border: 1px solid #ddd;
border-radius: 4px;
font-size: 1rem;
}
.btn {
display: inline-block;
padding: 8px 16px;
border-radius: 4px;
text-decoration: none;
transition: background 0.3s;
font-size: 0.9rem;
}
.btn-primary {
background: #3498db;
color: white;
}
.btn-primary:hover {
background: #2980b9;
text-decoration: none;
}
footer {
text-align: center;
padding: 20px;
color: #666;
margin-top: 40px;
}
</style>
{% block extra_css %}{% endblock %}
</head>
<body>
<header>
<div class="container">
<h1>Frigate Counter Dashboard</h1>
<nav>
<a href="{{ url_for('index') }}">Dashboard</a>
</nav>
</div>
</header>
<div class="container">
{% block content %}{% endblock %}
</div>
<footer>
<p>Frigate Counter - Real-time bag counting system</p>
</footer>
{% block extra_js %}{% endblock %}
</body>
</html>

View File

@@ -0,0 +1,52 @@
{% extends "base.html" %}
{% block title %}{{ camera_name }} - Camera Details{% endblock %}
{% block content %}
<div class="card">
<h2>Camera: {{ camera_name }}</h2>
<div class="stats-grid">
<div class="stat-card">
<h3>{{ counts|length }}</h3>
<p>Days with Data</p>
</div>
<div class="stat-card">
<h3>{{ total }}</h3>
<p>Total Counts</p>
</div>
<div class="stat-card">
<h3>{{ (total / counts|length)|round(1) if counts|length > 0 else 0 }}</h3>
<p>Average per Day</p>
</div>
</div>
{% if counts %}
<table>
<thead>
<tr>
<th>Date</th>
<th>Count</th>
<th>Timestamp</th>
</tr>
</thead>
<tbody>
{% for item in counts %}
<tr>
<td><a href="{{ url_for('date_detail', date_str=item.date) }}">{{ item.date }}</a></td>
<td><span class="badge badge-success">{{ item.counter_value }}</span></td>
<td>{{ item.timestamp }}</td>
</tr>
{% endfor %}
</tbody>
</table>
{% else %}
<div class="empty-state">
<h3>No data for this camera</h3>
<p>There are no records for camera {{ camera_name }}.</p>
</div>
{% endif %}
<a href="{{ url_for('index') }}" class="btn btn-primary">← Back to Dashboard</a>
</div>
{% endblock %}

View File

@@ -0,0 +1,58 @@
{% extends "base.html" %}
{% block title %}{{ date }} - Daily Details{% endblock %}
{% block content %}
<div class="card">
<h2>Details for {{ date }}</h2>
<div class="date-selector">
<label for="date-select">Jump to date: </label>
<select id="date-select" onchange="window.location.href=this.value">
<option value="">Select a date...</option>
{% for d in available_dates %}
<option value="{{ url_for('date_detail', date_str=d) }}" {% if d == date %}selected{% endif %}>{{ d }}</option>
{% endfor %}
</select>
</div>
<div class="stats-grid">
<div class="stat-card">
<h3>{{ counts|length }}</h3>
<p>Camera Entries</p>
</div>
<div class="stat-card">
<h3>{{ total }}</h3>
<p>Total Counts</p>
</div>
</div>
{% if counts %}
<table>
<thead>
<tr>
<th>Camera Name</th>
<th>Count</th>
<th>Timestamp</th>
</tr>
</thead>
<tbody>
{% for item in counts %}
<tr>
<td><a href="{{ url_for('camera_detail', camera_name=item.camera_name) }}">{{ item.camera_name }}</a></td>
<td><span class="badge badge-success">{{ item.counter_value }}</span></td>
<td>{{ item.timestamp }}</td>
</tr>
{% endfor %}
</tbody>
</table>
{% else %}
<div class="empty-state">
<h3>No data for this date</h3>
<p>There are no records for {{ date }}.</p>
</div>
{% endif %}
<a href="{{ url_for('index') }}" class="btn btn-primary">← Back to Dashboard</a>
</div>
{% endblock %}

123
templates/index.html Normal file
View File

@@ -0,0 +1,123 @@
{% extends "base.html" %}
{% block title %}Dashboard - Frigate Counter{% endblock %}
{% block content %}
<!-- Today's Stats -->
<div class="stats-grid">
<div class="stat-card">
<h3>{{ today_data|length }}</h3>
<p>Cameras Active Today</p>
</div>
<div class="stat-card">
<h3>{{ today_data|sum(attribute='counter_value') }}</h3>
<p>Total Counts Today</p>
</div>
<div class="stat-card">
<h3>{{ summary|length }}</h3>
<p>Days with Data</p>
</div>
<div class="stat-card">
<h3>{{ cameras|sum(attribute='total_count') }}</h3>
<p>All Time Total</p>
</div>
</div>
<!-- Today's Details -->
<div class="card">
<h2>Today's Activity ({{ today }})</h2>
{% if today_data %}
<table>
<thead>
<tr>
<th>Camera</th>
<th>Count</th>
<th>Last Updated</th>
</tr>
</thead>
<tbody>
{% for item in today_data %}
<tr>
<td><a href="{{ url_for('camera_detail', camera_name=item.camera_name) }}">{{ item.camera_name }}</a></td>
<td><span class="badge badge-success">{{ item.counter_value }}</span></td>
<td>{{ item.timestamp }}</td>
</tr>
{% endfor %}
</tbody>
</table>
{% else %}
<div class="empty-state">
<h3>No data for today yet</h3>
<p>Counts will appear here once the counter starts receiving events.</p>
</div>
{% endif %}
</div>
<!-- Daily Summary -->
<div class="card">
<h2>Daily Summary</h2>
{% if summary %}
<table>
<thead>
<tr>
<th>Date</th>
<th>Cameras</th>
<th>Total Counts</th>
<th>Last Update</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{% for day in summary %}
<tr>
<td><strong>{{ day.date }}</strong></td>
<td><span class="badge badge-info">{{ day.camera_count }}</span></td>
<td><span class="badge badge-success">{{ day.total_count }}</span></td>
<td>{{ day.last_update }}</td>
<td><a href="{{ url_for('date_detail', date_str=day.date) }}" class="btn btn-primary">View Details</a></td>
</tr>
{% endfor %}
</tbody>
</table>
{% else %}
<div class="empty-state">
<h3>No data available</h3>
<p>Daily summaries will appear here once data is recorded.</p>
</div>
{% endif %}
</div>
<!-- Camera Summary -->
<div class="card">
<h2>Camera Summary</h2>
{% if cameras %}
<table>
<thead>
<tr>
<th>Camera Name</th>
<th>Days Active</th>
<th>Total Counts</th>
<th>Last Update</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{% for camera in cameras %}
<tr>
<td><strong>{{ camera.camera_name }}</strong></td>
<td><span class="badge badge-info">{{ camera.day_count }}</span></td>
<td><span class="badge badge-success">{{ camera.total_count }}</span></td>
<td>{{ camera.last_update }}</td>
<td><a href="{{ url_for('camera_detail', camera_name=camera.camera_name) }}" class="btn btn-primary">View Details</a></td>
</tr>
{% endfor %}
</tbody>
</table>
{% else %}
<div class="empty-state">
<h3>No cameras registered</h3>
<p>Camera data will appear here once events are processed.</p>
</div>
{% endif %}
</div>
{% endblock %}

221
web_app.py Normal file
View File

@@ -0,0 +1,221 @@
#!/usr/bin/env python3
"""
Flask Web Application for Frigate Counter
Displays daily karung counts from SQLite database
"""
from flask import Flask, render_template, jsonify, request
import sqlite3
from datetime import datetime, date, timedelta
from typing import List, Dict, Optional
import os
app = Flask(__name__)
DB_PATH = 'karung_counts.db'
def get_db_connection():
"""Create a database connection"""
conn = sqlite3.connect(DB_PATH)
conn.row_factory = sqlite3.Row
return conn
def get_daily_counts(selected_date: Optional[str] = None) -> List[Dict]:
"""Get counts for a specific date or all dates"""
conn = get_db_connection()
cursor = conn.cursor()
if selected_date:
cursor.execute('''
SELECT camera_name, date, counter_value, timestamp
FROM karung_counts
WHERE date = ?
ORDER BY timestamp DESC
''', (selected_date,))
else:
cursor.execute('''
SELECT camera_name, date, counter_value, timestamp
FROM karung_counts
ORDER BY date DESC, timestamp DESC
''')
rows = cursor.fetchall()
conn.close()
return [{
'camera_name': row['camera_name'],
'date': row['date'],
'counter_value': row['counter_value'],
'timestamp': row['timestamp']
} for row in rows]
def get_summary_by_date() -> List[Dict]:
"""Get daily summary grouped by date"""
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute('''
SELECT
date,
COUNT(DISTINCT camera_name) as camera_count,
SUM(counter_value) as total_count,
MAX(timestamp) as last_update
FROM karung_counts
GROUP BY date
ORDER BY date DESC
''')
rows = cursor.fetchall()
conn.close()
return [{
'date': row['date'],
'camera_count': row['camera_count'],
'total_count': row['total_count'] or 0,
'last_update': row['last_update']
} for row in rows]
def get_available_dates() -> List[str]:
"""Get list of all dates with data"""
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute('''
SELECT DISTINCT date
FROM karung_counts
ORDER BY date DESC
''')
rows = cursor.fetchall()
conn.close()
return [row['date'] for row in rows]
def get_camera_summary() -> List[Dict]:
"""Get summary by camera"""
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute('''
SELECT
camera_name,
COUNT(DISTINCT date) as day_count,
SUM(counter_value) as total_count,
MAX(timestamp) as last_update
FROM karung_counts
GROUP BY camera_name
ORDER BY camera_name
''')
rows = cursor.fetchall()
conn.close()
return [{
'camera_name': row['camera_name'],
'day_count': row['day_count'],
'total_count': row['total_count'] or 0,
'last_update': row['last_update']
} for row in rows]
@app.route('/')
def index():
"""Main page showing daily summary"""
summary = get_summary_by_date()
cameras = get_camera_summary()
available_dates = get_available_dates()
today = date.today().isoformat()
today_data = get_daily_counts(today)
return render_template('index.html',
summary=summary,
cameras=cameras,
today_data=today_data,
available_dates=available_dates,
today=today)
@app.route('/date/<date_str>')
def date_detail(date_str: str):
"""Show details for a specific date"""
counts = get_daily_counts(date_str)
available_dates = get_available_dates()
# Calculate total for this date
total = sum(c['counter_value'] for c in counts)
return render_template('date_detail.html',
date=date_str,
counts=counts,
total=total,
available_dates=available_dates)
@app.route('/camera/<camera_name>')
def camera_detail(camera_name: str):
"""Show details for a specific camera"""
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute('''
SELECT date, counter_value, timestamp
FROM karung_counts
WHERE camera_name = ?
ORDER BY date DESC
''', (camera_name,))
rows = cursor.fetchall()
conn.close()
counts = [{
'date': row['date'],
'counter_value': row['counter_value'],
'timestamp': row['timestamp']
} for row in rows]
total = sum(c['counter_value'] for c in counts)
return render_template('camera_detail.html',
camera_name=camera_name,
counts=counts,
total=total)
@app.route('/api/counts')
def api_counts():
"""API endpoint to get all counts"""
date_filter = request.args.get('date')
counts = get_daily_counts(date_filter)
return jsonify({
'counts': counts,
'date_filter': date_filter
})
@app.route('/api/summary')
def api_summary():
"""API endpoint to get daily summary"""
summary = get_summary_by_date()
return jsonify({'summary': summary})
@app.route('/api/cameras')
def api_cameras():
"""API endpoint to get camera summary"""
cameras = get_camera_summary()
return jsonify({'cameras': cameras})
if __name__ == '__main__':
# Ensure database exists
if not os.path.exists(DB_PATH):
print(f"Error: Database {DB_PATH} not found!")
exit(1)
# Run Flask app on all interfaces, port 5000
app.run(host='0.0.0.0', port=5000, debug=True)