File size: 6,219 Bytes
0a50640
 
d839675
 
0a50640
d839675
0a50640
 
 
 
 
 
 
 
 
d839675
8668322
d839675
0a50640
 
 
 
 
 
 
 
 
 
 
 
 
 
d839675
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8668322
d839675
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8668322
 
d839675
 
 
 
 
 
 
 
 
 
0a50640
 
8668322
d839675
 
0a50640
 
 
 
 
 
 
 
 
 
 
 
8668322
0a50640
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8668322
0a50640
 
 
8668322
d839675
0a50640
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
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)