feat: Implementado formato JSON personalizado
This commit is contained in:
@@ -2,6 +2,7 @@
|
|||||||
# pyright: basic
|
# pyright: basic
|
||||||
|
|
||||||
import os
|
import os
|
||||||
|
import sys
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
@@ -11,7 +12,7 @@ from utils import parser, crud, stats
|
|||||||
HEADER = """=== Terramotos ==="""
|
HEADER = """=== Terramotos ==="""
|
||||||
|
|
||||||
MENU ="""[1] Criar a base de dados
|
MENU ="""[1] Criar a base de dados
|
||||||
[2] Atualizar uma entrada
|
[] 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
|
||||||
@@ -58,7 +59,7 @@ def main():
|
|||||||
retInfo = None
|
retInfo = None
|
||||||
|
|
||||||
while isRunning:
|
while isRunning:
|
||||||
os.system("cls")
|
os.system("cls" if sys.platform == "windows" else "clear")
|
||||||
print(HEADER + "\n" + MENU)
|
print(HEADER + "\n" + MENU)
|
||||||
usrIn = input("Opção: ").lower()
|
usrIn = input("Opção: ").lower()
|
||||||
|
|
||||||
@@ -78,23 +79,24 @@ def main():
|
|||||||
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":
|
case "2":
|
||||||
if db is not None:
|
pass
|
||||||
crud.read_ids(db)
|
# if db is not None:
|
||||||
eid_choice = _get_usr_input("Escolhe o ID: ", int)
|
# 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!"
|
# if not _event_exists(db, eid_choice):
|
||||||
|
# retInfo = "ID do event não encontrado!"
|
||||||
else:
|
#
|
||||||
table = crud.get_table(db, eid_choice)
|
# else:
|
||||||
crud.show_table(table)
|
# table = crud.get_table(db, eid_choice)
|
||||||
row_choice = _get_usr_input("Escolhe a linha a atualizar: ", int)
|
# crud.show_table(table)
|
||||||
new_data = {}
|
# row_choice = _get_usr_input("Escolhe a linha a atualizar: ", int)
|
||||||
for col in crud.TABLE_READ_RET:
|
# new_data = {}
|
||||||
val = _get_usr_input(f"Novo valor para {col} (Enter para manter o valor atual): ")
|
# for col in crud.TABLE_READ_RET:
|
||||||
if val is not None:
|
# val = _get_usr_input(f"Novo valor para {col} (Enter para manter o valor atual): ")
|
||||||
new_data[col] = val
|
# if val is not None:
|
||||||
crud.update_table_row(db, row_choice, new_data)
|
# 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:
|
||||||
@@ -121,7 +123,7 @@ def main():
|
|||||||
retInfo = "ID do event não encontrado!"
|
retInfo = "ID do event não encontrado!"
|
||||||
|
|
||||||
else:
|
else:
|
||||||
os.system("cls")
|
os.system("cls" if sys.platform == "windows" else "clear")
|
||||||
table = crud.get_table(db, eid_choice)
|
table = crud.get_table(db, eid_choice)
|
||||||
_prettify_event(table)
|
_prettify_event(table)
|
||||||
crud.show_table(table)
|
crud.show_table(table)
|
||||||
@@ -146,6 +148,7 @@ def main():
|
|||||||
retInfo = "ID do event não encontrado!"
|
retInfo = "ID do event não encontrado!"
|
||||||
|
|
||||||
else:
|
else:
|
||||||
|
os.system("cls" if sys.platform == "windows" else "clear")
|
||||||
table = crud.get_table(db, choice)
|
table = crud.get_table(db, choice)
|
||||||
_prettify_event(table)
|
_prettify_event(table)
|
||||||
crud.show_table(table)
|
crud.show_table(table)
|
||||||
@@ -187,7 +190,7 @@ def main():
|
|||||||
retInfo = "ID do event não encontrado!"
|
retInfo = "ID do event não encontrado!"
|
||||||
|
|
||||||
else:
|
else:
|
||||||
os.system("cls")
|
os.system("cls" if sys.platform == "windows" else "clear")
|
||||||
table = crud.get_table(db, eid_choice)
|
table = crud.get_table(db, eid_choice)
|
||||||
_prettify_event(table)
|
_prettify_event(table)
|
||||||
crud.show_table(table)
|
crud.show_table(table)
|
||||||
|
|||||||
@@ -159,6 +159,7 @@ def _parse_type_3(data: list[str]):
|
|||||||
for line in data:
|
for line in data:
|
||||||
if line.startswith(" SENTIDO") or line.startswith(" REGIAO"):
|
if line.startswith(" SENTIDO") or line.startswith(" REGIAO"):
|
||||||
c, v = line[:-2].strip().split(": ", maxsplit=1)
|
c, v = line[:-2].strip().split(": ", maxsplit=1)
|
||||||
|
v = v.split(",")[0]
|
||||||
comments[c.capitalize()] = v
|
comments[c.capitalize()] = v
|
||||||
|
|
||||||
return comments
|
return comments
|
||||||
@@ -173,8 +174,8 @@ 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)])
|
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"}, inplace=True)
|
dados.rename(columns={'STAT': "Estacao", 'SP': "Componente" , 'PHASW': "Tipo Onda", 'HR': "Hora", 'MM': "Min", 'SECON': "Seg", 'AMPL': "Amplitude", " DIST": "Dist. Epi"}, inplace=True)
|
||||||
return dados
|
return dados
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
# pyright: basic
|
# pyright: basic
|
||||||
|
|
||||||
import os
|
import os
|
||||||
|
import sys
|
||||||
|
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
import numpy as np
|
import numpy as np
|
||||||
@@ -29,7 +30,7 @@ CHOICE = {"1": "Magnitudes", "2": "Distancia","3": "Prof"}
|
|||||||
|
|
||||||
|
|
||||||
def filter_submenu(type: str):
|
def filter_submenu(type: str):
|
||||||
os.system("cls")
|
os.system("cls" if sys.platform == "windows" else "clear")
|
||||||
print(f"{STAT_HEADER}\n = {type} = ")
|
print(f"{STAT_HEADER}\n = {type} = ")
|
||||||
print(FILTER_CHOICES)
|
print(FILTER_CHOICES)
|
||||||
|
|
||||||
@@ -45,7 +46,7 @@ def filter_submenu(type: str):
|
|||||||
def stat_menu(df: pd.DataFrame):
|
def stat_menu(df: pd.DataFrame):
|
||||||
inStats = True
|
inStats = True
|
||||||
while inStats:
|
while inStats:
|
||||||
os.system("cls")
|
os.system("cls" if sys.platform == "windows" else "clear")
|
||||||
print(STAT_HEADER + "\n" + STAT_MENU)
|
print(STAT_HEADER + "\n" + STAT_MENU)
|
||||||
usrIn = input("Opção: ").lower()
|
usrIn = input("Opção: ").lower()
|
||||||
|
|
||||||
|
|||||||
76
utils/utils.py
Normal file
76
utils/utils.py
Normal file
@@ -0,0 +1,76 @@
|
|||||||
|
#! /usr/bin/env python
|
||||||
|
# pyright: basic
|
||||||
|
|
||||||
|
from datetime import time
|
||||||
|
import json
|
||||||
|
from math import modf
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from numpy import nan
|
||||||
|
import pandas as pd
|
||||||
|
|
||||||
|
|
||||||
|
def save_as_json(info: dict[str, Any]) -> bool:
|
||||||
|
with open("test.json", "w") as fp:
|
||||||
|
json.dump(info, fp)
|
||||||
|
|
||||||
|
return True
|
||||||
|
|
||||||
|
# TODO: passar os nomes das colunas, para não haver problemas no futuro, caso se altere os nomes da dataframe
|
||||||
|
def create_dict_struct(df: pd.DataFrame, event_cols, station_cols) -> dict[str, Any]:
|
||||||
|
# get all events by their id
|
||||||
|
uniqueIds = df["ID"].unique()
|
||||||
|
|
||||||
|
allEvents = {}
|
||||||
|
|
||||||
|
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)].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_stations_info_1(info: pd.DataFrame) -> dict[str, Any]:
|
||||||
|
stationsDict = {}
|
||||||
|
for idx in range(len(info)):
|
||||||
|
aux = info.iloc[idx]
|
||||||
|
|
||||||
|
micro, sec = tuple(map(int, modf(aux["Seg"])))
|
||||||
|
hms = time(hour=aux["Hora"],minute=aux["Min"], second=sec, microsecond=micro).strftime("%H:%M:%S.%f")
|
||||||
|
station = {"Componente": aux["Componente"], "Hora": hms, "Distancia": float(aux["DIS"])}
|
||||||
|
|
||||||
|
if type(aux["Tipo Onda"]) != float:
|
||||||
|
station.update({"Tipo Onda": aux["Tipo Onda"]})
|
||||||
|
if aux["Tipo Onda"] == "IAML":
|
||||||
|
station.update({"Amplitude": float(aux["Amplitude"])})
|
||||||
|
|
||||||
|
|
||||||
|
if aux["Estacao"] not in stationsDict.keys():
|
||||||
|
stationsDict[aux["Estacao"]] = [station]
|
||||||
|
else:
|
||||||
|
stationsDict[aux["Estacao"]].append(station)
|
||||||
|
return {"Estacoes": stationsDict}
|
||||||
|
|
||||||
|
|
||||||
|
def create_mag_info(magnitudes):
|
||||||
|
mags = {}
|
||||||
|
for value in magnitudes:
|
||||||
|
mags[value["Tipo"]] = value["Magnitude"]
|
||||||
|
return mags
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
import parser
|
||||||
|
|
||||||
|
df = parser.parse("dados.txt")
|
||||||
|
a = create_dict_struct(df, None, None)
|
||||||
|
save_as_json(a)
|
||||||
Reference in New Issue
Block a user