diff --git a/earthquakes.py b/earthquakes.py index c93b18e..5618968 100644 --- a/earthquakes.py +++ b/earthquakes.py @@ -1,18 +1,21 @@ #! /usr/bin/env python # pyright: basic +import json import os import sys from datetime import datetime import pandas as pd -from utils import parser, crud, stats +from utils import parser, crud, stats, utils 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 -[] Atualizar uma entrada (Removido) [3] Apagar um evento [4] Apagar uma entrada de um evento [5] Visualizar um evento @@ -24,20 +27,13 @@ MENU ="""[1] Criar a base de dados [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: + _retValues = utils.create_dict_struct(df, EVENT_COLS, None) + with open(fname , "w") as fp: try: - df.to_json(fp, indent=4) + json.dump(_retValues, fp) except: return False return True @@ -56,12 +52,6 @@ def main(): isRunning = True db = None - - stdin = get_from_stdin() - if stdin is not None: - db = parser.parse(stdin) - - retInfo = None while isRunning: @@ -84,26 +74,6 @@ def main(): else: 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": if db is not None: crud.read_ids(db) @@ -135,7 +105,6 @@ def main(): crud.show_table(table) 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) new_table = crud.get_table(db, eid_choice) @@ -223,14 +192,6 @@ def main(): 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: currFiles = os.listdir(os.getcwd()) if name in currFiles: diff --git a/utils/parser.py b/utils/parser.py index 43ac6a3..1e80b15 100644 --- a/utils/parser.py +++ b/utils/parser.py @@ -101,8 +101,7 @@ def _parse_preamble(hLines: list[str]): case "6": aux[6].append(line) case "E": - pass - # aux["E"].append(line) + aux["E"].append(line) case "I": aux["I"].append(line) case "F": @@ -136,7 +135,7 @@ def _parse_type_1(data: list[str]): depth = float(aux[38:43]) 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: 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]): 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.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 diff --git a/utils/utils.py b/utils/utils.py index fd89b06..2bca49b 100644 --- a/utils/utils.py +++ b/utils/utils.py @@ -6,7 +6,6 @@ import json from math import modf from typing import Any -from numpy import nan 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: filteredDf = df.loc[df["ID"] == id] 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)) return allEvents -def create_event_info(info: pd.DataFrame) -> dict[str, Any]: - return {"DataHora": info.iloc[0]["Data"], "Lat": float(info.iloc[0]["Lat"]), "Long": float(info.iloc[0]["Long"]), - "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"], - "Sentido": info.iloc[0]["Sentido"]} +def create_event_info(info: pd.DataFrame, cols) -> dict[str, Any]: + informacoes = dict() + + for v in cols: + 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]: