Sky_Anomaly / app.py
broadfield-dev's picture
Update app.py
8668322 verified
from flask import Flask, render_template, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from huggingface_hub import HfApi
import pandas as pd
import os
import requests
app = Flask(__name__)
# Configure SQLite database
basedir = os.path.abspath(os.path.dirname(__file__))
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'app.db')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
# Dataset repository ID (replace with your dataset)
DATASET_REPO_ID = 'broadfield-dev/sky-anomaly-data' # Update with your repository
# Database model for anomaly reports
class Report(db.Model):
id = db.Column(db.Integer, primary_key=True)
latitude = db.Column(db.Float, nullable=False)
longitude = db.Column(db.Float, nullable=False)
direction = db.Column(db.Float, nullable=False) # Arrow rotation in degrees
start_lat = db.Column(db.Float)
start_lon = db.Column(db.Float)
end_lat = db.Column(db.Float)
end_lon = db.Column(db.Float)
description = db.Column(db.Text)
timestamp = db.Column(db.String(20))
observer_name = db.Column(db.String(100))
# Export reports to Hugging Face Hub
def export_to_hub():
try:
reports = Report.query.all()
data = [{
'id': r.id,
'latitude': r.latitude,
'longitude': r.longitude,
'direction': r.direction,
'start_lat': r.start_lat,
'start_lon': r.start_lon,
'end_lat': r.end_lat,
'end_lon': r.end_lon,
'description': r.description,
'timestamp': r.timestamp,
'observer_name': r.observer_name
} for r in reports]
# Save to CSV
df = pd.DataFrame(data)
csv_path = os.path.join(basedir, 'reports.csv')
df.to_csv(csv_path, index=False)
# Upload to Hugging Face Hub
api = HfApi()
api.upload_file(
path_or_fileobj=csv_path,
path_in_repo='reports.csv',
repo_id=DATASET_REPO_ID,
repo_type='dataset',
token=os.getenv('HF_TOKEN')
)
print("Successfully exported reports to Hugging Face Hub")
except Exception as e:
print(f"Failed to export to Hub: {e}")
# Load reports from Hugging Face Hub
def load_from_hub():
try:
# Download reports.csv from the dataset
csv_url = f'https://huggingface.co/datasets/{DATASET_REPO_ID}/raw/main/reports.csv'
response = requests.get(csv_url)
if response.status_code == 200:
# Save CSV locally
csv_path = os.path.join(basedir, 'reports.csv')
with open(csv_path, 'wb') as f:
f.write(response.content)
# Read CSV and populate database
df = pd.read_csv(csv_path)
for _, row in df.iterrows():
# Check if report already exists to avoid duplicates
existing = Report.query.filter_by(id=row['id']).first()
if not existing:
report = Report(
id=row['id'],
latitude=row['latitude'],
longitude=row['longitude'],
direction=row['direction'],
start_lat=row['start_lat'] if pd.notna(row['start_lat']) else None,
start_lon=row['start_lon'] if pd.notna(row['start_lon']) else None,
end_lat=row['end_lat'] if pd.notna(row['end_lat']) else None,
end_lon=row['end_lon'] if pd.notna(row['end_lon']) else None,
description=row['description'] if pd.notna(row['description']) else None,
timestamp=row['timestamp'] if pd.notna(row['timestamp']) else None,
observer_name=row['observer_name'] if pd.notna(row['observer_name']) else None
)
db.session.add(report)
db.session.commit()
print("Successfully loaded reports from Hugging Face Hub")
else:
print(f"Failed to download CSV: HTTP {response.status_code}")
except Exception as e:
print(f"Failed to load from Hub: {e}")
# Initialize database and load data
with app.app_context():
db.create_all()
# Load from Hub if database is empty
if Report.query.count() == 0:
load_from_hub()
@app.route('/')
def index():
reports = Report.query.all()
reports_data = [
{
'id': r.id,
'latitude': r.latitude,
'longitude': r.longitude,
'direction': r.direction,
'description': r.description,
'timestamp': r.timestamp,
'observer_name': r.observer_name
} for r in reports
]
return render_template('index.html', reports=reports_data)
@app.route('/add_report', methods=['GET', 'POST'])
def add_report():
if request.method == 'POST':
data = request.form
try:
report = Report(
latitude=float(data['latitude']),
longitude=float(data['longitude']),
direction=float(data['direction']),
start_lat=float(data['start_lat']) if data['start_lat'] else None,
start_lon=float(data['start_lon']) if data['start_lon'] else None,
end_lat=float(data['end_lat']) if data['end_lat'] else None,
end_lon=float(data['end_lon']) if data['end_lon'] else None,
description=data['description'],
timestamp=data['timestamp'],
observer_name=data['observer_name']
)
db.session.add(report)
db.session.commit()
# Export to Hugging Face Hub after adding report
export_to_hub()
return jsonify({'status': 'success', 'message': 'Report added successfully'})
except Exception as e:
db.session.rollback()
return jsonify({'status': 'error', 'message': str(e)}), 400
return render_template('add_report.html')
if __name__ == '__main__':
app.run(host='0.0.0.0', port=7860, debug=True)