Update app.py
Browse files
app.py
CHANGED
|
@@ -53,7 +53,7 @@ def add_location(device_id, device_name, latitude, longitude, accuracy=10, batte
|
|
| 53 |
except Exception as e:
|
| 54 |
return f"❌ Erro: {str(e)}"
|
| 55 |
|
| 56 |
-
# Função para criar página HTML
|
| 57 |
def create_auto_gps_page(device_id, device_name):
|
| 58 |
html_content = f"""
|
| 59 |
<!DOCTYPE html>
|
|
@@ -64,22 +64,17 @@ def create_auto_gps_page(device_id, device_name):
|
|
| 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(
|
|
@@ -88,28 +83,19 @@ def create_auto_gps_page(device_id, device_name):
|
|
| 88 |
const lng = position.coords.longitude;
|
| 89 |
const acc = position.coords.accuracy;
|
| 90 |
|
| 91 |
-
document.getElementById('status').textContent = "Localização
|
| 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
|
| 109 |
}}
|
| 110 |
}}
|
| 111 |
|
| 112 |
-
// Inicia a captura quando a página carrega
|
| 113 |
window.onload = getLocation;
|
| 114 |
</script>
|
| 115 |
</body>
|
|
@@ -119,23 +105,20 @@ def create_auto_gps_page(device_id, device_name):
|
|
| 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 "🌍
|
| 127 |
|
| 128 |
# Função para obter mapa atualizado
|
| 129 |
def get_updated_map():
|
| 130 |
try:
|
| 131 |
conn = sqlite3.connect('locations.db', check_same_thread=False)
|
| 132 |
df = pd.read_sql_query('''
|
| 133 |
-
SELECT
|
| 134 |
-
timestamp, accuracy, battery_level
|
| 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,59 +132,46 @@ def get_updated_map():
|
|
| 149 |
for _, row in df.iterrows():
|
| 150 |
folium.Marker(
|
| 151 |
[row['latitude'], row['longitude']],
|
| 152 |
-
popup=f""
|
| 153 |
-
|
| 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
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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("
|
| 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
|
|
|
|
| 53 |
except Exception as e:
|
| 54 |
return f"❌ Erro: {str(e)}"
|
| 55 |
|
| 56 |
+
# Função para criar página HTML de captura automática
|
| 57 |
def create_auto_gps_page(device_id, device_name):
|
| 58 |
html_content = f"""
|
| 59 |
<!DOCTYPE html>
|
|
|
|
| 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 |
</style>
|
| 68 |
</head>
|
| 69 |
<body>
|
| 70 |
<h1>Compartilhando Localização</h1>
|
| 71 |
<div id="status" class="status">Obtendo sua localização...</div>
|
|
|
|
| 72 |
|
| 73 |
<script>
|
|
|
|
| 74 |
function sendToGradio(latitude, longitude, accuracy) {{
|
|
|
|
| 75 |
window.location.href = `gradio://localhost:7860/?device_id={device_id}&device_name={device_name}&latitude=${{latitude}}&longitude=${{longitude}}&accuracy=${{accuracy}}`;
|
| 76 |
}}
|
| 77 |
|
|
|
|
| 78 |
function getLocation() {{
|
| 79 |
if (navigator.geolocation) {{
|
| 80 |
navigator.geolocation.watchPosition(
|
|
|
|
| 83 |
const lng = position.coords.longitude;
|
| 84 |
const acc = position.coords.accuracy;
|
| 85 |
|
| 86 |
+
document.getElementById('status').textContent = "Localização compartilhada com sucesso!";
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
sendToGradio(lat, lng, acc);
|
| 88 |
}},
|
| 89 |
error => {{
|
| 90 |
document.getElementById('status').textContent = "Erro: " + error.message;
|
| 91 |
}},
|
| 92 |
+
{{ enableHighAccuracy: true }}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 93 |
);
|
| 94 |
}} else {{
|
| 95 |
+
document.getElementById('status').textContent = "Geolocalização não suportada.";
|
| 96 |
}}
|
| 97 |
}}
|
| 98 |
|
|
|
|
| 99 |
window.onload = getLocation;
|
| 100 |
</script>
|
| 101 |
</body>
|
|
|
|
| 105 |
f.write(html_content)
|
| 106 |
return os.path.abspath("gps_auto_capture.html")
|
| 107 |
|
|
|
|
| 108 |
def start_auto_gps(device_id, device_name):
|
| 109 |
page_path = create_auto_gps_page(device_id, device_name)
|
| 110 |
webbrowser.open(f"file://{page_path}")
|
| 111 |
+
return "🌍 Captura automática iniciada! Permita o acesso à localização."
|
| 112 |
|
| 113 |
# Função para obter mapa atualizado
|
| 114 |
def get_updated_map():
|
| 115 |
try:
|
| 116 |
conn = sqlite3.connect('locations.db', check_same_thread=False)
|
| 117 |
df = pd.read_sql_query('''
|
| 118 |
+
SELECT device_name, latitude, longitude, timestamp, accuracy
|
|
|
|
| 119 |
FROM locations
|
|
|
|
|
|
|
| 120 |
ORDER BY timestamp DESC
|
| 121 |
+
LIMIT 50
|
| 122 |
''', conn)
|
| 123 |
conn.close()
|
| 124 |
|
|
|
|
| 132 |
for _, row in df.iterrows():
|
| 133 |
folium.Marker(
|
| 134 |
[row['latitude'], row['longitude']],
|
| 135 |
+
popup=f"{row['device_name']}<br>{row['timestamp']}",
|
| 136 |
+
icon=folium.Icon(color='blue')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 137 |
).add_to(m)
|
| 138 |
|
| 139 |
plugins.Fullscreen().add_to(m)
|
| 140 |
return m._repr_html_()
|
| 141 |
except Exception as e:
|
| 142 |
+
return f"<div style='color:red;padding:20px;'>Erro: {str(e)}</div>"
|
| 143 |
|
| 144 |
+
# Interface Gradio simplificada
|
| 145 |
def create_interface():
|
| 146 |
with gr.Blocks(title="📍 Monitor GPS Automático") as demo:
|
| 147 |
+
gr.Markdown("## 📍 Monitor de Localização em Tempo Real")
|
|
|
|
|
|
|
|
|
|
| 148 |
|
| 149 |
with gr.Row():
|
| 150 |
device_id = gr.Textbox(label="ID do Dispositivo", value="celular_1")
|
| 151 |
device_name = gr.Textbox(label="Nome do Dispositivo", value="Meu Celular")
|
|
|
|
|
|
|
|
|
|
| 152 |
auto_gps_btn = gr.Button("📍 Iniciar Captura Automática", variant="primary")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 153 |
|
| 154 |
+
gps_status = gr.Textbox(label="Status", interactive=False)
|
| 155 |
+
|
| 156 |
+
auto_gps_btn.click(
|
| 157 |
+
start_auto_gps,
|
| 158 |
+
inputs=[device_id, device_name],
|
| 159 |
+
outputs=gps_status
|
| 160 |
+
)
|
| 161 |
+
|
| 162 |
+
with gr.Tab("Mapa"):
|
| 163 |
map_html = gr.HTML(get_updated_map())
|
|
|
|
| 164 |
gr.Timer(5.0, get_updated_map, None, map_html)
|
| 165 |
|
| 166 |
+
with gr.Tab("Dados"):
|
| 167 |
gr.Dataframe(
|
| 168 |
lambda: pd.read_sql_query(
|
| 169 |
"SELECT device_name, latitude, longitude, timestamp, accuracy FROM locations ORDER BY timestamp DESC",
|
| 170 |
sqlite3.connect('locations.db')
|
| 171 |
),
|
| 172 |
+
interactive=False
|
|
|
|
| 173 |
)
|
| 174 |
|
|
|
|
| 175 |
@demo.load(inputs=None, outputs=None)
|
| 176 |
def handle_gps_data(request: gr.Request):
|
| 177 |
params = request.query_params
|