Skip to content
Snippets Groups Projects
Select Git revision
  • 476b8e54fe86a2da9f8e72c6c4e200587608ef53
  • main default protected
  • develop
3 results

app.py

Blame
  • Saket Agrahari's avatar
    Saket Agrahari authored
    476b8e54
    History
    app.py 7.18 KiB
    from flask import Flask, jsonify, send_file
    from flask_cors import CORS
    import json
    import os
    
    app = Flask(__name__)
    # Configure CORS to allow all origins
    CORS(app, resources={
        r"/api/*": {
            "origins": ["http://localhost:3000"],
            "methods": ["GET", "POST", "OPTIONS"],
            "allow_headers": ["Content-Type"]
        }
    })
    
    # Create data directory if it doesn't exist
    DATA_DIR = os.path.join(os.path.dirname(__file__), 'data')
    if not os.path.exists(DATA_DIR):
        os.makedirs(DATA_DIR)
    
    def convert_map_to_geojson():
        input_file_path = os.path.join(DATA_DIR, 'map.json')
        output_file_path = os.path.join(DATA_DIR, 'geant_map_geojson.json')
        
        try:
            with open(input_file_path, 'r') as f:
                network_data = json.load(f)
            
            geojson = {
                "type": "FeatureCollection",
                "features": []
            }
            
            for iptrunk in network_data['iptrunks']:
                if 'iptrunk_sides' in iptrunk['iptrunk']:
                    start_node = iptrunk['iptrunk']['iptrunk_sides'][0]['iptrunk_side_node']['router_site']
                    end_node = iptrunk['iptrunk']['iptrunk_sides'][1]['iptrunk_side_node']['router_site']
                    
                    coordinates = [
                        [float(start_node['site_longitude']), float(start_node['site_latitude'])],
                        [float(end_node['site_longitude']), float(end_node['site_latitude'])]
                    ]
                    
                    feature = {
                        "type": "Feature",
                        "properties": {
                            "subscription_id": iptrunk['subscription_id'],
                            "iptrunk_speed": iptrunk['iptrunk']['iptrunk_speed'],
                            "iptrunk_type": iptrunk['iptrunk']['iptrunk_type'],
                            "iptrunk_capacity": iptrunk['iptrunk']['iptrunk_capacity'],
                            "gs_id": iptrunk['iptrunk']['gs_id'],
                            "start_node_city": start_node['site_city'],
                            "end_node_city": end_node['site_city'],
                            "start_node_country": start_node['site_country'],
                            "end_node_country": end_node['site_country'],
                        },
                        "geometry": {
                            "type": "LineString",
                            "coordinates": coordinates
                        }
                    }
                    geojson['features'].append(feature)
            
            with open(output_file_path, 'w') as f:
                json.dump(geojson, f, indent=2)
        
        except Exception as e:
            print(f"Error converting to GeoJSON: {str(e)}")
    
    def convert_to_geojson(network_data):
        geojson = {
            "type": "FeatureCollection",
            "features": []
        }
        
        # Add nodes as Point features
        for node in network_data['cities']:  # Changed from 'nodes' to 'cities'
            feature = {
                "type": "Feature",
                "geometry": {
                    "type": "Point",
                    "coordinates": [float(node['long']), float(node['lat'])]  # Changed from longitude/latitude
                },
                "properties": {
                    "id": node['id'],
                    "name": node['name'],
                    "type": "node",
                    "region": node.get('region', ''),
                    "country_code": node.get('country_code', ''),
                    "info": node.get('info', '')
                }
            }
            geojson['features'].append(feature)
        
        # Add edges as LineString features
        for region, links in network_data['links'].items():
            for link in links:
                start_node = next((n for n in network_data['cities'] if n['id'] == link['endpoint1_id']), None)
                end_node = next((n for n in network_data['cities'] if n['id'] == link['endpoint2_id']), None)
                
                if start_node and end_node:
                    feature = {
                        "type": "Feature",
                        "geometry": {
                            "type": "LineString",
                            "coordinates": [
                                [float(start_node['long']), float(start_node['lat'])],
                                [float(end_node['long']), float(end_node['lat'])]
                            ]
                        },
                        "properties": {
                            "id": link['id'],
                            "source": link['endpoint1_id'],
                            "target": link['endpoint2_id'],
                            "type": "edge",
                            "capacity": link.get('capacity', ''),
                            "region": region,
                            "info": link.get('info', ''),
                            "network": link.get('network', '')
                        }
                    }
                    geojson['features'].append(feature)
        
        return geojson
    
    @app.route('/api/network-data')
    def get_network_data():
        try:
            file_path = os.path.join(DATA_DIR, 'nodes_and_edges.json')
            if not os.path.exists(file_path):
                return jsonify({"error": f"File not found: {file_path}"}), 404
                
            with open(file_path, 'r') as f:
                data = json.load(f)
                print("Backend data structure:", {
                    "cities_count": len(data.get('cities', [])),
                    "links_regions": list(data.get('links', {}).keys())
                })
                return jsonify(data)
                
        except json.JSONDecodeError as e:
            return jsonify({"error": f"Invalid JSON in file: {str(e)}"}), 400
        except Exception as e:
            return jsonify({"error": f"Server error: {str(e)}"}), 500
    
    @app.route('/api/topology')
    def get_topology():
        try:
            file_path = os.path.join(DATA_DIR, 'topo.json')
            if not os.path.exists(file_path):
                return jsonify({"error": f"File not found: {file_path}"}), 404
                
            with open(file_path, 'r') as f:
                topo_data = json.load(f)
                # Ensure the topology data is in GeoJSON format
                if 'type' not in topo_data:
                    # If it's not already GeoJSON, convert it
                    geojson = {
                        "type": "FeatureCollection",
                        "features": [{
                            "type": "Feature",
                            "geometry": feature,
                            "properties": {}
                        } for feature in topo_data.get('features', [])]
                    }
                    return jsonify(geojson)
                return jsonify(topo_data)
        except json.JSONDecodeError as e:
            return jsonify({"error": f"Invalid JSON in file: {str(e)}"}), 400
        except Exception as e:
            return jsonify({"error": f"Server error: {str(e)}"}), 500
    
    @app.route('/api/geant-map')
    def get_geant_map():
        try:
            file_path = os.path.join(DATA_DIR, 'geant_map_geojson.json')
            if not os.path.exists(file_path):
                return jsonify({"error": f"File not found: {file_path}"}), 404
                
            with open(file_path, 'r') as f:
                data = json.load(f)
                return jsonify(data)
                
        except json.JSONDecodeError as e:
            return jsonify({"error": f"Invalid JSON in file: {str(e)}"}), 400
        except Exception as e:
            return jsonify({"error": f"Server error: {str(e)}"}), 500
    
    if __name__ == '__main__':
        convert_map_to_geojson()
        app.run(debug=True)