Update app.py
Browse files
app.py
CHANGED
|
@@ -6,7 +6,6 @@ import folium
|
|
| 6 |
from folium import plugins
|
| 7 |
import webbrowser
|
| 8 |
import os
|
| 9 |
-
from geopy.distance import geodesic
|
| 10 |
|
| 11 |
# Configuração do banco de dados
|
| 12 |
def init_db():
|
|
@@ -54,50 +53,77 @@ def add_location(device_id, device_name, latitude, longitude, accuracy=10, batte
|
|
| 54 |
except Exception as e:
|
| 55 |
return f"❌ Erro: {str(e)}"
|
| 56 |
|
| 57 |
-
# Função para
|
| 58 |
-
def
|
| 59 |
-
# Cria um arquivo HTML temporário com JavaScript para captura de GPS
|
| 60 |
html_content = f"""
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
}},
|
| 77 |
-
error => {{
|
| 78 |
-
alert("Erro: " + error.message);
|
| 79 |
-
}},
|
| 80 |
-
{{ enableHighAccuracy: true }}
|
| 81 |
-
);
|
| 82 |
-
}} else {{
|
| 83 |
-
alert("Geolocalização não suportada neste navegador.");
|
| 84 |
-
}}
|
| 85 |
-
}}
|
| 86 |
-
</script>
|
| 87 |
-
</head>
|
| 88 |
-
<body>
|
| 89 |
-
<h1>Compartilhar Localização</h1>
|
| 90 |
-
<button onclick="captureLocation()">Compartilhar Minha Localização Atual</button>
|
| 91 |
-
<p>Permita o acesso à localização quando solicitado.</p>
|
| 92 |
-
</body>
|
| 93 |
-
</html>
|
| 94 |
-
"""
|
| 95 |
|
| 96 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 97 |
f.write(html_content)
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
|
| 102 |
# Função para obter mapa atualizado
|
| 103 |
def get_updated_map():
|
|
@@ -109,6 +135,7 @@ def get_updated_map():
|
|
| 109 |
FROM locations
|
| 110 |
WHERE timestamp = (SELECT MAX(timestamp) FROM locations l2
|
| 111 |
WHERE l2.device_id = locations.device_id)
|
|
|
|
| 112 |
''', conn)
|
| 113 |
conn.close()
|
| 114 |
|
|
@@ -122,61 +149,70 @@ def get_updated_map():
|
|
| 122 |
for _, row in df.iterrows():
|
| 123 |
folium.Marker(
|
| 124 |
[row['latitude'], row['longitude']],
|
| 125 |
-
popup=f"
|
| 126 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 127 |
).add_to(m)
|
| 128 |
|
|
|
|
| 129 |
return m._repr_html_()
|
| 130 |
except Exception as e:
|
| 131 |
-
return f"Erro: {str(e)}"
|
| 132 |
|
| 133 |
# Interface Gradio
|
| 134 |
def create_interface():
|
| 135 |
with gr.Blocks(title="📍 Monitor GPS Automático") as demo:
|
| 136 |
-
gr.Markdown("
|
|
|
|
|
|
|
|
|
|
| 137 |
|
| 138 |
with gr.Row():
|
| 139 |
-
device_id = gr.Textbox(label="ID do Dispositivo", value="
|
| 140 |
-
device_name = gr.Textbox(label="Nome
|
| 141 |
|
| 142 |
with gr.Row():
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
gps_status = gr.Textbox(interactive=False)
|
| 147 |
-
|
| 148 |
-
gps_btn.click(
|
| 149 |
-
start_gps_capture,
|
| 150 |
-
inputs=[device_id, device_name],
|
| 151 |
-
outputs=gps_status
|
| 152 |
-
)
|
| 153 |
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
manual_btn = gr.Button("📌 Inserir Manualmente")
|
| 160 |
-
manual_status = gr.Textbox(interactive=False)
|
| 161 |
-
|
| 162 |
-
manual_btn.click(
|
| 163 |
-
add_location,
|
| 164 |
-
inputs=[device_id, device_name, latitude, longitude],
|
| 165 |
-
outputs=manual_status
|
| 166 |
-
)
|
| 167 |
|
| 168 |
with gr.Tab("Mapa em Tempo Real"):
|
| 169 |
map_html = gr.HTML(get_updated_map())
|
| 170 |
-
|
|
|
|
| 171 |
|
| 172 |
-
with gr.Tab("
|
| 173 |
gr.Dataframe(
|
| 174 |
lambda: pd.read_sql_query(
|
| 175 |
-
"SELECT device_name, latitude, longitude, timestamp FROM locations ORDER BY timestamp DESC",
|
| 176 |
sqlite3.connect('locations.db')
|
| 177 |
),
|
| 178 |
-
interactive=False
|
|
|
|
| 179 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 180 |
|
| 181 |
return demo
|
| 182 |
|
|
|
|
| 6 |
from folium import plugins
|
| 7 |
import webbrowser
|
| 8 |
import os
|
|
|
|
| 9 |
|
| 10 |
# Configuração do banco de dados
|
| 11 |
def init_db():
|
|
|
|
| 53 |
except Exception as e:
|
| 54 |
return f"❌ Erro: {str(e)}"
|
| 55 |
|
| 56 |
+
# Função para criar página HTML que captura a localização automaticamente
|
| 57 |
+
def create_auto_gps_page(device_id, device_name):
|
|
|
|
| 58 |
html_content = f"""
|
| 59 |
+
<!DOCTYPE html>
|
| 60 |
+
<html>
|
| 61 |
+
<head>
|
| 62 |
+
<title>Compartilhamento de Localização</title>
|
| 63 |
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 64 |
+
<style>
|
| 65 |
+
body {{ font-family: Arial, sans-serif; padding: 20px; text-align: center; }}
|
| 66 |
+
.status {{ font-size: 18px; margin: 20px 0; font-weight: bold; }}
|
| 67 |
+
.coords {{ margin: 15px 0; }}
|
| 68 |
+
</style>
|
| 69 |
+
</head>
|
| 70 |
+
<body>
|
| 71 |
+
<h1>Compartilhando Localização</h1>
|
| 72 |
+
<div id="status" class="status">Obtendo sua localização...</div>
|
| 73 |
+
<div id="coords" class="coords"></div>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
|
| 75 |
+
<script>
|
| 76 |
+
// Função para enviar a localização para o servidor Gradio
|
| 77 |
+
function sendToGradio(latitude, longitude, accuracy) {{
|
| 78 |
+
// Usando o esquema gradio:// para enviar os dados
|
| 79 |
+
window.location.href = `gradio://localhost:7860/?device_id={device_id}&device_name={device_name}&latitude=${{latitude}}&longitude=${{longitude}}&accuracy=${{accuracy}}`;
|
| 80 |
+
}}
|
| 81 |
+
|
| 82 |
+
// Tenta obter a localização automaticamente
|
| 83 |
+
function getLocation() {{
|
| 84 |
+
if (navigator.geolocation) {{
|
| 85 |
+
navigator.geolocation.watchPosition(
|
| 86 |
+
position => {{
|
| 87 |
+
const lat = position.coords.latitude;
|
| 88 |
+
const lng = position.coords.longitude;
|
| 89 |
+
const acc = position.coords.accuracy;
|
| 90 |
+
|
| 91 |
+
document.getElementById('status').textContent = "Localização obtida com sucesso!";
|
| 92 |
+
document.getElementById('coords').innerHTML =
|
| 93 |
+
`Latitude: ${lat.toFixed(6)}<br>Longitude: ${lng.toFixed(6)}<br>Precisão: ${Math.round(acc)} metros`;
|
| 94 |
+
|
| 95 |
+
// Envia para o Gradio
|
| 96 |
+
sendToGradio(lat, lng, acc);
|
| 97 |
+
}},
|
| 98 |
+
error => {{
|
| 99 |
+
document.getElementById('status').textContent = "Erro: " + error.message;
|
| 100 |
+
}},
|
| 101 |
+
{{
|
| 102 |
+
enableHighAccuracy: true,
|
| 103 |
+
maximumAge: 0,
|
| 104 |
+
timeout: 5000
|
| 105 |
+
}}
|
| 106 |
+
);
|
| 107 |
+
}} else {{
|
| 108 |
+
document.getElementById('status').textContent = "Geolocalização não suportada neste navegador.";
|
| 109 |
+
}}
|
| 110 |
+
}}
|
| 111 |
+
|
| 112 |
+
// Inicia a captura quando a página carrega
|
| 113 |
+
window.onload = getLocation;
|
| 114 |
+
</script>
|
| 115 |
+
</body>
|
| 116 |
+
</html>
|
| 117 |
+
"""
|
| 118 |
+
with open("gps_auto_capture.html", "w") as f:
|
| 119 |
f.write(html_content)
|
| 120 |
+
return os.path.abspath("gps_auto_capture.html")
|
| 121 |
+
|
| 122 |
+
# Função para iniciar a captura automática
|
| 123 |
+
def start_auto_gps(device_id, device_name):
|
| 124 |
+
page_path = create_auto_gps_page(device_id, device_name)
|
| 125 |
+
webbrowser.open(f"file://{page_path}")
|
| 126 |
+
return "🌍 Página de captura aberta! Permita o acesso à localização no navegador."
|
| 127 |
|
| 128 |
# Função para obter mapa atualizado
|
| 129 |
def get_updated_map():
|
|
|
|
| 135 |
FROM locations
|
| 136 |
WHERE timestamp = (SELECT MAX(timestamp) FROM locations l2
|
| 137 |
WHERE l2.device_id = locations.device_id)
|
| 138 |
+
ORDER BY timestamp DESC
|
| 139 |
''', conn)
|
| 140 |
conn.close()
|
| 141 |
|
|
|
|
| 149 |
for _, row in df.iterrows():
|
| 150 |
folium.Marker(
|
| 151 |
[row['latitude'], row['longitude']],
|
| 152 |
+
popup=f"""
|
| 153 |
+
<b>{row['device_name']}</b><br>
|
| 154 |
+
📍 {row['latitude']:.6f}, {row['longitude']:.6f}<br>
|
| 155 |
+
⏰ {row['timestamp']}<br>
|
| 156 |
+
🎯 Precisão: ±{row['accuracy']:.0f}m
|
| 157 |
+
""",
|
| 158 |
+
icon=folium.Icon(color='blue', icon='user', prefix='fa')
|
| 159 |
).add_to(m)
|
| 160 |
|
| 161 |
+
plugins.Fullscreen().add_to(m)
|
| 162 |
return m._repr_html_()
|
| 163 |
except Exception as e:
|
| 164 |
+
return f"<div style='color:red;padding:20px;'>Erro ao carregar mapa: {str(e)}</div>"
|
| 165 |
|
| 166 |
# Interface Gradio
|
| 167 |
def create_interface():
|
| 168 |
with gr.Blocks(title="📍 Monitor GPS Automático") as demo:
|
| 169 |
+
gr.Markdown("""
|
| 170 |
+
## 📍 Monitor de Localização em Tempo Real
|
| 171 |
+
**Sistema de rastreamento automático via GPS**
|
| 172 |
+
""")
|
| 173 |
|
| 174 |
with gr.Row():
|
| 175 |
+
device_id = gr.Textbox(label="ID do Dispositivo", value="celular_1")
|
| 176 |
+
device_name = gr.Textbox(label="Nome do Dispositivo", value="Meu Celular")
|
| 177 |
|
| 178 |
with gr.Row():
|
| 179 |
+
# Botão para iniciar captura automática
|
| 180 |
+
auto_gps_btn = gr.Button("📍 Iniciar Captura Automática", variant="primary")
|
| 181 |
+
gps_status = gr.Textbox(label="Status", interactive=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 182 |
|
| 183 |
+
auto_gps_btn.click(
|
| 184 |
+
start_auto_gps,
|
| 185 |
+
inputs=[device_id, device_name],
|
| 186 |
+
outputs=gps_status
|
| 187 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 188 |
|
| 189 |
with gr.Tab("Mapa em Tempo Real"):
|
| 190 |
map_html = gr.HTML(get_updated_map())
|
| 191 |
+
# Atualiza o mapa a cada 5 segundos
|
| 192 |
+
gr.Timer(5.0, get_updated_map, None, map_html)
|
| 193 |
|
| 194 |
+
with gr.Tab("Histórico de Localizações"):
|
| 195 |
gr.Dataframe(
|
| 196 |
lambda: pd.read_sql_query(
|
| 197 |
+
"SELECT device_name, latitude, longitude, timestamp, accuracy FROM locations ORDER BY timestamp DESC",
|
| 198 |
sqlite3.connect('locations.db')
|
| 199 |
),
|
| 200 |
+
interactive=False,
|
| 201 |
+
height=400
|
| 202 |
)
|
| 203 |
+
|
| 204 |
+
# Manipulador para receber dados da página web
|
| 205 |
+
@demo.load(inputs=None, outputs=None)
|
| 206 |
+
def handle_gps_data(request: gr.Request):
|
| 207 |
+
params = request.query_params
|
| 208 |
+
if 'latitude' in params and 'longitude' in params:
|
| 209 |
+
add_location(
|
| 210 |
+
params.get('device_id', 'unknown'),
|
| 211 |
+
params.get('device_name', 'Dispositivo Móvel'),
|
| 212 |
+
params['latitude'],
|
| 213 |
+
params['longitude'],
|
| 214 |
+
params.get('accuracy', 10)
|
| 215 |
+
)
|
| 216 |
|
| 217 |
return demo
|
| 218 |
|