RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.
Go agent-harnessagent-native-databaseagentic-aiagentic-retrievalagentic-searchaiai-agentscontext-enginecontext-engineeringcontext-managementharness-engineeringknowledge-compilationragretrieval-augmented-generationretrieval-harnesssearch-harness
Move 'get_project_base_directory' to common directory (#10940)
Jin Hai44f2d6f5daba
diff --git a/api/apps/document_app.py b/api/apps/document_app.pyindex fb6f9fdd42..934da374cc 100644--- a/api/apps/document_app.py+++ b/api/apps/document_app.py@@ -42,7 +42,8 @@ from api.utils.api_utils import (server_error_response,validate_request,)-from api.utils.file_utils import filename_type, get_project_base_directory, thumbnail+from api.utils.file_utils import filename_type, thumbnail+from common.file_utils import get_project_base_directoryfrom api.utils.web_utils import CONTENT_TYPE_MAP, html2pdf, is_valid_urlfrom deepdoc.parser.html_parser import RAGFlowHtmlParserfrom rag.nlp import search, rag_tokenizerdiff --git a/api/db/init_data.py b/api/db/init_data.pyindex 39b87d06f0..78ef6cfc93 100644--- a/api/db/init_data.py+++ b/api/db/init_data.py@@ -30,7 +30,7 @@ from api.db.services.tenant_llm_service import LLMFactoriesService, TenantLLMSerfrom api.db.services.llm_service import LLMService, LLMBundle, get_init_tenant_llmfrom api.db.services.user_service import TenantService, UserTenantServicefrom api import settings-from api.utils.file_utils import get_project_base_directory+from common.file_utils import get_project_base_directoryfrom api.common.base64 import encode_to_base64diff --git a/api/ragflow_server.py b/api/ragflow_server.pyindex fb49f3d8bd..8ce3916494 100644--- a/api/ragflow_server.py+++ b/api/ragflow_server.py@@ -36,7 +36,7 @@ from api import settingsfrom api.apps import app, smtp_mail_serverfrom api.db.runtime_config import RuntimeConfigfrom api.db.services.document_service import DocumentService-from api import utils+from common.file_utils import get_project_base_directoryfrom api.db.db_models import init_database_tables as init_web_dbfrom api.db.init_data import init_web_data@@ -88,7 +88,7 @@ if __name__ == '__main__':f'RAGFlow version: {get_ragflow_version()}')logging.info(- f'project base: {utils.file_utils.get_project_base_directory()}'+ f'project base: {get_project_base_directory()}')show_configs()settings.init_settings()diff --git a/api/settings.py b/api/settings.pyindex c8573bf29c..592753eb20 100644--- a/api/settings.py+++ b/api/settings.py@@ -25,7 +25,7 @@ import rag.utils.infinity_connimport rag.utils.opensearch_connfrom api.constants import RAG_FLOW_SERVICE_NAMEfrom api.utils.configs import decrypt_database_config, get_base_config-from api.utils.file_utils import get_project_base_directory+from common.file_utils import get_project_base_directoryfrom rag.nlp import searchLLM = Nonediff --git a/api/utils/configs.py b/api/utils/configs.pyindex 48e4922465..c586d90915 100644--- a/api/utils/configs.py+++ b/api/utils/configs.py@@ -23,6 +23,7 @@ import pickleimport importlibfrom api.utils import file_utils+from common.file_utils import get_project_base_directoryfrom filelock import FileLockfrom api.utils.common import bytes_to_string, string_to_bytesfrom api.constants import SERVICE_CONF@@ -30,7 +31,7 @@ from api.constants import SERVICE_CONFdef conf_realpath(conf_name):conf_path = f"conf/{conf_name}"- return os.path.join(file_utils.get_project_base_directory(), conf_path)+ return os.path.join(get_project_base_directory(), conf_path)def read_config(conf_name=SERVICE_CONF):@@ -129,8 +130,7 @@ def decrypt_database_config(def update_config(key, value, conf_name=SERVICE_CONF):conf_path = conf_realpath(conf_name=conf_name)if not os.path.isabs(conf_path):- conf_path = os.path.join(- file_utils.get_project_base_directory(), conf_path)+ conf_path = os.path.join(get_project_base_directory(), conf_path)with FileLock(os.path.join(os.path.dirname(conf_path), ".lock")):config = file_utils.load_yaml_conf(conf_path=conf_path) or {}diff --git a/api/utils/crypt.py b/api/utils/crypt.pyindex eb922a8868..174ca35683 100644--- a/api/utils/crypt.py+++ b/api/utils/crypt.py@@ -19,14 +19,14 @@ import osimport sysfrom Cryptodome.PublicKey import RSAfrom Cryptodome.Cipher import PKCS1_v1_5 as Cipher_pkcs1_v1_5-from api.utils import file_utils+from common.file_utils import get_project_base_directorydef crypt(line):"""decrypt(crypt(input_string)) == base64(input_string), which frontend and admin_client use."""- file_path = os.path.join(file_utils.get_project_base_directory(), "conf", "public.pem")+ file_path = os.path.join(get_project_base_directory(), "conf", "public.pem")rsa_key = RSA.importKey(open(file_path).read(), "Welcome")cipher = Cipher_pkcs1_v1_5.new(rsa_key)password_base64 = base64.b64encode(line.encode('utf-8')).decode("utf-8")@@ -35,7 +35,7 @@ def crypt(line):def decrypt(line):- file_path = os.path.join(file_utils.get_project_base_directory(), "conf", "private.pem")+ file_path = os.path.join(get_project_base_directory(), "conf", "private.pem")rsa_key = RSA.importKey(open(file_path).read(), "Welcome")cipher = Cipher_pkcs1_v1_5.new(rsa_key)return cipher.decrypt(base64.b64decode(line), "Fail to decrypt password!").decode('utf-8')@@ -50,7 +50,7 @@ def decrypt2(crypt_text):hex_fixed = '00' + decode_data.hex()decode_data = b16decode(hex_fixed.upper())- file_path = os.path.join(file_utils.get_project_base_directory(), "conf", "private.pem")+ file_path = os.path.join(get_project_base_directory(), "conf", "private.pem")pem = open(file_path).read()rsa_key = RSA.importKey(pem, "Welcome")cipher = Cipher_PKCS1_v1_5.new(rsa_key)diff --git a/api/utils/file_utils.py b/api/utils/file_utils.pyindex 999a1147db..8eb84dcd2b 100644--- a/api/utils/file_utils.py+++ b/api/utils/file_utils.py@@ -43,6 +43,7 @@ from ruamel.yaml import YAML# Local importsfrom api.constants import IMG_BASE64_PREFIXfrom api.db import FileType+from common.file_utils import get_project_base_directoryPROJECT_BASE = os.getenv("RAG_PROJECT_BASE") or os.getenv("RAG_DEPLOY_BASE")@@ -51,21 +52,6 @@ if LOCK_KEY_pdfplumber not in sys.modules:sys.modules[LOCK_KEY_pdfplumber] = threading.Lock()-def get_project_base_directory(*args):- global PROJECT_BASE- if PROJECT_BASE is None:- PROJECT_BASE = os.path.abspath(- os.path.join(- os.path.dirname(os.path.realpath(__file__)),- os.pardir,- os.pardir,- )- )-- if args:- return os.path.join(PROJECT_BASE, *args)- return PROJECT_BASE-@cached(cache=LRUCache(maxsize=10))def load_json_conf(conf_path):if os.path.isabs(conf_path):diff --git a/api/utils/log_utils.py b/api/utils/log_utils.pyindex 0a4840e79a..0348f9e096 100644--- a/api/utils/log_utils.py+++ b/api/utils/log_utils.py@@ -17,19 +17,10 @@ import osimport os.pathimport loggingfrom logging.handlers import RotatingFileHandler+from common.file_utils import get_project_base_directoryinitialized_root_logger = False-def get_project_base_directory():- PROJECT_BASE = os.path.abspath(- os.path.join(- os.path.dirname(os.path.realpath(__file__)),- os.pardir,- os.pardir,- )- )- return PROJECT_BASE-def init_root_logger(logfile_basename: str, log_format: str = "%(asctime)-15s %(levelname)-8s %(process)d %(message)s"):global initialized_root_loggerif initialized_root_logger:diff --git a/common/file_utils.py b/common/file_utils.pynew file mode 100644index 0000000000..6b07bf6464--- /dev/null+++ b/common/file_utils.py@@ -0,0 +1,33 @@+#+# Copyright 2025 The InfiniFlow Authors. All Rights Reserved.+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+#++import os++PROJECT_BASE = os.getenv("RAG_PROJECT_BASE") or os.getenv("RAG_DEPLOY_BASE")++def get_project_base_directory(*args):+ global PROJECT_BASE+ if PROJECT_BASE is None:+ PROJECT_BASE = os.path.abspath(+ os.path.join(+ os.path.dirname(os.path.realpath(__file__)),+ os.pardir,+ )+ )++ if args:+ return os.path.join(PROJECT_BASE, *args)+ return PROJECT_BASEdiff --git a/deepdoc/parser/pdf_parser.py b/deepdoc/parser/pdf_parser.pyindex c9f2f34ca3..dba55bb13c 100644--- a/deepdoc/parser/pdf_parser.py+++ b/deepdoc/parser/pdf_parser.py@@ -34,7 +34,7 @@ from huggingface_hub import snapshot_downloadfrom PIL import Imagefrom pypdf import PdfReader as pdf2_read-from api.utils.file_utils import get_project_base_directory+from common.file_utils import get_project_base_directoryfrom api.utils.common import pip_install_torchfrom deepdoc.vision import OCR, AscendLayoutRecognizer, LayoutRecognizer, Recognizer, TableStructureRecognizerfrom rag.app.picture import vision_llm_chunk as picture_vision_llm_chunkdiff --git a/deepdoc/vision/layout_recognizer.py b/deepdoc/vision/layout_recognizer.pyindex 9cd0b5a5d1..8068cbc070 100644--- a/deepdoc/vision/layout_recognizer.py+++ b/deepdoc/vision/layout_recognizer.py@@ -25,7 +25,7 @@ import cv2import numpy as npfrom huggingface_hub import snapshot_download-from api.utils.file_utils import get_project_base_directory+from common.file_utils import get_project_base_directoryfrom deepdoc.vision import Recognizerfrom deepdoc.vision.operators import nmsdiff --git a/deepdoc/vision/ocr.py b/deepdoc/vision/ocr.pyindex 1a99e6ce04..4c4831d7c9 100644--- a/deepdoc/vision/ocr.py+++ b/deepdoc/vision/ocr.py@@ -21,7 +21,7 @@ import osfrom huggingface_hub import snapshot_download-from api.utils.file_utils import get_project_base_directory+from common.file_utils import get_project_base_directoryfrom api.utils.common import pip_install_torchfrom rag.settings import PARALLEL_DEVICESfrom .operators import * # noqa: F403diff --git a/deepdoc/vision/recognizer.py b/deepdoc/vision/recognizer.pyindex 65995a5798..af259a3842 100644--- a/deepdoc/vision/recognizer.py+++ b/deepdoc/vision/recognizer.py@@ -22,7 +22,7 @@ import cv2from functools import cmp_to_key-from api.utils.file_utils import get_project_base_directory+from common.file_utils import get_project_base_directoryfrom .operators import * # noqa: F403from .operators import preprocessfrom . import operatorsdiff --git a/deepdoc/vision/table_structure_recognizer.py b/deepdoc/vision/table_structure_recognizer.pyindex 34b988e9a8..cf1c79db1a 100644--- a/deepdoc/vision/table_structure_recognizer.py+++ b/deepdoc/vision/table_structure_recognizer.py@@ -21,7 +21,7 @@ from collections import Counterimport numpy as npfrom huggingface_hub import snapshot_download-from api.utils.file_utils import get_project_base_directory+from common.file_utils import get_project_base_directoryfrom rag.nlp import rag_tokenizerfrom .recognizer import Recognizerdiff --git a/rag/nlp/rag_tokenizer.py b/rag/nlp/rag_tokenizer.pyindex c3394971e3..3c4b978336 100644--- a/rag/nlp/rag_tokenizer.py+++ b/rag/nlp/rag_tokenizer.py@@ -25,7 +25,7 @@ import sysfrom hanziconv import HanziConvfrom nltk import word_tokenizefrom nltk.stem import PorterStemmer, WordNetLemmatizer-from api.utils.file_utils import get_project_base_directory+from common.file_utils import get_project_base_directoryclass RagTokenizer:diff --git a/rag/nlp/synonym.py b/rag/nlp/synonym.pyindex b28560ce1f..0956ee8e83 100644--- a/rag/nlp/synonym.py+++ b/rag/nlp/synonym.py@@ -20,7 +20,7 @@ import osimport timeimport refrom nltk.corpus import wordnet-from api.utils.file_utils import get_project_base_directory+from common.file_utils import get_project_base_directoryclass Dealer:diff --git a/rag/nlp/term_weight.py b/rag/nlp/term_weight.pyindex 33ee626604..392117c18d 100644--- a/rag/nlp/term_weight.py+++ b/rag/nlp/term_weight.py@@ -21,7 +21,7 @@ import reimport osimport numpy as npfrom rag.nlp import rag_tokenizer-from api.utils.file_utils import get_project_base_directory+from common.file_utils import get_project_base_directoryclass Dealer:diff --git a/rag/settings.py b/rag/settings.pyindex 6c2017dc14..6167c08ae5 100644--- a/rag/settings.py+++ b/rag/settings.py@@ -16,7 +16,7 @@import osimport loggingfrom api.utils.configs import get_base_config, decrypt_database_config-from api.utils.file_utils import get_project_base_directory+from common.file_utils import get_project_base_directoryfrom api.utils.common import pip_install_torch# Serverdiff --git a/rag/svr/task_executor.py b/rag/svr/task_executor.pyindex 7bc577c63a..8a0d464bab 100644--- a/rag/svr/task_executor.py+++ b/rag/svr/task_executor.py@@ -28,7 +28,8 @@ from api.db.services.knowledgebase_service import KnowledgebaseServicefrom api.db.services.pipeline_operation_log_service import PipelineOperationLogServicefrom api.utils.api_utils import timeoutfrom api.utils.base64_image import image2id-from api.utils.log_utils import init_root_logger, get_project_base_directory+from api.utils.log_utils import init_root_logger+from common.file_utils import get_project_base_directoryfrom api.utils.configs import show_configsfrom graphrag.general.index import run_graphrag_for_kbfrom graphrag.utils import get_llm_cache, set_llm_cache, get_tags_from_cache, set_tags_to_cachediff --git a/rag/utils/__init__.py b/rag/utils/__init__.pyindex f3a696318c..64db543b1c 100644--- a/rag/utils/__init__.py+++ b/rag/utils/__init__.py@@ -17,7 +17,7 @@import osimport tiktoken-from api.utils.file_utils import get_project_base_directory+from common.file_utils import get_project_base_directorytiktoken_cache_dir = get_project_base_directory()os.environ["TIKTOKEN_CACHE_DIR"] = tiktoken_cache_dirdiff --git a/rag/utils/es_conn.py b/rag/utils/es_conn.pyindex e662428bae..e2ce8c9ed1 100644--- a/rag/utils/es_conn.py+++ b/rag/utils/es_conn.py@@ -27,7 +27,7 @@ from elastic_transport import ConnectionTimeoutfrom rag import settingsfrom rag.settings import TAG_FLD, PAGERANK_FLDfrom common.decorator import singleton-from api.utils.file_utils import get_project_base_directory+from common.file_utils import get_project_base_directoryfrom api.utils.common import convert_bytesfrom rag.utils.doc_store_conn import DocStoreConnection, MatchExpr, OrderByExpr, MatchTextExpr, MatchDenseExpr, \FusionExprdiff --git a/rag/utils/infinity_conn.py b/rag/utils/infinity_conn.pyindex 1d6dbd0918..9a92c8e863 100644--- a/rag/utils/infinity_conn.py+++ b/rag/utils/infinity_conn.py@@ -29,7 +29,7 @@ from rag import settingsfrom rag.settings import PAGERANK_FLD, TAG_FLDfrom common.decorator import singletonimport pandas as pd-from api.utils.file_utils import get_project_base_directory+from common.file_utils import get_project_base_directoryfrom rag.nlp import is_englishfrom rag.utils.doc_store_conn import (diff --git a/rag/utils/opensearch_conn.py b/rag/utils/opensearch_conn.pyindex 3c2cf376b4..5c51be52f2 100644--- a/rag/utils/opensearch_conn.py+++ b/rag/utils/opensearch_conn.py@@ -27,7 +27,7 @@ from opensearchpy import ConnectionTimeoutfrom rag import settingsfrom rag.settings import TAG_FLD, PAGERANK_FLDfrom common.decorator import singleton-from api.utils.file_utils import get_project_base_directory+from common.file_utils import get_project_base_directoryfrom rag.utils.doc_store_conn import DocStoreConnection, MatchExpr, OrderByExpr, MatchTextExpr, MatchDenseExpr, \FusionExprfrom rag.nlp import is_english, rag_tokenizerdiff --git a/test/unit_test/common/test_file_utils.py b/test/unit_test/common/test_file_utils.pynew file mode 100644index 0000000000..616312cde2--- /dev/null+++ b/test/unit_test/common/test_file_utils.py@@ -0,0 +1,123 @@+#+# Copyright 2025 The InfiniFlow Authors. All Rights Reserved.+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+#++import os+import pytest+from unittest.mock import patch+from common import file_utils+from common.file_utils import get_project_base_directory+++class TestGetProjectBaseDirectory:+ """Test cases for get_project_base_directory function"""++ def test_returns_project_base_when_no_args(self):+ """Test that function returns project base directory when no arguments provided"""+ result = get_project_base_directory()++ assert result is not None+ assert isinstance(result, str)+ assert os.path.isabs(result) # Should return absolute path++ def test_returns_path_with_single_argument(self):+ """Test that function joins project base with single additional path component"""+ result = get_project_base_directory("subfolder")++ assert result is not None+ assert "subfolder" in result+ assert result.endswith("subfolder")++ def test_returns_path_with_multiple_arguments(self):+ """Test that function joins project base with multiple path components"""+ result = get_project_base_directory("folder1", "folder2", "file.txt")++ assert result is not None+ assert "folder1" in result+ assert "folder2" in result+ assert "file.txt" in result+ assert os.path.basename(result) == "file.txt"++ def test_uses_environment_variable_when_available(self):+ """Test that function uses RAG_PROJECT_BASE environment variable when set"""+ test_path = "/custom/project/path"++ file_utils.PROJECT_BASE = test_path++ result = get_project_base_directory()+ assert result == test_path++ def test_calculates_default_path_when_no_env_vars(self):+ """Test that function calculates default path when no environment variables are set"""+ with patch.dict(os.environ, {}, clear=True): # Clear all environment variables+ # Reset the global variable to force re-initialization++ result = get_project_base_directory()++ # Should return a valid absolute path+ assert result is not None+ assert os.path.isabs(result)+ assert os.path.basename(result) != "" # Should not be root directory++ def test_caches_project_base_value(self):+ """Test that PROJECT_BASE is cached after first calculation"""+ # Reset the global variable++ # First call should calculate the value+ first_result = get_project_base_directory()++ # Store the current value+ cached_value = file_utils.PROJECT_BASE++ # Second call should use cached value+ second_result = get_project_base_directory()++ assert first_result == second_result+ assert file_utils.PROJECT_BASE == cached_value++ def test_path_components_joined_correctly(self):+ """Test that path components are properly joined with the base directory"""+ base_path = get_project_base_directory()+ expected_path = os.path.join(base_path, "data", "files", "document.txt")++ result = get_project_base_directory("data", "files", "document.txt")++ assert result == expected_path++ def test_handles_empty_string_arguments(self):+ """Test that function handles empty string arguments correctly"""+ result = get_project_base_directory("")++ # Should still return a valid path (base directory)+ assert result is not None+ assert os.path.isabs(result)+++# Parameterized tests for different path combinations[email protected]("path_args,expected_suffix", [+ ((), ""), # No additional arguments+ (("src",), "src"),+ (("data", "models"), os.path.join("data", "models")),+ (("config", "app", "settings.json"), os.path.join("config", "app", "settings.json")),+])+def test_various_path_combinations(path_args, expected_suffix):+ """Test various combinations of path arguments"""+ base_path = get_project_base_directory()+ result = get_project_base_directory(*path_args)++ if expected_suffix:+ assert result.endswith(expected_suffix)+ else:+ assert result == base_path