Files
syops/backend/edkb_system/skills/export.py
T
2026-05-12 08:16:42 +08:00

568 lines
19 KiB
Python

from __future__ import annotations
import base64
import hashlib
import io
import json
import os
import re
import shutil
from dataclasses import asdict, replace
from pathlib import Path
from urllib.parse import quote, urlparse
from edkb_system.contracts import Block, Chunk, Context
def _write(path: Path, text: str) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(text, encoding="utf-8")
_EMBEDDED_IMG_RE = re.compile(
r"!\[(?P<alt>[^\]]*)\]\((?P<uri>data:image/(?P<fmt>[a-zA-Z0-9.+-]+);base64,(?P<b64>[^)]+))\)",
re.IGNORECASE | re.DOTALL,
)
_EMBEDDED_IMG_LOOSE_RE = re.compile(
r"!\[(?P<alt>[^\]]*)\]\((?P<uri>data:image/[^)]*)\)",
re.IGNORECASE | re.DOTALL,
)
_EMBEDDED_IMG_ANY_RE = re.compile(
r"!\[[^\]]*\]\(data:image/.*?\)",
re.IGNORECASE | re.DOTALL,
)
_KEEP_IMAGE = "__KEEP_EMBEDDED_IMAGE__"
_DROP_IMAGE = "__DROP_EMBEDDED_IMAGE__"
def _bool_env(name: str, default: bool) -> bool:
raw = os.getenv(name)
if raw is None:
return default
return raw.strip().lower() in {"1", "true", "yes", "on"}
def _sanitize_segment(raw: str) -> str:
s = (raw or "").strip()
if not s:
return "untitled"
s = re.sub(r"\s+", "_", s)
s = s.replace("/", "_").replace("\\", "_")
s = re.sub(r"[:*?\"<>|]", "_", s)
s = re.sub(r"_+", "_", s).strip("._")
return s or "untitled"
def _build_object_prefix(
source_category: str, source_rel_path: str, source_file: str
) -> str:
rel = (source_rel_path or source_file or "document").replace("\\", "/").strip("/")
parts = [p for p in rel.split("/") if p and p not in {".", ".."}]
category = _sanitize_segment(source_category)
if not category:
if len(parts) >= 2:
category = _sanitize_segment(parts[0])
else:
category = "uncategorized"
if parts and _sanitize_segment(parts[0]) == category:
parts = parts[1:]
if parts:
doc_parts = parts[:-1] + [Path(parts[-1]).stem or "document"]
else:
doc_parts = [Path(source_file or "document").stem or "document"]
normalized = [category] + [_sanitize_segment(p) for p in doc_parts]
normalized = [p for p in normalized if p]
return "/".join(normalized)
def _normalize_endpoint(raw_endpoint: str) -> tuple[str, bool]:
endpoint = (raw_endpoint or "").strip()
secure_default = False
if "://" in endpoint:
parsed = urlparse(endpoint)
secure_default = parsed.scheme.lower() == "https"
endpoint = parsed.netloc or parsed.path
endpoint = endpoint.strip().rstrip("/")
return endpoint, secure_default
def _normalize_public_base(raw_base: str, endpoint: str, secure: bool) -> str:
base = (raw_base or "").strip().rstrip("/")
if not base:
scheme = "https" if secure else "http"
return f"{scheme}://{endpoint}".rstrip("/")
if "://" not in base:
scheme = "https" if secure else "http"
return f"{scheme}://{base}".rstrip("/")
return base.rstrip("/")
def _quote_object_name(object_name: str) -> str:
return "/".join(quote(seg, safe="") for seg in object_name.split("/"))
def _ext_from_blob(blob: bytes) -> str | None:
if blob.startswith(b"\x89PNG\r\n\x1a\n"):
return "png"
if blob.startswith(b"\xff\xd8\xff"):
return "jpg"
if blob.startswith((b"GIF87a", b"GIF89a")):
return "gif"
if blob.startswith(b"BM"):
return "bmp"
if len(blob) >= 12 and blob[:4] == b"RIFF" and blob[8:12] == b"WEBP":
return "webp"
return None
def _normalize_ext(fmt: str, blob: bytes) -> str:
f = (fmt or "").lower().strip()
if f in {"jpeg", "jpg"}:
return "jpg"
if f in {"png", "gif", "bmp", "webp"}:
return f
guessed = _ext_from_blob(blob)
return guessed or "png"
def _content_type_for_ext(ext: str) -> str:
if ext == "jpg":
return "image/jpeg"
if ext == "png":
return "image/png"
if ext == "gif":
return "image/gif"
if ext == "bmp":
return "image/bmp"
if ext == "webp":
return "image/webp"
return "application/octet-stream"
def _is_valid_image_blob(blob: bytes) -> bool:
if len(blob) < 8:
return False
if _ext_from_blob(blob):
return True
# Unknown format fallback: keep only if not tiny garbage.
return len(blob) >= 64
class _MinioStorage:
def __init__(
self,
*,
endpoint: str,
bucket_name: str,
access_key: str,
secret_key: str,
secure: bool,
public_base: str,
) -> None:
import importlib
minio_mod = importlib.import_module("minio")
minio_ctor = getattr(minio_mod, "Minio")
self.bucket_name = bucket_name
self.public_base = public_base.rstrip("/")
self.client = minio_ctor(
endpoint,
access_key=access_key,
secret_key=secret_key,
secure=secure,
)
if not self.client.bucket_exists(bucket_name):
self.client.make_bucket(bucket_name)
def put_bytes(self, object_name: str, blob: bytes, content_type: str) -> None:
stream = io.BytesIO(blob)
self.client.put_object(
self.bucket_name,
object_name,
stream,
len(blob),
content_type=content_type,
)
def list_prefix(self, prefix: str) -> list[str]:
return [
obj.object_name
for obj in self.client.list_objects(
self.bucket_name,
prefix=prefix,
recursive=True,
)
]
def remove_object(self, object_name: str) -> None:
self.client.remove_object(self.bucket_name, object_name)
def build_url(self, object_name: str) -> str:
return (
f"{self.public_base}/{self.bucket_name}/{_quote_object_name(object_name)}"
)
class _RemoteImageRewriter:
def __init__(
self,
*,
context: Context,
source_file: str,
source_rel_path: str,
source_category: str,
) -> None:
self.context = context
self.source_file = source_file
self.source_rel_path = source_rel_path
self.source_category = source_category
self.object_prefix = _build_object_prefix(
source_category, source_rel_path, source_file
)
self.allow_embed_fallback = _bool_env("MINIO_ALLOW_EMBED_FALLBACK", False)
self.storage: _MinioStorage | None = None
self._storage_initialized = False
self.uri_cache: dict[str, str] = {}
self.sha_cache: dict[str, tuple[str, str]] = {}
self.referenced_objects: set[str] = set()
self.uploaded_count = 0
self.reused_count = 0
self.invalid_removed_count = 0
self.kept_embedded_count = 0
self.stale_removed_count = 0
self._upload_error_warn_count = 0
self._saw_embedded_image = False
self._next_image_index = 1
def _build_storage(self) -> _MinioStorage | None:
if not _bool_env("MINIO_UPLOAD_ENABLED", True):
if self.allow_embed_fallback:
self.context.warnings.append(
"image-hosting disabled by MINIO_UPLOAD_ENABLED"
)
return None
raise RuntimeError("image-hosting disabled by MINIO_UPLOAD_ENABLED")
endpoint_raw = os.getenv("MINIO_ENDPOINT", "127.0.0.1:9000")
endpoint, secure_default = _normalize_endpoint(endpoint_raw)
secure = _bool_env("MINIO_SECURE", secure_default)
if not endpoint:
if self.allow_embed_fallback:
self.context.warnings.append(
"image-hosting disabled: MINIO_ENDPOINT is empty"
)
return None
raise RuntimeError("image-hosting disabled: MINIO_ENDPOINT is empty")
bucket_name = os.getenv("MINIO_BUCKET", "image-hosting-service")
access_key = os.getenv("MINIO_ACCESS_KEY", "admin")
secret_key = os.getenv("MINIO_SECRET_KEY", "difyai123456")
public_base = _normalize_public_base(
os.getenv("MINIO_PUBLIC_BASE_URL", ""), endpoint, secure
)
try:
return _MinioStorage(
endpoint=endpoint,
bucket_name=bucket_name,
access_key=access_key,
secret_key=secret_key,
secure=secure,
public_base=public_base,
)
except Exception as exc:
if self.allow_embed_fallback:
self.context.warnings.append(
f"image-hosting unavailable, keep embedded image: {exc}"
)
return None
raise RuntimeError(f"image-hosting unavailable: {exc}")
def _warn_upload_error(self, msg: str) -> None:
if self._upload_error_warn_count < 5:
self.context.warnings.append(msg)
self._upload_error_warn_count += 1
def _ensure_storage(self) -> None:
if self._storage_initialized:
return
self.storage = self._build_storage()
self._storage_initialized = True
def _process_embedded_uri(self, uri: str, fmt: str, b64_raw: str) -> str:
cached = self.uri_cache.get(uri)
if cached is not None:
return cached
fmt = (fmt or "png").lower()
b64_clean = re.sub(r"\s+", "", b64_raw)
try:
blob = base64.b64decode(b64_clean, validate=False)
except Exception:
self.invalid_removed_count += 1
self.uri_cache[uri] = _DROP_IMAGE
return _DROP_IMAGE
if not _is_valid_image_blob(blob):
self.invalid_removed_count += 1
self.uri_cache[uri] = _DROP_IMAGE
return _DROP_IMAGE
self._ensure_storage()
if self.storage is None:
if not self.allow_embed_fallback:
raise RuntimeError(
"image-hosting unavailable: embedded fallback is disabled"
)
self.kept_embedded_count += 1
self.uri_cache[uri] = _KEEP_IMAGE
return _KEEP_IMAGE
sha = hashlib.sha256(blob).hexdigest()
cached_sha = self.sha_cache.get(sha)
if cached_sha is not None:
url, object_name = cached_sha
self.referenced_objects.add(object_name)
self.reused_count += 1
self.uri_cache[uri] = url
return url
ext = _normalize_ext(fmt, blob)
content_type = _content_type_for_ext(ext)
file_name = f"img_{self._next_image_index:03d}_{sha[:8]}.{ext}"
self._next_image_index += 1
object_name = (
f"{self.object_prefix}/{file_name}" if self.object_prefix else file_name
)
try:
self.storage.put_bytes(object_name, blob, content_type)
url = self.storage.build_url(object_name)
self.sha_cache[sha] = (url, object_name)
self.referenced_objects.add(object_name)
self.uploaded_count += 1
self.uri_cache[uri] = url
return url
except Exception as exc:
if not self.allow_embed_fallback:
raise RuntimeError(
f"image-hosting upload failed ({self.source_file}): {object_name} ({exc})"
) from exc
self.kept_embedded_count += 1
self.uri_cache[uri] = _KEEP_IMAGE
self._warn_upload_error(
f"image-hosting upload failed ({self.source_file}): {object_name} ({exc})"
)
return _KEEP_IMAGE
def _process_match(self, m: re.Match[str]) -> str:
return self._process_embedded_uri(
m.group("uri"),
m.group("fmt") or "png",
m.group("b64") or "",
)
def _process_loose_uri(self, uri: str) -> str:
cached = self.uri_cache.get(uri)
if cached is not None:
return cached
head, sep, b64_raw = uri.partition(",")
if not sep:
self.invalid_removed_count += 1
self.uri_cache[uri] = _DROP_IMAGE
return _DROP_IMAGE
fmt = "png"
m = re.match(r"^data:image/(?P<fmt>[a-zA-Z0-9.+-]+)", head, re.IGNORECASE)
if m:
fmt = (m.group("fmt") or "png").lower()
return self._process_embedded_uri(uri, fmt, b64_raw)
def replace_text(self, text: str) -> str:
if not text or "data:image/" not in text:
return text
self._saw_embedded_image = True
def repl(m: re.Match[str]) -> str:
alt = m.group("alt") or "image"
decision = self._process_match(m)
if decision == _DROP_IMAGE:
return ""
if decision == _KEEP_IMAGE:
return m.group(0)
return f"![{alt}]({decision})"
out = _EMBEDDED_IMG_RE.sub(repl, text)
if "data:image/" in out:
def loose_repl(m: re.Match[str]) -> str:
alt = m.group("alt") or "image"
decision = self._process_loose_uri(m.group("uri") or "")
if decision == _DROP_IMAGE:
return ""
if decision == _KEEP_IMAGE:
return m.group(0)
return f"![{alt}]({decision})"
out = _EMBEDDED_IMG_LOOSE_RE.sub(loose_repl, out)
if not self.allow_embed_fallback and "data:image/" in out:
dropped_before = self.invalid_removed_count
out = _EMBEDDED_IMG_LOOSE_RE.sub("", out)
out = _EMBEDDED_IMG_ANY_RE.sub("", out)
removed = self.invalid_removed_count - dropped_before
if "data:image/" in out:
self.context.warnings.append(
"image-hosting left non-markdown data:image content; kept as-is"
)
else:
self.context.warnings.append(
"image-hosting removed unsupported embedded images"
+ (f": {removed}" if removed > 0 else "")
)
out = re.sub(r"(?:\s*<br>\s*){2,}", " <br> ", out)
return out
def finalize(self) -> None:
if self._saw_embedded_image and _bool_env("MINIO_CLEANUP_STALE", True):
self._ensure_storage()
if self.storage is not None and _bool_env("MINIO_CLEANUP_STALE", True):
prefix = f"{self.object_prefix}/"
try:
for object_name in self.storage.list_prefix(prefix):
if object_name in self.referenced_objects:
continue
self.storage.remove_object(object_name)
self.stale_removed_count += 1
except Exception as exc:
self.context.warnings.append(
f"image-hosting cleanup failed ({self.source_file}): {exc}"
)
if self.invalid_removed_count > 0:
self.context.warnings.append(
f"image-hosting removed invalid images: {self.invalid_removed_count}"
)
if self.kept_embedded_count > 0 and self.storage is None:
self.context.warnings.append(
"image-hosting unavailable: keep legacy data:image embeds"
)
if (
self.uploaded_count > 0
or self.reused_count > 0
or self.stale_removed_count > 0
):
self.context.warnings.append(
"image-hosting synced "
f"(uploaded={self.uploaded_count}, reused={self.reused_count}, "
f"stale_removed={self.stale_removed_count}, prefix={self.object_prefix})"
)
def run(input_data: dict, context: Context) -> dict:
out_dir = Path(input_data["out_dir"])
out_dir.mkdir(parents=True, exist_ok=True)
source_file = input_data.get("source_file", "")
source_rel_path = input_data.get("source_rel_path", source_file)
source_category = input_data.get("source_category", "")
source_stem = Path(source_file).stem if source_file else out_dir.name
flat_clean_path = Path(
input_data.get("flat_md_path", out_dir.parent / f"{source_stem}.md")
)
view_clean_path = out_dir / "03_clean_view.md"
view_images_dir = out_dir / "images_view"
for p in [
out_dir / "01_raw_layout.json",
out_dir / "02_flow_procedure.md",
out_dir / "03_clean.md",
out_dir / "04_chunks.jsonl",
out_dir / "report.md",
view_clean_path,
flat_clean_path,
]:
if p.exists():
p.unlink()
chunks_dir = out_dir / "chunks"
if chunks_dir.exists():
shutil.rmtree(chunks_dir)
if view_images_dir.exists():
shutil.rmtree(view_images_dir)
clean_md: str = input_data.get("clean_md", "")
chunks: list[Chunk] = input_data.get("chunks", [])
blocks: list[Block] = input_data.get("blocks", [])
flow_markdowns: list[str] = input_data.get("flow_markdowns", [])
rewriter = _RemoteImageRewriter(
context=context,
source_file=source_file,
source_rel_path=source_rel_path,
source_category=source_category,
)
clean_md = rewriter.replace_text(clean_md)
exported_chunks = [replace(c, text=rewriter.replace_text(c.text)) for c in chunks]
rewriter.finalize()
_write(out_dir / "03_clean.md", clean_md)
_write(flat_clean_path, clean_md)
lines = [json.dumps(asdict(c), ensure_ascii=False) for c in exported_chunks]
_write(out_dir / "04_chunks.jsonl", "\n".join(lines) + ("\n" if lines else ""))
chunks_dir.mkdir(parents=True, exist_ok=True)
for c in exported_chunks:
_write(chunks_dir / f"chunk_{c.index:04d}.md", c.text + "\n")
if flow_markdowns:
_write(out_dir / "02_flow_procedure.md", "\n\n".join(flow_markdowns) + "\n")
_write(
out_dir / "01_raw_layout.json",
json.dumps([asdict(b) for b in blocks], ensure_ascii=False, indent=2) + "\n",
)
report_lines = [
f"# Report: {input_data.get('source_file', '')}",
"",
f"- pages: {context.pages}",
f"- images: {context.images}",
f"- ocr_characters: {context.ocr_characters}",
f"- flows_detected: {context.flows_detected}",
f"- confidence: {context.confidence:.2f}",
"",
"## warnings",
]
if context.warnings:
report_lines.extend([f"- {w}" for w in context.warnings])
else:
report_lines.append("- none")
report_lines.extend(
[
"",
"## recommended_dify_settings",
"- Index: High Quality",
"- Retrieval: Hybrid",
"- Chunking: General",
"",
]
)
_write(out_dir / "report.md", "\n".join(report_lines))
return {"out_dir": str(out_dir)}