Files
dify/api/core/extension/extensible.py
T
+40 5bbf685035 feat: fix i18n missing keys and merge upstream/main (#24615)
Signed-off-by: -LAN- <[email protected]>
Signed-off-by: kenwoodjw <[email protected]>
Signed-off-by: Yongtao Huang <[email protected]>
Signed-off-by: yihong0618 <[email protected]>
Signed-off-by: zhanluxianshen <[email protected]>
Co-authored-by: -LAN- <[email protected]>
Co-authored-by: GuanMu <[email protected]>
Co-authored-by: Davide Delbianco <[email protected]>
Co-authored-by: NeatGuyCoding <[email protected]>
Co-authored-by: kenwoodjw <[email protected]>
Co-authored-by: Yongtao Huang <[email protected]>
Co-authored-by: Yongtao Huang <[email protected]>
Co-authored-by: Qiang Lee <[email protected]>
Co-authored-by: 李强04 <[email protected]>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Co-authored-by: Asuka Minato <[email protected]>
Co-authored-by: Matri Qi <[email protected]>
Co-authored-by: huayaoyue6 <[email protected]>
Co-authored-by: Bowen Liang <[email protected]>
Co-authored-by: znn <[email protected]>
Co-authored-by: crazywoola <[email protected]>
Co-authored-by: crazywoola <[email protected]>
Co-authored-by: Copilot <[email protected]>
Co-authored-by: yihong <[email protected]>
Co-authored-by: Muke Wang <[email protected]>
Co-authored-by: wangmuke <[email protected]>
Co-authored-by: Wu Tianwei <[email protected]>
Co-authored-by: quicksand <[email protected]>
Co-authored-by: 非法操作 <[email protected]>
Co-authored-by: zxhlyh <[email protected]>
Co-authored-by: Eric Guo <[email protected]>
Co-authored-by: Zhedong Cen <[email protected]>
Co-authored-by: jiangbo721 <[email protected]>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: hjlarry <[email protected]>
Co-authored-by: lxsummer <[email protected]>
Co-authored-by: 湛露先生 <[email protected]>
Co-authored-by: Guangdong Liu <[email protected]>
Co-authored-by: QuantumGhost <[email protected]>
Co-authored-by: Claude <[email protected]>
Co-authored-by: Yessenia-d <[email protected]>
Co-authored-by: huangzhuo1949 <[email protected]>
Co-authored-by: huangzhuo <[email protected]>
Co-authored-by: 17hz <[email protected]>
Co-authored-by: Amy <[email protected]>
Co-authored-by: Joel <[email protected]>
Co-authored-by: Nite Knite <[email protected]>
Co-authored-by: Yeuoly <[email protected]>
Co-authored-by: Petrus Han <[email protected]>
Co-authored-by: iamjoel <[email protected]>
Co-authored-by: Kalo Chin <[email protected]>
Co-authored-by: Ujjwal Maurya <[email protected]>
Co-authored-by: Maries <[email protected]>
2025-08-27 15:07:28 +08:00

136 lines
4.6 KiB
Python

import enum
import importlib.util
import json
import logging
import os
from pathlib import Path
from typing import Any, Optional
from pydantic import BaseModel
from core.helper.position_helper import sort_to_dict_by_position_map
logger = logging.getLogger(__name__)
class ExtensionModule(enum.Enum):
MODERATION = "moderation"
EXTERNAL_DATA_TOOL = "external_data_tool"
class ModuleExtension(BaseModel):
extension_class: Optional[Any] = None
name: str
label: Optional[dict] = None
form_schema: Optional[list] = None
builtin: bool = True
position: Optional[int] = None
class Extensible:
module: ExtensionModule
name: str
tenant_id: str
config: Optional[dict] = None
def __init__(self, tenant_id: str, config: Optional[dict] = None) -> None:
self.tenant_id = tenant_id
self.config = config
@classmethod
def scan_extensions(cls):
extensions = []
position_map: dict[str, int] = {}
# Get the package name from the module path
package_name = ".".join(cls.__module__.split(".")[:-1])
try:
# Get package directory path
package_spec = importlib.util.find_spec(package_name)
if not package_spec or not package_spec.origin:
raise ImportError(f"Could not find package {package_name}")
package_dir = os.path.dirname(package_spec.origin)
# Traverse subdirectories
for subdir_name in os.listdir(package_dir):
if subdir_name.startswith("__"):
continue
subdir_path = os.path.join(package_dir, subdir_name)
if not os.path.isdir(subdir_path):
continue
extension_name = subdir_name
file_names = os.listdir(subdir_path)
# Check for extension module file
if (extension_name + ".py") not in file_names:
logger.warning("Missing %s.py file in %s, Skip.", extension_name, subdir_path)
continue
# Check for builtin flag and position
builtin = False
position = 0
if "__builtin__" in file_names:
builtin = True
builtin_file_path = os.path.join(subdir_path, "__builtin__")
if os.path.exists(builtin_file_path):
position = int(Path(builtin_file_path).read_text(encoding="utf-8").strip())
position_map[extension_name] = position
# Import the extension module
module_name = f"{package_name}.{extension_name}.{extension_name}"
spec = importlib.util.find_spec(module_name)
if not spec or not spec.loader:
raise ImportError(f"Failed to load module {module_name}")
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
# Find extension class
extension_class = None
for name, obj in vars(mod).items():
if isinstance(obj, type) and issubclass(obj, cls) and obj != cls:
extension_class = obj
break
if not extension_class:
logger.warning("Missing subclass of %s in %s, Skip.", cls.__name__, module_name)
continue
# Load schema if not builtin
json_data: dict[str, Any] = {}
if not builtin:
json_path = os.path.join(subdir_path, "schema.json")
if not os.path.exists(json_path):
logger.warning("Missing schema.json file in %s, Skip.", subdir_path)
continue
with open(json_path, encoding="utf-8") as f:
json_data = json.load(f)
# Create extension
extensions.append(
ModuleExtension(
extension_class=extension_class,
name=extension_name,
label=json_data.get("label"),
form_schema=json_data.get("form_schema"),
builtin=builtin,
position=position,
)
)
except Exception as e:
logger.exception("Error scanning extensions")
raise
# Sort extensions by position
sorted_extensions = sort_to_dict_by_position_map(
position_map=position_map, data=extensions, name_func=lambda x: x.name
)
return sorted_extensions