novo json

This commit is contained in:
2025-11-15 16:05:33 -01:00
parent 047f5e25ac
commit afef4c4d5c
3 changed files with 24 additions and 58 deletions

View File

@@ -1,18 +1,21 @@
#! /usr/bin/env python #! /usr/bin/env python
# pyright: basic # pyright: basic
import json
import os import os
import sys import sys
from datetime import datetime from datetime import datetime
import pandas as pd import pandas as pd
from utils import parser, crud, stats from utils import parser, crud, stats, utils
HEADER = """=== Terramotos ===""" HEADER = """=== Terramotos ==="""
EVENT_COLS = ["Data", "Latitude", "Longitude", "Profundidade", "Tipo Evento", "Gap", "Magnitudes", "Regiao", "Sentido"]
STATION_COLS = ["Estacao", "Hora", "Min", "Seg", "Componente", "Distancia Epicentro", "Tipo Onda"]
MENU ="""[1] Criar a base de dados MENU ="""[1] Criar a base de dados
[] Atualizar uma entrada (Removido)
[3] Apagar um evento [3] Apagar um evento
[4] Apagar uma entrada de um evento [4] Apagar uma entrada de um evento
[5] Visualizar um evento [5] Visualizar um evento
@@ -24,20 +27,13 @@ MENU ="""[1] Criar a base de dados
[Q] Sair [Q] Sair
""" """
def guardar_df(df: pd.DataFrame, fname: str) -> bool:
with open(fname, "w") as fp:
fname = f"{fname}.txt"
try:
fp.write(df.to_string())
except ValueError:
return False
return True
def guardar_json(df: pd.DataFrame, fname: str) -> bool: def guardar_json(df: pd.DataFrame, fname: str) -> bool:
_retValues = utils.create_dict_struct(df, EVENT_COLS, None)
with open(fname , "w") as fp: with open(fname , "w") as fp:
try: try:
df.to_json(fp, indent=4) json.dump(_retValues, fp)
except: except:
return False return False
return True return True
@@ -56,12 +52,6 @@ def main():
isRunning = True isRunning = True
db = None db = None
stdin = get_from_stdin()
if stdin is not None:
db = parser.parse(stdin)
retInfo = None retInfo = None
while isRunning: while isRunning:
@@ -84,26 +74,6 @@ def main():
else: else:
input("Base de dados não encontrada. Por favor tenta de novo.") input("Base de dados não encontrada. Por favor tenta de novo.")
case "2":
pass
# if db is not None:
# crud.read_ids(db)
# eid_choice = _get_usr_input("Escolhe o ID: ", int)
#
# if not _event_exists(db, eid_choice):
# retInfo = "ID do event não encontrado!"
#
# else:
# table = crud.get_table(db, eid_choice)
# crud.show_table(table)
# row_choice = _get_usr_input("Escolhe a linha a atualizar: ", int)
# new_data = {}
# for col in crud.TABLE_READ_RET:
# val = _get_usr_input(f"Novo valor para {col} (Enter para manter o valor atual): ")
# if val is not None:
# new_data[col] = val
# crud.update_table_row(db, row_choice, new_data)
case "3": case "3":
if db is not None: if db is not None:
crud.read_ids(db) crud.read_ids(db)
@@ -135,7 +105,6 @@ def main():
crud.show_table(table) crud.show_table(table)
row_choice = _get_usr_input("Escolhe a linha a apagar:", int) row_choice = _get_usr_input("Escolhe a linha a apagar:", int)
# TODO: balizar a escolha para apenas as linhas do evento em questao
db, msg = crud.delete_table_row(db, eid_choice, row_choice) db, msg = crud.delete_table_row(db, eid_choice, row_choice)
new_table = crud.get_table(db, eid_choice) new_table = crud.get_table(db, eid_choice)
@@ -223,14 +192,6 @@ def main():
input("Clique Enter para continuar") input("Clique Enter para continuar")
def get_from_stdin() -> list[str] | None:
if sys.stdin.isatty():
return sys.stdin.readlines()
return None
def _file_exists(name: str) -> bool: def _file_exists(name: str) -> bool:
currFiles = os.listdir(os.getcwd()) currFiles = os.listdir(os.getcwd())
if name in currFiles: if name in currFiles:

View File

@@ -101,8 +101,7 @@ def _parse_preamble(hLines: list[str]):
case "6": case "6":
aux[6].append(line) aux[6].append(line)
case "E": case "E":
pass aux["E"].append(line)
# aux["E"].append(line)
case "I": case "I":
aux["I"].append(line) aux["I"].append(line)
case "F": case "F":
@@ -136,7 +135,7 @@ def _parse_type_1(data: list[str]):
depth = float(aux[38:43]) depth = float(aux[38:43])
no_stat = int(aux[48:51]) no_stat = int(aux[48:51])
hypo = {"Data": dt.isoformat(), "Distancia": dist_ind, "Tipo Ev": ev_type, "Lat": lat, "Long": long, "Prof": depth, "Estacoes": no_stat, "Magnitudes": list()} hypo = {"Data": dt.isoformat(), "Distancia": dist_ind, "Tipo Evento": ev_type, "Latitude": lat, "Longitude": long, "Profundidade": depth, "Estacoes": no_stat, "Magnitudes": list()}
for l in data: for l in data:
hypo["Magnitudes"] = hypo["Magnitudes"] + _parse_mag(l) hypo["Magnitudes"] = hypo["Magnitudes"] + _parse_mag(l)
@@ -175,7 +174,7 @@ def _parse_type_6(data: list[str]):
def _parse_type_7(data: list[str]): def _parse_type_7(data: list[str]):
aux = io.StringIO("\n".join(data)) aux = io.StringIO("\n".join(data))
dados = pd.read_fwf(aux, colspecs=[(1,5), (6,8),(10,15), (18,20), (20,22), (23,28), (34,38), (71,75)]) dados = pd.read_fwf(aux, colspecs=[(1,5), (6,8),(10,15), (18,20), (20,22), (23,28), (34,38), (71,75)])
dados.rename(columns={'STAT': "Estacao", 'SP': "Componente" , 'PHASW': "Tipo Onda", 'HR': "Hora", 'MM': "Min", 'SECON': "Seg", 'AMPL': "Amplitude", " DIST": "Dist. Epi"}, inplace=True) dados.rename(columns={'STAT': "Estacao", 'SP': "Componente" , 'PHASW': "Tipo Onda", 'HR': "Hora", 'MM': "Min", 'SECON': "Seg", 'AMPL': "Amplitude", " DIST": "Distancia Epicentro"}, inplace=True)
return dados return dados

View File

@@ -6,7 +6,6 @@ import json
from math import modf from math import modf
from typing import Any from typing import Any
from numpy import nan
import pandas as pd import pandas as pd
@@ -26,17 +25,24 @@ def create_dict_struct(df: pd.DataFrame, event_cols, station_cols) -> dict[str,
for id in uniqueIds: for id in uniqueIds:
filteredDf = df.loc[df["ID"] == id] filteredDf = df.loc[df["ID"] == id]
first_row = filteredDf.head(1) first_row = filteredDf.head(1)
allEvents[int(id)] = create_event_info(first_row) allEvents[int(id)] = create_event_info(first_row, event_cols)
allEvents[int(id)].update(create_stations_info_1(filteredDf)) allEvents[int(id)].update(create_stations_info_1(filteredDf))
return allEvents return allEvents
def create_event_info(info: pd.DataFrame) -> dict[str, Any]: def create_event_info(info: pd.DataFrame, cols) -> dict[str, Any]:
return {"DataHora": info.iloc[0]["Data"], "Lat": float(info.iloc[0]["Lat"]), "Long": float(info.iloc[0]["Long"]), informacoes = dict()
"Profundidade": float(info.iloc[0]["Prof"]), "Tipo Evento": info.iloc[0]["Tipo Ev"],
"Magnitude": create_mag_info(info.iloc[0]["Magnitudes"]), "Regiao": info.iloc[0]["Regiao"], for v in cols:
"Sentido": info.iloc[0]["Sentido"]} if v == "Magnitudes":
informacoes[v] = create_mag_info(info.iloc[0][v])
elif v in {"Latitude", "Longitude", "Profundidade", "Gap"}:
informacoes[v] = float(info.iloc[0][v])
else:
informacoes[v] = info.iloc[0][v]
return informacoes
def create_stations_info_1(info: pd.DataFrame) -> dict[str, Any]: def create_stations_info_1(info: pd.DataFrame) -> dict[str, Any]: