-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtraceability.py
More file actions
278 lines (219 loc) · 10.9 KB
/
Copy pathtraceability.py
File metadata and controls
278 lines (219 loc) · 10.9 KB
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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
"""
Módulo de Rastreabilidade para Ocean PDF Scraper
Cria documentação automática de cada pedido de download
"""
import os
import json
from datetime import datetime
from pathlib import Path
from typing import List, Dict, Any, Optional
import shutil
class TraceabilityManager:
"""Gerenciador de rastreabilidade para downloads de livros"""
def __init__(self, base_dir: str = "/app/_download/verificados"):
self.base_dir = Path(base_dir)
self.current_session_id = None
self.current_session_dir = None
self.session_data = {
"request_info": {},
"execution_steps": [],
"results": {},
"lessons_learned": [],
"commands_executed": []
}
def create_session(self, request_info: Dict[str, Any]) -> str:
"""Criar nova sessão de rastreabilidade"""
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
self.current_session_id = f"pedido_{timestamp}"
self.current_session_dir = self.base_dir / self.current_session_id
# Criar diretório da sessão
self.current_session_dir.mkdir(exist_ok=True)
# Inicializar dados da sessão
self.session_data = {
"request_info": request_info,
"execution_steps": [],
"results": {
"total_requested": 0,
"successful_downloads": 0,
"failed_downloads": 0,
"total_size_mb": 0,
"execution_time_seconds": 0,
"files_downloaded": []
},
"lessons_learned": [],
"commands_executed": [],
"start_time": datetime.now().isoformat(),
"end_time": None
}
return self.current_session_id
def add_execution_step(self, step_type: str, description: str, details: Dict[str, Any] = None):
"""Adicionar etapa de execução"""
step = {
"timestamp": datetime.now().isoformat(),
"type": step_type,
"description": description,
"details": details or {}
}
self.session_data["execution_steps"].append(step)
def add_command(self, command: str, result: str = None):
"""Adicionar comando executado"""
cmd_entry = {
"timestamp": datetime.now().isoformat(),
"command": command,
"result": result
}
self.session_data["commands_executed"].append(cmd_entry)
def add_download_result(self, book_title: str, success: bool, file_info: Dict[str, Any] = None):
"""Adicionar resultado de download"""
if success:
self.session_data["results"]["successful_downloads"] += 1
if file_info:
self.session_data["results"]["files_downloaded"].append({
"title": book_title,
"filename": file_info.get("filename", ""),
"size_mb": file_info.get("size_mb", 0),
"download_time": file_info.get("download_time", 0)
})
self.session_data["results"]["total_size_mb"] += file_info.get("size_mb", 0)
else:
self.session_data["results"]["failed_downloads"] += 1
def add_lesson_learned(self, lesson: str, category: str = "general"):
"""Adicionar lição aprendida"""
lesson_entry = {
"timestamp": datetime.now().isoformat(),
"category": category,
"lesson": lesson
}
self.session_data["lessons_learned"].append(lesson_entry)
def move_files_to_session_dir(self, files: List[str]):
"""Mover arquivos baixados para o diretório da sessão"""
moved_files = []
for file_path in files:
if os.path.exists(file_path):
filename = os.path.basename(file_path)
destination = self.current_session_dir / filename
shutil.move(file_path, destination)
moved_files.append(str(destination))
return moved_files
def generate_readme(self) -> str:
"""Gerar README.md com toda a documentação"""
# Calcular estatísticas
total_requested = self.session_data["results"]["total_requested"]
successful = self.session_data["results"]["successful_downloads"]
failed = self.session_data["results"]["failed_downloads"]
success_rate = (successful / total_requested * 100) if total_requested > 0 else 0
# Tempo de execução
start_time = datetime.fromisoformat(self.session_data["start_time"])
end_time = datetime.now()
execution_time = (end_time - start_time).total_seconds()
self.session_data["results"]["execution_time_seconds"] = execution_time
readme_content = f"""# 📚 RASTREABILIDADE DE DOWNLOAD DE LIVROS
**Data/Hora:** {datetime.now().strftime("%d de %B de %Y - %H:%M:%S")}
**ID do Pedido:** {self.current_session_id}
**Status:** {'✅ CONCLUÍDO COM SUCESSO' if failed == 0 else '⚠️ CONCLUÍDO COM ALGUNS ERROS'}
## 🎯 **O QUE FOI SOLICITADO**
{self._format_request_info()}
## 🔧 **O QUE FOI EXECUTADO**
{self._format_execution_steps()}
## 📊 **RESULTADOS OBTIDOS**
### **✅ RESUMO FINAL:**
- **📚 Total de Livros Solicitados:** {total_requested}
- **✅ Downloads Bem-Sucedidos:** {successful} ({success_rate:.1f}%)
- **❌ Downloads Falhados:** {failed}
- **📥 Total de Arquivos:** {len(self.session_data['results']['files_downloaded'])}
- **📏 Tamanho Total:** {self.session_data['results']['total_size_mb']:.2f} MB
- **⏱️ Tempo Total de Execução:** {execution_time:.2f} segundos
### **📁 ARQUIVOS BAIXADOS:**
{self._format_downloaded_files()}
## 🔍 **LIÇÕES APRENDIDAS**
{self._format_lessons_learned()}
## 📋 **COMANDOS EXECUTADOS**
{self._format_commands()}
## 🎯 **STATUS FINAL**
{'**✅ MISSÃO CUMPRIDA COM SUCESSO TOTAL!**' if failed == 0 else '**⚠️ MISSÃO CONCLUÍDA COM ALGUNS ERROS**'}
{'Todos os livros solicitados foram baixados com sucesso.' if failed == 0 else f'{failed} livro(s) falharam no download.'} O processo foi documentado completamente e as lições aprendidas foram incorporadas ao protocolo.
---
**📅 Documentado em:** {datetime.now().strftime("%d de %B de %Y - %H:%M:%S")}
**🤖 Sistema:** Ocean PDF Scraper MCP Server v2.0
**📁 Localização:** `_download/verificados/{self.current_session_id}/`
"""
return readme_content
def _format_request_info(self) -> str:
"""Formatar informações da solicitação"""
request_info = self.session_data["request_info"]
if "books" in request_info:
books_list = "\n".join([f"{i+1}. **{book['title']}** – {book.get('author', 'Autor não especificado')}"
for i, book in enumerate(request_info["books"])])
return f"O usuário solicitou o download de **{len(request_info['books'])} livros específicos**:\n\n{books_list}"
elif "keyword" in request_info:
return f"O usuário solicitou o download de livros sobre: **{request_info['keyword']}**"
else:
return "Solicitação de download de livros"
def _format_execution_steps(self) -> str:
"""Formatar etapas de execução"""
steps_text = ""
for i, step in enumerate(self.session_data["execution_steps"], 1):
steps_text += f"### **ETAPA {i}: {step['type'].title()}**\n"
steps_text += f"- **Descrição:** {step['description']}\n"
steps_text += f"- **Timestamp:** {step['timestamp']}\n"
if step.get("details"):
for key, value in step["details"].items():
steps_text += f"- **{key.title()}:** {value}\n"
steps_text += "\n"
return steps_text
def _format_downloaded_files(self) -> str:
"""Formatar lista de arquivos baixados"""
if not self.session_data["results"]["files_downloaded"]:
return "Nenhum arquivo baixado com sucesso."
files_text = ""
for i, file_info in enumerate(self.session_data["results"]["files_downloaded"], 1):
files_text += f"{i}. **{file_info['filename']}** ({file_info['size_mb']:.2f} MB)\n"
return files_text
def _format_lessons_learned(self) -> str:
"""Formatar lições aprendidas"""
if not self.session_data["lessons_learned"]:
return "Nenhuma lição específica registrada nesta sessão."
lessons_text = ""
for lesson in self.session_data["lessons_learned"]:
lessons_text += f"- **{lesson['category'].title()}:** {lesson['lesson']}\n"
return lessons_text
def _format_commands(self) -> str:
"""Formatar comandos executados"""
if not self.session_data["commands_executed"]:
return "Nenhum comando específico registrado."
commands_text = "```bash\n"
for cmd in self.session_data["commands_executed"]:
commands_text += f"# {cmd['timestamp']}\n"
commands_text += f"{cmd['command']}\n"
if cmd.get("result"):
commands_text += f"# Resultado: {cmd['result']}\n"
commands_text += "\n"
commands_text += "```"
return commands_text
def save_session(self):
"""Salvar sessão completa"""
if not self.current_session_dir:
return
# Salvar README.md
readme_path = self.current_session_dir / "README.md"
with open(readme_path, 'w', encoding='utf-8') as f:
f.write(self.generate_readme())
# Salvar dados JSON da sessão
json_path = self.current_session_dir / "session_data.json"
with open(json_path, 'w', encoding='utf-8') as f:
json.dump(self.session_data, f, indent=2, ensure_ascii=False)
# Finalizar sessão
self.session_data["end_time"] = datetime.now().isoformat()
def get_session_summary(self) -> Dict[str, Any]:
"""Obter resumo da sessão atual"""
return {
"session_id": self.current_session_id,
"session_dir": str(self.current_session_dir) if self.current_session_dir else None,
"total_requested": self.session_data["results"]["total_requested"],
"successful_downloads": self.session_data["results"]["successful_downloads"],
"failed_downloads": self.session_data["results"]["failed_downloads"],
"success_rate": (self.session_data["results"]["successful_downloads"] /
self.session_data["results"]["total_requested"] * 100) if self.session_data["results"]["total_requested"] > 0 else 0,
"total_size_mb": self.session_data["results"]["total_size_mb"],
"files_count": len(self.session_data["results"]["files_downloaded"])
}