-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenerate_index.py
114 lines (93 loc) · 3.86 KB
/
generate_index.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
import os
import json
import requests
from datetime import datetime
from dotenv import load_dotenv
# Carrega as variáveis de ambiente do arquivo .env
load_dotenv()
# Configuração dos diretórios e URLs
CONTENTS_DIR = "contents"
INDEX_FILE = "index.json"
BASE_URL = "https://zenitheesc.github.io/launches-data/contents/"
OPENCAGE_API_URL = "https://api.opencagedata.com/geocode/v1/json"
OPENCAGE_API_KEY = os.getenv("API_KEY") # Carrega a chave da API do .env
HEADERS = {"User-Agent": "launches-data-bot"}
def get_city(lat, lon):
"""Obtém a cidade a partir das coordenadas usando a API do OpenCage."""
if lat is None or lon is None:
return "Desconhecido"
try:
params = {
"q": f"{lat},{lon}",
"key": OPENCAGE_API_KEY,
"language": "pt" # Define o idioma da resposta
}
response = requests.get(OPENCAGE_API_URL, params=params, headers=HEADERS)
response.raise_for_status()
results = response.json().get("results", [])
if results:
components = results[0].get("components", {})
# Procura por cidade, vila ou município
for field in ["city", "town", "village", "municipality"]:
if field in components:
return components[field]
return "Desconhecido"
except requests.RequestException as e:
print(f"Erro ao buscar cidade para {lat}, {lon}: {e}")
return "Desconhecido"
def process_json(filepath):
"""Lê um arquivo JSON e retorna informações relevantes do lançamento."""
try:
with open(filepath, "r", encoding="utf-8") as f:
data = json.load(f)
if not data:
return None
first, last = data[0], data[-1]
max_altitude = max((entry.get("alt", 0) for entry in data), default=0)
return {
"launch_city": get_city(first.get("lat"), first.get("lon")),
"landing_city": get_city(last.get("lat"), last.get("lon")),
"max_altitude": max_altitude,
"launch_datetime": first.get("datetime", "Desconhecido")
}
except (json.JSONDecodeError, OSError) as e:
print(f"Erro ao processar {filepath}: {e}")
return None
def load_existing_index():
"""Carrega o index.json existente."""
if os.path.exists(INDEX_FILE):
try:
with open(INDEX_FILE, "r", encoding="utf-8") as f:
return json.load(f)
except (json.JSONDecodeError, OSError) as e:
print(f"Erro ao carregar {INDEX_FILE}: {e}")
return []
def generate_index():
"""Gera ou atualiza o index.json com novos arquivos JSON processados."""
if not os.path.isdir(CONTENTS_DIR):
print(f"Diretório '{CONTENTS_DIR}' não encontrado.")
return
existing_index = load_existing_index()
processed_files = {entry["name"] for entry in existing_index}
new_entries = []
for file in filter(lambda f: f.endswith(".json") and f not in processed_files, os.listdir(CONTENTS_DIR)):
print(f"Processando: {file}")
metadata = process_json(os.path.join(CONTENTS_DIR, file))
if metadata:
new_entries.append({
"name": file,
"download_url": BASE_URL + file,
**metadata
})
if new_entries:
try:
new_entries.sort(key=lambda x: datetime.strptime(x["launch_datetime"], "%Y-%m-%dT%H:%M:%S.%fZ"), reverse=True)
except ValueError:
print("Erro ao ordenar os lançamentos por data.")
with open(INDEX_FILE, "w", encoding="utf-8") as f:
json.dump(existing_index + new_entries, f, indent=4, ensure_ascii=False)
print(f"Index atualizado com {len(new_entries)} novos arquivos.")
else:
print("Nenhum novo arquivo encontrado. Index.json não foi modificado.")
if __name__ == "__main__":
generate_index()