168 lines
No EOL
6.3 KiB
Python
168 lines
No EOL
6.3 KiB
Python
"""
|
|
Filecreator-Agent für die Erstellung von Dateien mit Inhalten und deren Speicherung in der Datenbank (Fortsetzung).
|
|
"""
|
|
|
|
import logging
|
|
import base64
|
|
from typing import List, Dict, Any, Optional, Tuple
|
|
import uuid
|
|
from datetime import datetime
|
|
from modules.agentservice_base import BaseAgent
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
class FilecreatorAgent(BaseAgent):
|
|
"""Agent für die Erstellung und Speicherung von Dateien"""
|
|
|
|
# (Vorherige Implementierung hier)
|
|
|
|
def _extract_file_params(self, message_content: str) -> Dict[str, Any]:
|
|
"""
|
|
Extrahiert Dateiparameter aus dem Nachrichteninhalt.
|
|
|
|
Args:
|
|
message_content: Inhalt der Nachricht
|
|
|
|
Returns:
|
|
Dictionary mit Dateiparametern
|
|
"""
|
|
# Grundlegende Parameter
|
|
file_params = {
|
|
"name": "document.txt",
|
|
"content": "",
|
|
"type": "text/plain"
|
|
}
|
|
|
|
# Einfache Heuristik zur Extraktion der Parameter
|
|
lines = message_content.split('\n')
|
|
content_lines = []
|
|
is_content_section = False
|
|
|
|
for line in lines:
|
|
line = line.strip()
|
|
|
|
# Dateiname erkennen
|
|
if line.startswith("DATEINAME:") or line.startswith("FILENAME:"):
|
|
file_params["name"] = line.split(":", 1)[1].strip()
|
|
|
|
# Dateityp erkennen
|
|
elif line.startswith("TYP:") or line.startswith("TYPE:"):
|
|
file_type = line.split(":", 1)[1].strip().lower()
|
|
|
|
# MIME-Typ anhand der Angabe setzen
|
|
if file_type in ["text", "txt", "plain"]:
|
|
file_params["type"] = "text/plain"
|
|
if not file_params["name"].endswith(".txt"):
|
|
file_params["name"] += ".txt"
|
|
|
|
elif file_type in ["markdown", "md"]:
|
|
file_params["type"] = "text/markdown"
|
|
if not file_params["name"].endswith(".md"):
|
|
file_params["name"] += ".md"
|
|
|
|
elif file_type in ["csv"]:
|
|
file_params["type"] = "text/csv"
|
|
if not file_params["name"].endswith(".csv"):
|
|
file_params["name"] += ".csv"
|
|
|
|
elif file_type in ["json"]:
|
|
file_params["type"] = "application/json"
|
|
if not file_params["name"].endswith(".json"):
|
|
file_params["name"] += ".json"
|
|
|
|
elif file_type in ["html"]:
|
|
file_params["type"] = "text/html"
|
|
if not file_params["name"].endswith(".html"):
|
|
file_params["name"] += ".html"
|
|
|
|
# Inhalt sammeln
|
|
elif line == "INHALT:" or line == "CONTENT:":
|
|
is_content_section = True
|
|
continue
|
|
|
|
elif is_content_section:
|
|
content_lines.append(line)
|
|
|
|
# Wenn kein Inhalt gefunden wurde, versuche den gesamten Inhalt zu verwenden
|
|
if not content_lines and not is_content_section:
|
|
# Ignoriere die ersten und letzten Zeilen (können Anweisungen sein)
|
|
if len(lines) > 4:
|
|
content_lines = lines[2:-2]
|
|
else:
|
|
content_lines = lines
|
|
|
|
# Inhalt zusammensetzen
|
|
file_params["content"] = "\n".join(content_lines)
|
|
|
|
# Dateiformat aus dem Dateinamen ableiten, falls nicht explizit angegeben
|
|
if "type" not in file_params:
|
|
file_extension = file_params["name"].split(".")[-1].lower() if "." in file_params["name"] else ""
|
|
if file_extension == "md":
|
|
file_params["type"] = "text/markdown"
|
|
elif file_extension == "csv":
|
|
file_params["type"] = "text/csv"
|
|
elif file_extension == "json":
|
|
file_params["type"] = "application/json"
|
|
elif file_extension == "html":
|
|
file_params["type"] = "text/html"
|
|
else:
|
|
file_params["type"] = "text/plain"
|
|
|
|
return file_params
|
|
|
|
async def _create_and_save_file(self, file_params: Dict[str, Any], lucydom_interface) -> Tuple[str, str, str]:
|
|
"""
|
|
Erstellt und speichert eine Datei in der Datenbank.
|
|
|
|
Args:
|
|
file_params: Parameter für die Dateierstellung
|
|
lucydom_interface: Interface für Datenbankzugriffe
|
|
|
|
Returns:
|
|
Tuple mit (file_id, file_name, file_type)
|
|
"""
|
|
if not lucydom_interface:
|
|
raise ValueError("Kein LucyDOM-Interface verfügbar für die Dateispeicherung")
|
|
|
|
# Dateiparameter extrahieren
|
|
file_name = file_params.get("name", "document.txt")
|
|
file_content = file_params.get("content", "")
|
|
content_type = file_params.get("type", "text/plain")
|
|
|
|
# Dateityp aus dem Content-Type ableiten
|
|
file_type = "document" # Standard-Dateityp
|
|
if content_type.startswith("image/"):
|
|
file_type = "image"
|
|
|
|
# Binäre Dateidaten erstellen
|
|
file_data = file_content.encode('utf-8')
|
|
|
|
# Datei über LucyDOM-Interface speichern
|
|
try:
|
|
file_meta = lucydom_interface.save_uploaded_file(file_data, file_name)
|
|
|
|
if not file_meta or "id" not in file_meta:
|
|
raise ValueError("Fehler beim Speichern der Datei")
|
|
|
|
file_id = file_meta["id"]
|
|
|
|
# Dateityp aktualisieren, falls notwendig
|
|
update_data = {"type": file_type, "content_type": content_type}
|
|
lucydom_interface.update_file(file_id, update_data)
|
|
|
|
return file_id, file_name, file_type
|
|
|
|
except Exception as e:
|
|
logger.error(f"Fehler beim Speichern der Datei {file_name}: {str(e)}")
|
|
raise ValueError(f"Fehler beim Speichern der Datei: {str(e)}")
|
|
|
|
|
|
# Singleton-Instanz
|
|
_filecreator_agent = None
|
|
|
|
def get_filecreator_agent():
|
|
"""Gibt eine Singleton-Instanz des FileCreator-Agenten zurück"""
|
|
global _filecreator_agent
|
|
if _filecreator_agent is None:
|
|
_filecreator_agent = FilecreatorAgent()
|
|
return _filecreator_agent |