diff --git a/.github/workflows/black.yml b/.github/workflows/black.yml index 35953ec6..b0844312 100644 --- a/.github/workflows/black.yml +++ b/.github/workflows/black.yml @@ -13,4 +13,5 @@ jobs: - uses: actions/checkout@v4 - uses: psf/black@stable with: - src: "hugegraph-llm/src hugegraph-python-client/src" \ No newline at end of file + options: "--check --verbose --line-length 100" + src: "hugegraph-llm/src hugegraph-python-client/src" diff --git a/hugegraph-llm/src/hugegraph_llm/llms/api_bot.py b/hugegraph-llm/src/hugegraph_llm/llms/api_bot.py index d18d7925..f019ff15 100644 --- a/hugegraph-llm/src/hugegraph_llm/llms/api_bot.py +++ b/hugegraph-llm/src/hugegraph_llm/llms/api_bot.py @@ -33,20 +33,24 @@ def __init__(self): @retry(tries=3, delay=1) def generate( - self, - messages: Optional[List[Dict[str, Any]]] = None, - prompt: Optional[str] = None, + self, + messages: Optional[List[Dict[str, Any]]] = None, + prompt: Optional[str] = None, ) -> str: if messages is None: assert prompt is not None, "Messages or prompt must be provided." messages = [{"role": "user", "content": prompt}] url = self.base_url - payload = json.dumps({ - "messages": messages, - }) + payload = json.dumps( + { + "messages": messages, + } + ) headers = {"Content-Type": "application/json"} - response = requests.request("POST", url, headers=headers, data=payload, timeout=30) + response = requests.request( + "POST", url, headers=headers, data=payload, timeout=30 + ) if response.status_code != 200: raise Exception( f"Request failed with code {response.status_code}, message: {response.text}" @@ -55,10 +59,10 @@ def generate( return response_json["content"] def generate_streaming( - self, - messages: Optional[List[Dict[str, Any]]] = None, - prompt: Optional[str] = None, - on_token_callback: Callable = None, + self, + messages: Optional[List[Dict[str, Any]]] = None, + prompt: Optional[str] = None, + on_token_callback: Callable = None, ) -> str: return self.generate(messages, prompt) @@ -75,4 +79,8 @@ def get_llm_type(self) -> str: if __name__ == "__main__": client = ApiBotClient() print(client.generate(prompt="What is the capital of China?")) - print(client.generate(messages=[{"role": "user", "content": "What is the capital of China?"}])) + print( + client.generate( + messages=[{"role": "user", "content": "What is the capital of China?"}] + ) + ) diff --git a/hugegraph-llm/src/hugegraph_llm/llms/ernie_bot.py b/hugegraph-llm/src/hugegraph_llm/llms/ernie_bot.py index d0838aa5..3028cb85 100644 --- a/hugegraph-llm/src/hugegraph_llm/llms/ernie_bot.py +++ b/hugegraph-llm/src/hugegraph_llm/llms/ernie_bot.py @@ -41,7 +41,9 @@ def get_access_token(self): "client_id": self.api_key, "client_secret": self.secret_key, } - return str(requests.post(url, params=params, timeout=2).json().get("access_token")) + return str( + requests.post(url, params=params, timeout=2).json().get("access_token") + ) @retry(tries=3, delay=1) def generate( @@ -56,14 +58,18 @@ def generate( # parameter check failed, temperature range is (0, 1.0] payload = json.dumps({"messages": messages, "temperature": 0.1}) headers = {"Content-Type": "application/json"} - response = requests.request("POST", url, headers=headers, data=payload, timeout=30) + response = requests.request( + "POST", url, headers=headers, data=payload, timeout=30 + ) if response.status_code != 200: raise Exception( f"Request failed with code {response.status_code}, message: {response.text}" ) response_json = json.loads(response.text) if "error_code" in response_json: - raise Exception(f"Error {response_json['error_code']}: {response_json['error_msg']}") + raise Exception( + f"Error {response_json['error_code']}: {response_json['error_msg']}" + ) return response_json["result"] def generate_streaming( @@ -87,4 +93,8 @@ def get_llm_type(self) -> str: if __name__ == "__main__": client = ErnieBotClient() print(client.generate(prompt="What is the capital of China?")) - print(client.generate(messages=[{"role": "user", "content": "What is the capital of China?"}])) + print( + client.generate( + messages=[{"role": "user", "content": "What is the capital of China?"}] + ) + ) diff --git a/hugegraph-llm/src/hugegraph_llm/llms/init_llm.py b/hugegraph-llm/src/hugegraph_llm/llms/init_llm.py index 1fb88599..c132bb31 100644 --- a/hugegraph-llm/src/hugegraph_llm/llms/init_llm.py +++ b/hugegraph-llm/src/hugegraph_llm/llms/init_llm.py @@ -45,4 +45,8 @@ def get_llm(self): if __name__ == "__main__": client = LLMs().get_llm() print(client.generate(prompt="What is the capital of China?")) - print(client.generate(messages=[{"role": "user", "content": "What is the capital of China?"}])) + print( + client.generate( + messages=[{"role": "user", "content": "What is the capital of China?"}] + ) + ) diff --git a/hugegraph-llm/src/hugegraph_llm/operators/common_op/check_schema.py b/hugegraph-llm/src/hugegraph_llm/operators/common_op/check_schema.py index 0228a976..224e517c 100644 --- a/hugegraph-llm/src/hugegraph_llm/operators/common_op/check_schema.py +++ b/hugegraph-llm/src/hugegraph_llm/operators/common_op/check_schema.py @@ -30,13 +30,17 @@ def run(self, schema=None) -> Any: raise ValueError("Input data is not a dictionary.") if "vertices" not in schema or "edges" not in schema: raise ValueError("Input data does not contain 'vertices' or 'edges'.") - if not isinstance(schema["vertices"], list) or not isinstance(schema["edges"], list): + if not isinstance(schema["vertices"], list) or not isinstance( + schema["edges"], list + ): raise ValueError("'vertices' or 'edges' in input data is not a list.") for vertex in schema["vertices"]: if not isinstance(vertex, dict): raise ValueError("Vertex in input data is not a dictionary.") if "vertex_label" not in vertex: - raise ValueError("Vertex in input data does not contain 'vertex_label'.") + raise ValueError( + "Vertex in input data does not contain 'vertex_label'." + ) if not isinstance(vertex["vertex_label"], str): raise ValueError("'vertex_label' in vertex is not of correct type.") for edge in schema["edges"]: diff --git a/hugegraph-llm/src/hugegraph_llm/operators/common_op/nltk_helper.py b/hugegraph-llm/src/hugegraph_llm/operators/common_op/nltk_helper.py index dc3b1dce..66d9b6df 100644 --- a/hugegraph-llm/src/hugegraph_llm/operators/common_op/nltk_helper.py +++ b/hugegraph-llm/src/hugegraph_llm/operators/common_op/nltk_helper.py @@ -68,7 +68,9 @@ def get_cache_dir() -> str: # Windows (hopefully) else: - local = os.environ.get("LOCALAPPDATA", None) or os.path.expanduser("~\\AppData\\Local") + local = os.environ.get("LOCALAPPDATA", None) or os.path.expanduser( + "~\\AppData\\Local" + ) path = Path(local, "hugegraph_llm") if not os.path.exists(path): diff --git a/hugegraph-llm/src/hugegraph_llm/operators/hugegraph_op/commit_to_hugegraph.py b/hugegraph-llm/src/hugegraph_llm/operators/hugegraph_op/commit_to_hugegraph.py index 695c5b71..63dbec90 100644 --- a/hugegraph-llm/src/hugegraph_llm/operators/hugegraph_op/commit_to_hugegraph.py +++ b/hugegraph-llm/src/hugegraph_llm/operators/hugegraph_op/commit_to_hugegraph.py @@ -84,18 +84,20 @@ def init_schema(self, schema): properties = edge["properties"] for prop in properties: self.schema.propertyKey(prop).asText().ifNotExist().create() - self.schema.edgeLabel(edge_label).sourceLabel(source_vertex_label).targetLabel( - target_vertex_label - ).properties(*properties).nullableKeys(*properties).ifNotExist().create() + self.schema.edgeLabel(edge_label).sourceLabel( + source_vertex_label + ).targetLabel(target_vertex_label).properties(*properties).nullableKeys( + *properties + ).ifNotExist().create() def schema_free_mode(self, data): self.schema.propertyKey("name").asText().ifNotExist().create() self.schema.vertexLabel("vertex").useCustomizeStringId().properties( "name" ).ifNotExist().create() - self.schema.edgeLabel("edge").sourceLabel("vertex").targetLabel("vertex").properties( - "name" - ).ifNotExist().create() + self.schema.edgeLabel("edge").sourceLabel("vertex").targetLabel( + "vertex" + ).properties("name").ifNotExist().create() self.schema.indexLabel("vertexByName").onV("vertex").by( "name" diff --git a/hugegraph-llm/src/hugegraph_llm/operators/hugegraph_op/graph_rag_query.py b/hugegraph-llm/src/hugegraph_llm/operators/hugegraph_op/graph_rag_query.py index 3a0905f8..5b5595a8 100644 --- a/hugegraph-llm/src/hugegraph_llm/operators/hugegraph_op/graph_rag_query.py +++ b/hugegraph-llm/src/hugegraph_llm/operators/hugegraph_op/graph_rag_query.py @@ -84,7 +84,6 @@ def __init__( self._prop_to_match = prop_to_match self._schema = "" - def run(self, context: Dict[str, Any]) -> Dict[str, Any]: if self._client is None: if isinstance(context.get("graph_client"), PyHugeClient): @@ -95,7 +94,9 @@ def run(self, context: Dict[str, Any]) -> Dict[str, Any]: graph = context.get("graph") or "hugegraph" user = context.get("user") or "admin" pwd = context.get("pwd") or "admin" - self._client = PyHugeClient(ip=ip, port=port, graph=graph, user=user, pwd=pwd) + self._client = PyHugeClient( + ip=ip, port=port, graph=graph, user=user, pwd=pwd + ) assert self._client is not None, "No graph for query." keywords = context.get("keywords") @@ -138,8 +139,12 @@ def run(self, context: Dict[str, Any]) -> Dict[str, Any]: edge_labels=edge_labels_str, ) - result: List[Any] = self._client.gremlin().exec(gremlin=rag_gremlin_query)["data"] - knowledge: Set[str] = self._format_knowledge_from_query_result(query_result=result) + result: List[Any] = self._client.gremlin().exec(gremlin=rag_gremlin_query)[ + "data" + ] + knowledge: Set[str] = self._format_knowledge_from_query_result( + query_result=result + ) context["synthesize_context_body"] = list(knowledge) context["synthesize_context_head"] = ( @@ -152,7 +157,9 @@ def run(self, context: Dict[str, Any]) -> Dict[str, Any]: verbose = context.get("verbose") or False if verbose: print("\033[93mKNOWLEDGE FROM GRAPH:") - print("\n".join(rel for rel in context["synthesize_context_body"]) + "\033[0m") + print( + "\n".join(rel for rel in context["synthesize_context_body"]) + "\033[0m" + ) return context @@ -171,7 +178,9 @@ def _format_knowledge_from_query_result( for i, item in enumerate(raw_flat_rel): if i % 2 == 0: matched_str = ( - item["id"] if use_id_to_match else item["props"][self._prop_to_match] + item["id"] + if use_id_to_match + else item["props"][self._prop_to_match] ) if matched_str in node_cache: flat_rel = flat_rel[:-prior_edge_str_len] @@ -202,8 +211,12 @@ def _format_knowledge_from_query_result( def _extract_labels_from_schema(self) -> Tuple[List[str], List[str]]: schema = self._get_graph_schema() node_props_str, edge_props_str = schema.split("\n")[:2] - node_props_str = node_props_str[len("Node properties: ") :].strip("[").strip("]") - edge_props_str = edge_props_str[len("Edge properties: ") :].strip("[").strip("]") + node_props_str = ( + node_props_str[len("Node properties: ") :].strip("[").strip("]") + ) + edge_props_str = ( + edge_props_str[len("Edge properties: ") :].strip("[").strip("]") + ) node_labels = self._extract_label_names(node_props_str) edge_labels = self._extract_label_names(edge_props_str) return node_labels, edge_labels diff --git a/hugegraph-llm/src/hugegraph_llm/operators/kg_construction_task.py b/hugegraph-llm/src/hugegraph_llm/operators/kg_construction_task.py index 492d8e74..9480f243 100644 --- a/hugegraph-llm/src/hugegraph_llm/operators/kg_construction_task.py +++ b/hugegraph-llm/src/hugegraph_llm/operators/kg_construction_task.py @@ -33,7 +33,9 @@ def __init__(self, llm: BaseLLM): self.llm = llm self.result = None - def import_schema(self, from_hugegraph=None, from_extraction=None, from_user_defined=None): + def import_schema( + self, from_hugegraph=None, from_extraction=None, from_user_defined=None + ): if from_hugegraph: self.operators.append(SchemaManager(from_hugegraph)) elif from_user_defined: diff --git a/hugegraph-llm/src/hugegraph_llm/operators/llm_op/answer_synthesize.py b/hugegraph-llm/src/hugegraph_llm/operators/llm_op/answer_synthesize.py index 62164941..d8d15c23 100644 --- a/hugegraph-llm/src/hugegraph_llm/operators/llm_op/answer_synthesize.py +++ b/hugegraph-llm/src/hugegraph_llm/operators/llm_op/answer_synthesize.py @@ -43,7 +43,9 @@ def __init__( context_tail: Optional[str] = None, ): self._llm = llm - self._prompt_template = prompt_template or DEFAULT_ANSWER_SYNTHESIZE_TEMPLATE_TMPL + self._prompt_template = ( + prompt_template or DEFAULT_ANSWER_SYNTHESIZE_TEMPLATE_TMPL + ) self._question = question self._context_body = context_body self._context_head = context_head @@ -69,16 +71,22 @@ def run(self, context: Dict[str, Any]) -> Dict[str, Any]: elif isinstance(self._context_body, (list, set)): context_body_str = "\n".join(line for line in self._context_body) elif isinstance(self._context_body, dict): - context_body_str = "\n".join(f"{k}: {v}" for k, v in self._context_body.items()) + context_body_str = "\n".join( + f"{k}: {v}" for k, v in self._context_body.items() + ) else: context_body_str = str(self._context_body) - context_head_str = context.get("synthesize_context_head") or self._context_head or "" - context_tail_str = context.get("synthesize_context_tail") or self._context_tail or "" - - context_str = (f"{context_head_str}\n" f"{context_body_str}\n" f"{context_tail_str}").strip( - "\n" + context_head_str = ( + context.get("synthesize_context_head") or self._context_head or "" ) + context_tail_str = ( + context.get("synthesize_context_tail") or self._context_tail or "" + ) + + context_str = ( + f"{context_head_str}\n" f"{context_body_str}\n" f"{context_tail_str}" + ).strip("\n") prompt = self._prompt_template.format( context_str=context_str, diff --git a/hugegraph-llm/src/hugegraph_llm/operators/llm_op/info_extract.py b/hugegraph-llm/src/hugegraph_llm/operators/llm_op/info_extract.py index ab35da2b..75f47926 100644 --- a/hugegraph-llm/src/hugegraph_llm/operators/llm_op/info_extract.py +++ b/hugegraph-llm/src/hugegraph_llm/operators/llm_op/info_extract.py @@ -45,7 +45,9 @@ def generate_extract_triple_prompt(text, schema=None) -> str: The extracted text is: {text}""" -def fit_token_space_by_split_text(llm: BaseLLM, text: str, prompt_token: int) -> List[str]: +def fit_token_space_by_split_text( + llm: BaseLLM, text: str, prompt_token: int +) -> List[str]: max_length = 500 allowed_tokens = llm.max_allowed_token_length() - prompt_token chunked_data = [text[i : i + max_length] for i in range(0, len(text), max_length)] @@ -53,7 +55,8 @@ def fit_token_space_by_split_text(llm: BaseLLM, text: str, prompt_token: int) -> current_chunk = "" for chunk in chunked_data: if ( - int(llm.num_tokens_from_string(current_chunk)) + int(llm.num_tokens_from_string(chunk)) + int(llm.num_tokens_from_string(current_chunk)) + + int(llm.num_tokens_from_string(chunk)) < allowed_tokens ): current_chunk += chunk @@ -84,13 +87,19 @@ def extract_triples_by_regex_with_schema(schema, text, graph): for vertex in schema["vertices"]: if vertex["vertex_label"] == label and p in vertex["properties"]: if (s, label) not in vertices_dict: - vertices_dict[(s, label)] = {"name": s, "label": label, "properties": {p: o}} + vertices_dict[(s, label)] = { + "name": s, + "label": label, + "properties": {p: o}, + } else: vertices_dict[(s, label)]["properties"].update({p: o}) break for edge in schema["edges"]: if edge["edge_label"] == label: - graph["edges"].append({"start": s, "end": o, "type": label, "properties": {}}) + graph["edges"].append( + {"start": s, "end": o, "type": label, "properties": {}} + ) break graph["vertices"] = list(vertices_dict.values()) @@ -105,13 +114,19 @@ def __init__( self.text = text def run(self, schema=None) -> Dict[str, List[Any]]: - prompt_token = self.llm.num_tokens_from_string(generate_extract_triple_prompt("", schema)) + prompt_token = self.llm.num_tokens_from_string( + generate_extract_triple_prompt("", schema) + ) chunked_text = fit_token_space_by_split_text( llm=self.llm, text=self.text, prompt_token=int(prompt_token) ) - result = {"vertices": [], "edges": [], "schema": schema} if schema else {"triples": []} + result = ( + {"vertices": [], "edges": [], "schema": schema} + if schema + else {"triples": []} + ) for chunk in chunked_text: proceeded_chunk = self.extract_triples_by_llm(schema, chunk) print(f"[LLM] input: {chunk} \n output:{proceeded_chunk}") diff --git a/hugegraph-llm/src/hugegraph_llm/operators/llm_op/keyword_extract.py b/hugegraph-llm/src/hugegraph_llm/operators/llm_op/keyword_extract.py index 54d698ce..f75d9191 100644 --- a/hugegraph-llm/src/hugegraph_llm/operators/llm_op/keyword_extract.py +++ b/hugegraph-llm/src/hugegraph_llm/operators/llm_op/keyword_extract.py @@ -53,7 +53,9 @@ def __init__( self._query = text self._language = language.lower() self._max_keywords = max_keywords - self._extract_template = extract_template or DEFAULT_KEYWORDS_EXTRACT_TEMPLATE_TMPL + self._extract_template = ( + extract_template or DEFAULT_KEYWORDS_EXTRACT_TEMPLATE_TMPL + ) self._expand_template = expand_template or DEFAULT_KEYWORDS_EXPAND_TEMPLATE_TMPL def run(self, context: Dict[str, Any]) -> Dict[str, Any]: @@ -132,7 +134,11 @@ def _extract_keywords_from_response( sub_tokens = re.findall(r"\w+", token) if len(sub_tokens) > 1: results.update( - {w for w in sub_tokens if w not in NLTKHelper().stopwords(lang=self._language)} + { + w + for w in sub_tokens + if w not in NLTKHelper().stopwords(lang=self._language) + } ) return results diff --git a/hugegraph-llm/src/hugegraph_llm/operators/llm_op/unstructured_data_utils.py b/hugegraph-llm/src/hugegraph_llm/operators/llm_op/unstructured_data_utils.py index 38eabb16..5164ada7 100644 --- a/hugegraph-llm/src/hugegraph_llm/operators/llm_op/unstructured_data_utils.py +++ b/hugegraph-llm/src/hugegraph_llm/operators/llm_op/unstructured_data_utils.py @@ -107,7 +107,9 @@ def nodes_schemas_text_to_list_of_dict(nodes_schemas): properties = json.loads(properties) except json.decoder.JSONDecodeError: properties = {} - result.append({"label": label, "primary_key": primary_key, "properties": properties}) + result.append( + {"label": label, "primary_key": primary_key, "properties": properties} + ) return result @@ -119,7 +121,9 @@ def relationships_schemas_text_to_list_of_dict(relationships_schemas): continue start = relationships_schema_list[0].strip().replace('"', "") end = relationships_schema_list[2].strip().replace('"', "") - relationships_schema_type = relationships_schema_list[1].strip().replace('"', "") + relationships_schema_type = ( + relationships_schema_list[1].strip().replace('"', "") + ) properties = re.search(JSON_REGEX, relationships_schema) if properties is None: diff --git a/hugegraph-llm/src/hugegraph_llm/utils/config.py b/hugegraph-llm/src/hugegraph_llm/utils/config.py index 5a205de4..55561bc7 100644 --- a/hugegraph-llm/src/hugegraph_llm/utils/config.py +++ b/hugegraph-llm/src/hugegraph_llm/utils/config.py @@ -31,8 +31,12 @@ def __init__(self, config_file=None, section=None): def init_config_file(self, config_file): if config_file is None: - root_dir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) - config_file = os.path.join(root_dir, "hugegraph_llm", "config", "config.ini") + root_dir = os.path.dirname( + os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + ) + config_file = os.path.join( + root_dir, "hugegraph_llm", "config", "config.ini" + ) if not os.path.exists(config_file): config = configparser.ConfigParser() diff --git a/hugegraph-llm/src/hugegraph_llm/utils/gradio_demo.py b/hugegraph-llm/src/hugegraph_llm/utils/gradio_demo.py index a5df0d7b..92447a73 100644 --- a/hugegraph-llm/src/hugegraph_llm/utils/gradio_demo.py +++ b/hugegraph-llm/src/hugegraph_llm/utils/gradio_demo.py @@ -40,21 +40,33 @@ def init_hg_test_data(): schema.vertexLabel("Person").properties( "name", "birthDate" ).useCustomizeStringId().ifNotExist().create() - schema.vertexLabel("Movie").properties("name").useCustomizeStringId().ifNotExist().create() - schema.edgeLabel("ActedIn").sourceLabel("Person").targetLabel("Movie").ifNotExist().create() + schema.vertexLabel("Movie").properties( + "name" + ).useCustomizeStringId().ifNotExist().create() + schema.edgeLabel("ActedIn").sourceLabel("Person").targetLabel( + "Movie" + ).ifNotExist().create() - schema.indexLabel("PersonByName").onV("Person").by("name").secondary().ifNotExist().create() - schema.indexLabel("MovieByName").onV("Movie").by("name").secondary().ifNotExist().create() + schema.indexLabel("PersonByName").onV("Person").by( + "name" + ).secondary().ifNotExist().create() + schema.indexLabel("MovieByName").onV("Movie").by( + "name" + ).secondary().ifNotExist().create() graph = client.graph() - graph.addVertex("Person", {"name": "Al Pacino", "birthDate": "1940-04-25"}, id="Al Pacino") + graph.addVertex( + "Person", {"name": "Al Pacino", "birthDate": "1940-04-25"}, id="Al Pacino" + ) graph.addVertex( "Person", {"name": "Robert De Niro", "birthDate": "1943-08-17"}, id="Robert De Niro", ) graph.addVertex("Movie", {"name": "The Godfather"}, id="The Godfather") - graph.addVertex("Movie", {"name": "The Godfather Part II"}, id="The Godfather Part II") + graph.addVertex( + "Movie", {"name": "The Godfather Part II"}, id="The Godfather Part II" + ) graph.addVertex( "Movie", {"name": "The Godfather Coda The Death of Michael Corleone"}, @@ -63,7 +75,9 @@ def init_hg_test_data(): graph.addEdge("ActedIn", "Al Pacino", "The Godfather", {}) graph.addEdge("ActedIn", "Al Pacino", "The Godfather Part II", {}) - graph.addEdge("ActedIn", "Al Pacino", "The Godfather Coda The Death of Michael Corleone", {}) + graph.addEdge( + "ActedIn", "Al Pacino", "The Godfather Coda The Death of Michael Corleone", {} + ) graph.addEdge("ActedIn", "Robert De Niro", "The Godfather Part II", {}) schema.getSchema() graph.close() @@ -122,13 +136,27 @@ def get_hg_client(): def init_config( - ip, port, user, pwd, graph, type, api_key, secret_key, llm_url, model_name, max_token + ip, + port, + user, + pwd, + graph, + type, + api_key, + secret_key, + llm_url, + model_name, + max_token, ): - root_dir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + root_dir = os.path.dirname( + os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + ) config_file = os.path.join(root_dir, "hugegraph_llm", "config", "config.ini") config = Config(config_file=config_file, section=Constants.HUGEGRAPH_CONFIG) - config.update_config({"ip": ip, "port": port, "user": user, "pwd": pwd, "graph": graph}) + config.update_config( + {"ip": ip, "port": port, "user": user, "pwd": pwd, "graph": graph} + ) config = Config(config_file=config_file, section="llm") config.update_config( @@ -170,7 +198,7 @@ def init_config( gr.Textbox(value="", label="secret_key"), gr.Textbox( value="https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/" - "chat/completions_pro?access_token=", + "chat/completions_pro?access_token=", label="llm_url", ), gr.Textbox(value="wenxin", label="model_name"), @@ -179,7 +207,9 @@ def init_config( with gr.Row(): out = gr.Textbox(label="Output") btn = gr.Button("Initialize configs") - btn.click(fn=init_config, inputs=inp + inp2, outputs=out) # pylint: disable=no-member + btn.click( + fn=init_config, inputs=inp + inp2, outputs=out + ) # pylint: disable=no-member gr.Markdown( """## 1. build knowledge graph @@ -247,12 +277,14 @@ def init_config( inp = [] out = gr.Textbox(label="Output") btn = gr.Button("Initialize HugeGraph test data") - btn.click(fn=init_hg_test_data, inputs=inp, outputs=out) # pylint: disable=no-member + # pylint: disable=no-member + btn.click(fn=init_hg_test_data, inputs=inp, outputs=out) with gr.Row(): inp = gr.Textbox(value="g.V().limit(10)", label="Gremlin query") out = gr.Textbox(label="Output") btn = gr.Button("Run gremlin query on HugeGraph") - btn.click(fn=run_gremlin_query, inputs=inp, outputs=out) # pylint: disable=no-member + # pylint: disable=no-member + btn.click(fn=run_gremlin_query, inputs=inp, outputs=out) app = gr.mount_gradio_app(app, hugegraph_llm, path="/") uvicorn.run(app, host="0.0.0.0", port=8001) diff --git a/hugegraph-llm/src/tests/operators/llm_op/test_disambiguate_data.py b/hugegraph-llm/src/tests/operators/llm_op/test_disambiguate_data.py index 04ee4214..cf143239 100644 --- a/hugegraph-llm/src/tests/operators/llm_op/test_disambiguate_data.py +++ b/hugegraph-llm/src/tests/operators/llm_op/test_disambiguate_data.py @@ -39,7 +39,11 @@ def setUp(self): { "name": "Alice", "label": "person", - "properties": {"name": "Alice", "age": "25", "occupation": "lawyer"}, + "properties": { + "name": "Alice", + "age": "25", + "occupation": "lawyer", + }, }, { "name": "Bob", @@ -57,10 +61,15 @@ def setUp(self): "properties": {"name": "www.bob.com", "url": "www.bob.com"}, }, ], - "edges": [{"start": "Alice", "end": "Bob", "type": "roommate", "properties": {}}], + "edges": [ + {"start": "Alice", "end": "Bob", "type": "roommate", "properties": {}} + ], "schema": { "vertices": [ - {"vertex_label": "person", "properties": ["name", "age", "occupation"]}, + { + "vertex_label": "person", + "properties": ["name", "age", "occupation"], + }, {"vertex_label": "webpage", "properties": ["name", "url"]}, ], "edges": [ diff --git a/hugegraph-llm/src/tests/operators/llm_op/test_info_extract.py b/hugegraph-llm/src/tests/operators/llm_op/test_info_extract.py index cd84521e..ad016999 100644 --- a/hugegraph-llm/src/tests/operators/llm_op/test_info_extract.py +++ b/hugegraph-llm/src/tests/operators/llm_op/test_info_extract.py @@ -82,7 +82,11 @@ def test_extract_by_regex_with_schema(self): { "name": "Alice", "label": "person", - "properties": {"name": "Alice", "age": "25", "occupation": "lawyer"}, + "properties": { + "name": "Alice", + "age": "25", + "occupation": "lawyer", + }, }, { "name": "Bob", @@ -100,10 +104,20 @@ def test_extract_by_regex_with_schema(self): "properties": {"name": "www.bob.com", "url": "www.bob.com"}, }, ], - "edges": [{"start": "Alice", "end": "Bob", "type": "roommate", "properties": {}}], + "edges": [ + { + "start": "Alice", + "end": "Bob", + "type": "roommate", + "properties": {}, + } + ], "schema": { "vertices": [ - {"vertex_label": "person", "properties": ["name", "age", "occupation"]}, + { + "vertex_label": "person", + "properties": ["name", "age", "occupation"], + }, {"vertex_label": "webpage", "properties": ["name", "url"]}, ], "edges": [ diff --git a/hugegraph-python-client/src/pyhugegraph/api/auth.py b/hugegraph-python-client/src/pyhugegraph/api/auth.py index 0ce11036..453079c0 100644 --- a/hugegraph-python-client/src/pyhugegraph/api/auth.py +++ b/hugegraph-python-client/src/pyhugegraph/api/auth.py @@ -272,7 +272,9 @@ def delete_target(self, target_id): ) check_if_success(response, NotFoundError(response.content)) - def update_target(self, target_id, target_name, target_graph, target_url, target_resources): + def update_target( + self, target_id, target_name, target_graph, target_url, target_resources + ): url = f"{self._host}/graphs/{self._graph_name}/auth/targets/{target_id}" data = { "target_name": target_name, diff --git a/hugegraph-python-client/src/pyhugegraph/api/graph.py b/hugegraph-python-client/src/pyhugegraph/api/graph.py index 959e6b03..7153ceb3 100644 --- a/hugegraph-python-client/src/pyhugegraph/api/graph.py +++ b/hugegraph-python-client/src/pyhugegraph/api/graph.py @@ -105,9 +105,7 @@ def appendVertex(self, vertex_id, properties): return None def eliminateVertex(self, vertex_id, properties): - url = ( - f'{self._host}/graphs/{self._graph_name}/graph/vertices/"{vertex_id}"?action=eliminate' - ) + url = f'{self._host}/graphs/{self._graph_name}/graph/vertices/"{vertex_id}"?action=eliminate' data = {"properties": properties} response = self.__session.put( @@ -130,7 +128,9 @@ def getVertexById(self, vertex_id): response = self.__session.get( url, auth=self._auth, headers=self._headers, timeout=self._timeout ) - if check_if_success(response, NotFoundError(f"Vertex not found: {str(response.content)}")): + if check_if_success( + response, NotFoundError(f"Vertex not found: {str(response.content)}") + ): res = VertexData(json.loads(response.content)) return res return None @@ -151,7 +151,9 @@ def getVertexByPage(self, label, limit, page=None, properties=None): response = self.__session.get( url, auth=self._auth, headers=self._headers, timeout=self._timeout ) - if check_if_success(response, NotFoundError(f"Vertex not found: {str(response.content)}")): + if check_if_success( + response, NotFoundError(f"Vertex not found: {str(response.content)}") + ): res = [] for item in json.loads(response.content)["vertices"]: res.append(VertexData(item)) @@ -177,7 +179,9 @@ def getVertexByCondition(self, label="", limit=0, page=None, properties=None): response = self.__session.get( url, auth=self._auth, headers=self._headers, timeout=self._timeout ) - if check_if_success(response, NotFoundError(f"Vertex not found: {str(response.content)}")): + if check_if_success( + response, NotFoundError(f"Vertex not found: {str(response.content)}") + ): res = [] for item in json.loads(response.content)["vertices"]: res.append(VertexData(item)) @@ -211,7 +215,9 @@ def addEdge(self, edge_label, out_id, in_id, properties): headers=self._headers, timeout=self._timeout, ) - if check_if_success(response, CreateError(f"created edge failed: {str(response.content)}")): + if check_if_success( + response, CreateError(f"created edge failed: {str(response.content)}") + ): res = EdgeData(json.loads(response.content)) return res return None @@ -258,7 +264,9 @@ def appendEdge(self, edge_id, properties): headers=self._headers, timeout=self._timeout, ) - if check_if_success(response, UpdateError(f"append edge failed: {str(response.content)}")): + if check_if_success( + response, UpdateError(f"append edge failed: {str(response.content)}") + ): res = EdgeData(json.loads(response.content)) return res return None @@ -287,7 +295,9 @@ def getEdgeById(self, edge_id): response = self.__session.get( url, auth=self._auth, headers=self._headers, timeout=self._timeout ) - if check_if_success(response, NotFoundError(f"not found edge: {str(response.content)}")): + if check_if_success( + response, NotFoundError(f"not found edge: {str(response.content)}") + ): res = EdgeData(json.loads(response.content)) return res return None @@ -323,7 +333,9 @@ def getEdgeByPage( response = self.__session.get( url, auth=self._auth, headers=self._headers, timeout=self._timeout ) - if check_if_success(response, NotFoundError(f"not found edges: {str(response.content)}")): + if check_if_success( + response, NotFoundError(f"not found edges: {str(response.content)}") + ): res = [] for item in json.loads(response.content)["edges"]: res.append(EdgeData(item)) @@ -336,7 +348,9 @@ def removeEdgeById(self, edge_id): response = self.__session.delete( url, auth=self._auth, headers=self._headers, timeout=self._timeout ) - if check_if_success(response, RemoveError(f"remove edge failed: {str(response.content)}")): + if check_if_success( + response, RemoveError(f"remove edge failed: {str(response.content)}") + ): return response.content return None diff --git a/hugegraph-python-client/src/pyhugegraph/api/schema_manage/edge_label.py b/hugegraph-python-client/src/pyhugegraph/api/schema_manage/edge_label.py index f694a492..76fb4f3b 100644 --- a/hugegraph-python-client/src/pyhugegraph/api/schema_manage/edge_label.py +++ b/hugegraph-python-client/src/pyhugegraph/api/schema_manage/edge_label.py @@ -147,9 +147,7 @@ def append(self): if key in dic: data[key] = dic[key] - url = ( - f'{self._host}/graphs/{self._graph_name}/schema/edgelabels/{data["name"]}?action=append' - ) + url = f'{self._host}/graphs/{self._graph_name}/schema/edgelabels/{data["name"]}?action=append' response = self.__session.put( url, data=json.dumps(data), auth=self._auth, headers=self._headers ) diff --git a/hugegraph-python-client/src/pyhugegraph/api/schema_manage/property_key.py b/hugegraph-python-client/src/pyhugegraph/api/schema_manage/property_key.py index c0a3af48..f22781c1 100644 --- a/hugegraph-python-client/src/pyhugegraph/api/schema_manage/property_key.py +++ b/hugegraph-python-client/src/pyhugegraph/api/schema_manage/property_key.py @@ -179,7 +179,9 @@ def eliminate(self): @decorator_params def remove(self): dic = self._parameter_holder.get_dic() - url = f'{self._host}/graphs/{self._graph_name}/schema/propertykeys/{dic["name"]}' + url = ( + f'{self._host}/graphs/{self._graph_name}/schema/propertykeys/{dic["name"]}' + ) response = self.__session.delete(url) self.clean_parameter_holder() if check_if_success( diff --git a/hugegraph-python-client/src/pyhugegraph/api/traverser.py b/hugegraph-python-client/src/pyhugegraph/api/traverser.py index b88ea741..f2aea7c8 100644 --- a/hugegraph-python-client/src/pyhugegraph/api/traverser.py +++ b/hugegraph-python-client/src/pyhugegraph/api/traverser.py @@ -203,7 +203,9 @@ def customized_paths( return response.json() return {} - def template_paths(self, sources, targets, steps, capacity=10000, limit=10, with_vertex=True): + def template_paths( + self, sources, targets, steps, capacity=10000, limit=10, with_vertex=True + ): url = f"{self.url}/templatepaths" data = { "sources": sources, @@ -240,7 +242,13 @@ def crosspoints(self, source_id, target_id, max_depth): return {} def customized_crosspoints( - self, sources, path_patterns, with_path=True, with_vertex=True, capacity=-1, limit=-1 + self, + sources, + path_patterns, + with_path=True, + with_vertex=True, + capacity=-1, + limit=-1, ): url = f"{self.url}/customizedcrosspoints" data = { diff --git a/hugegraph-python-client/src/pyhugegraph/example/hugegraph_example.py b/hugegraph-python-client/src/pyhugegraph/example/hugegraph_example.py index 27d02463..d58190e2 100644 --- a/hugegraph-python-client/src/pyhugegraph/example/hugegraph_example.py +++ b/hugegraph-python-client/src/pyhugegraph/example/hugegraph_example.py @@ -18,19 +18,23 @@ from pyhugegraph.client import PyHugeClient if __name__ == "__main__": - client = PyHugeClient("127.0.0.1", "8080", user="admin", pwd="admin", graph="hugegraph") + client = PyHugeClient( + "127.0.0.1", "8080", user="admin", pwd="admin", graph="hugegraph" + ) """schema""" schema = client.schema() schema.propertyKey("name").asText().ifNotExist().create() schema.propertyKey("birthDate").asText().ifNotExist().create() - schema.vertexLabel("Person").properties("name", "birthDate").usePrimaryKeyId().primaryKeys( - "name" - ).ifNotExist().create() + schema.vertexLabel("Person").properties( + "name", "birthDate" + ).usePrimaryKeyId().primaryKeys("name").ifNotExist().create() schema.vertexLabel("Movie").properties("name").usePrimaryKeyId().primaryKeys( "name" ).ifNotExist().create() - schema.edgeLabel("ActedIn").sourceLabel("Person").targetLabel("Movie").ifNotExist().create() + schema.edgeLabel("ActedIn").sourceLabel("Person").targetLabel( + "Movie" + ).ifNotExist().create() print(schema.getVertexLabels()) print(schema.getEdgeLabels()) @@ -43,7 +47,9 @@ p2 = g.addVertex("Person", {"name": "Robert De Niro", "birthDate": "1943-08-17"}) m1 = g.addVertex("Movie", {"name": "The Godfather"}) m2 = g.addVertex("Movie", {"name": "The Godfather Part II"}) - m3 = g.addVertex("Movie", {"name": "The Godfather Coda The Death of Michael Corleone"}) + m3 = g.addVertex( + "Movie", {"name": "The Godfather Coda The Death of Michael Corleone"} + ) # add Edge g.addEdge("ActedIn", p1.id, m1.id, {}) diff --git a/hugegraph-python-client/src/pyhugegraph/example/hugegraph_test.py b/hugegraph-python-client/src/pyhugegraph/example/hugegraph_test.py index 8b47f512..739862da 100644 --- a/hugegraph-python-client/src/pyhugegraph/example/hugegraph_test.py +++ b/hugegraph-python-client/src/pyhugegraph/example/hugegraph_test.py @@ -41,7 +41,9 @@ def __init__( self.address = address self.port = port self.graph = graph - self.client = PyHugeClient(address, port, user=username, pwd=password, graph=graph) + self.client = PyHugeClient( + address, port, user=username, pwd=password, graph=graph + ) self.schema = "" def exec(self, query) -> str: diff --git a/hugegraph-python-client/src/pyhugegraph/structure/property_key_data.py b/hugegraph-python-client/src/pyhugegraph/structure/property_key_data.py index 9b7b50c3..b4b170cc 100644 --- a/hugegraph-python-client/src/pyhugegraph/structure/property_key_data.py +++ b/hugegraph-python-client/src/pyhugegraph/structure/property_key_data.py @@ -45,7 +45,5 @@ def userdata(self): return self.__user_data def __repr__(self): - res = ( - f"name: {self.__name}, cardinality: {self.__cardinality}, data_type: {self.__data_type}" - ) + res = f"name: {self.__name}, cardinality: {self.__cardinality}, data_type: {self.__data_type}" return res diff --git a/hugegraph-python-client/src/pyhugegraph/utils/util.py b/hugegraph-python-client/src/pyhugegraph/utils/util.py index e07dec3d..d01a6306 100644 --- a/hugegraph-python-client/src/pyhugegraph/utils/util.py +++ b/hugegraph-python-client/src/pyhugegraph/utils/util.py @@ -43,7 +43,9 @@ def check_if_authorized(response): def check_if_success(response, error=None): - if (not str(response.status_code).startswith("20")) and check_if_authorized(response): + if (not str(response.status_code).startswith("20")) and check_if_authorized( + response + ): if error is None: error = NotFoundError(response.content) raise error diff --git a/hugegraph-python-client/src/tests/api/test_auth.py b/hugegraph-python-client/src/tests/api/test_auth.py index 10e6bad7..d2d30cf2 100644 --- a/hugegraph-python-client/src/tests/api/test_auth.py +++ b/hugegraph-python-client/src/tests/api/test_auth.py @@ -98,7 +98,9 @@ def test_group_operations(self): self.assertEqual(group["group_name"], "test_group") # Modify the group - group = self.auth.modify_group(group["id"], group_description="test_description") + group = self.auth.modify_group( + group["id"], group_description="test_description" + ) self.assertEqual(group["group_description"], "test_description") # Delete the group @@ -133,7 +135,9 @@ def test_target_operations(self): [{"type": "VERTEX", "label": "person", "properties": {"city": "Shanghai"}}], ) # Verify the target was modified - self.assertEqual(target["target_resources"][0]["properties"]["city"], "Shanghai") + self.assertEqual( + target["target_resources"][0]["properties"]["city"], "Shanghai" + ) # Delete the target self.auth.delete_target(target["id"]) diff --git a/hugegraph-python-client/src/tests/api/test_graph.py b/hugegraph-python-client/src/tests/api/test_graph.py index 9c8aac78..d3763be4 100644 --- a/hugegraph-python-client/src/tests/api/test_graph.py +++ b/hugegraph-python-client/src/tests/api/test_graph.py @@ -39,7 +39,9 @@ def tearDownClass(cls): cls.client.clear_graph_all_data() def test_add_vertex(self): - vertex = self.graph.addVertex("person", {"name": "marko", "age": 29, "city": "Beijing"}) + vertex = self.graph.addVertex( + "person", {"name": "marko", "age": 29, "city": "Beijing"} + ) self.assertIsNotNone(vertex) def test_add_vertices(self): @@ -57,7 +59,9 @@ def test_append_vertex(self): self.assertEqual(appended_vertex.properties["city"], "Beijing") def test_eliminate_vertex(self): - vertex = self.graph.addVertex("person", {"name": "marko", "age": 29, "city": "Beijing"}) + vertex = self.graph.addVertex( + "person", {"name": "marko", "age": 29, "city": "Beijing"} + ) self.graph.eliminateVertex(vertex.id, {"city": "Beijing"}) eliminated_vertex = self.graph.getVertexById(vertex.id) self.assertIsNone(eliminated_vertex.properties.get("city")) @@ -76,7 +80,9 @@ def test_get_vertex_by_page(self): def test_get_vertex_by_condition(self): self.graph.addVertex("person", {"name": "Alice", "age": 25}) self.graph.addVertex("person", {"name": "Bob", "age": 30}) - vertices = self.graph.getVertexByCondition("person", properties={"age": "P.gt(29)"}) + vertices = self.graph.getVertexByCondition( + "person", properties={"age": "P.gt(29)"} + ) self.assertEqual(len(vertices), 1) self.assertEqual(vertices[0].properties["name"], "Bob") @@ -91,7 +97,9 @@ def test_remove_vertex_by_id(self): def test_add_edge(self): vertex1 = self.graph.addVertex("person", {"name": "Alice", "age": 20}) vertex2 = self.graph.addVertex("person", {"name": "Bob", "age": 23}) - edge = self.graph.addEdge("knows", vertex1.id, vertex2.id, {"date": "2012-01-10"}) + edge = self.graph.addEdge( + "knows", vertex1.id, vertex2.id, {"date": "2012-01-10"} + ) self.assertIsNotNone(edge) def test_add_edges(self): @@ -100,8 +108,22 @@ def test_add_edges(self): vertices = self.graph.addEdges( [ - ("knows", vertex1.id, vertex2.id, "person", "person", {"date": "2012-01-10"}), - ("knows", vertex2.id, vertex1.id, "person", "person", {"date": "2012-01-10"}), + ( + "knows", + vertex1.id, + vertex2.id, + "person", + "person", + {"date": "2012-01-10"}, + ), + ( + "knows", + vertex2.id, + vertex1.id, + "person", + "person", + {"date": "2012-01-10"}, + ), ] ) self.assertEqual(len(vertices), 2) @@ -109,14 +131,18 @@ def test_add_edges(self): def test_append_edge(self): vertex1 = self.graph.addVertex("person", {"name": "Alice", "age": 20}) vertex2 = self.graph.addVertex("person", {"name": "Bob", "age": 23}) - edge = self.graph.addEdge("knows", vertex1.id, vertex2.id, {"date": "2012-01-10"}) + edge = self.graph.addEdge( + "knows", vertex1.id, vertex2.id, {"date": "2012-01-10"} + ) appended_edge = self.graph.appendEdge(edge.id, {"city": "Beijing"}) self.assertEqual(appended_edge.properties["city"], "Beijing") def test_eliminate_edge(self): vertex1 = self.graph.addVertex("person", {"name": "Alice", "age": 20}) vertex2 = self.graph.addVertex("person", {"name": "Bob", "age": 23}) - edge = self.graph.addEdge("knows", vertex1.id, vertex2.id, {"date": "2012-01-10"}) + edge = self.graph.addEdge( + "knows", vertex1.id, vertex2.id, {"date": "2012-01-10"} + ) self.graph.eliminateEdge(edge.id, {"city": "Beijing"}) eliminated_edge = self.graph.getEdgeById(edge.id) self.assertIsNone(eliminated_edge.properties.get("city")) @@ -124,7 +150,9 @@ def test_eliminate_edge(self): def test_get_edge_by_id(self): vertex1 = self.graph.addVertex("person", {"name": "Alice", "age": 20}) vertex2 = self.graph.addVertex("person", {"name": "Bob", "age": 23}) - edge = self.graph.addEdge("knows", vertex1.id, vertex2.id, {"date": "2012-01-10"}) + edge = self.graph.addEdge( + "knows", vertex1.id, vertex2.id, {"date": "2012-01-10"} + ) retrieved_edge = self.graph.getEdgeById(edge.id) self.assertEqual(retrieved_edge.id, edge.id) @@ -139,7 +167,9 @@ def test_get_edge_by_page(self): def test_remove_edge_by_id(self): vertex1 = self.graph.addVertex("person", {"name": "Alice", "age": 20}) vertex2 = self.graph.addVertex("person", {"name": "Bob", "age": 23}) - edge = self.graph.addEdge("knows", vertex1.id, vertex2.id, {"date": "2012-01-10"}) + edge = self.graph.addEdge( + "knows", vertex1.id, vertex2.id, {"date": "2012-01-10"} + ) self.graph.removeEdgeById(edge.id) try: self.graph.getEdgeById(edge.id) @@ -155,7 +185,11 @@ def test_get_vertices_by_id(self): def test_get_edges_by_id(self): vertex1 = self.graph.addVertex("person", {"name": "Alice", "age": 20}) vertex2 = self.graph.addVertex("person", {"name": "Bob", "age": 23}) - edge1 = self.graph.addEdge("knows", vertex1.id, vertex2.id, {"date": "2012-01-10"}) - edge2 = self.graph.addEdge("knows", vertex2.id, vertex1.id, {"date": "2012-01-10"}) + edge1 = self.graph.addEdge( + "knows", vertex1.id, vertex2.id, {"date": "2012-01-10"} + ) + edge2 = self.graph.addEdge( + "knows", vertex2.id, vertex1.id, {"date": "2012-01-10"} + ) edges = self.graph.getEdgesById([edge1.id, edge2.id]) self.assertEqual(len(edges), 2) diff --git a/hugegraph-python-client/src/tests/api/test_traverser.py b/hugegraph-python-client/src/tests/api/test_traverser.py index 70c206ac..66a687f4 100644 --- a/hugegraph-python-client/src/tests/api/test_traverser.py +++ b/hugegraph-python-client/src/tests/api/test_traverser.py @@ -47,16 +47,23 @@ def tearDown(self): pass def test_traverser_operations(self): - marko = self.graph.getVertexByCondition("person", properties={"name": "marko"})[0].id - josh = self.graph.getVertexByCondition("person", properties={"name": "josh"})[0].id - ripple = self.graph.getVertexByCondition("software", properties={"name": "ripple"})[0].id + marko = self.graph.getVertexByCondition("person", properties={"name": "marko"})[ + 0 + ].id + josh = self.graph.getVertexByCondition("person", properties={"name": "josh"})[ + 0 + ].id + ripple = self.graph.getVertexByCondition( + "software", properties={"name": "ripple"} + )[0].id k_out_result = self.traverser.k_out(marko, 2) self.assertEqual(k_out_result["vertices"], ["1:peter", "2:ripple"]) k_neighbor_result = self.traverser.k_neighbor(marko, 2) self.assertEqual( - k_neighbor_result["vertices"], ["1:peter", "1:josh", "2:lop", "2:ripple", "1:vadas"] + k_neighbor_result["vertices"], + ["1:peter", "1:josh", "2:lop", "2:ripple", "1:vadas"], ) same_neighbors_result = self.traverser.same_neighbors(marko, josh) @@ -66,11 +73,14 @@ def test_traverser_operations(self): self.assertEqual(jaccard_similarity_result["jaccard_similarity"], 0.2) shortest_path_result = self.traverser.shortest_path(marko, ripple, 3) - self.assertEqual(shortest_path_result["path"], ["1:marko", "1:josh", "2:ripple"]) + self.assertEqual( + shortest_path_result["path"], ["1:marko", "1:josh", "2:ripple"] + ) all_shortest_paths_result = self.traverser.all_shortest_paths(marko, ripple, 3) self.assertEqual( - all_shortest_paths_result["paths"], [{"objects": ["1:marko", "1:josh", "2:ripple"]}] + all_shortest_paths_result["paths"], + [{"objects": ["1:marko", "1:josh", "2:ripple"]}], ) weighted_shortest_path_result = self.traverser.weighted_shortest_path( @@ -80,14 +90,19 @@ def test_traverser_operations(self): weighted_shortest_path_result["vertices"], ["1:marko", "1:josh", "2:ripple"] ) - single_source_shortest_path_result = self.traverser.single_source_shortest_path(marko, 2) + single_source_shortest_path_result = self.traverser.single_source_shortest_path( + marko, 2 + ) self.assertEqual( single_source_shortest_path_result["paths"], { "1:peter": {"weight": 2.0, "vertices": ["1:marko", "2:lop", "1:peter"]}, "1:josh": {"weight": 1.0, "vertices": ["1:marko", "1:josh"]}, "2:lop": {"weight": 1.0, "vertices": ["1:marko", "2:lop"]}, - "2:ripple": {"weight": 2.0, "vertices": ["1:marko", "1:josh", "2:ripple"]}, + "2:ripple": { + "weight": 2.0, + "vertices": ["1:marko", "1:josh", "2:ripple"], + }, "1:vadas": {"weight": 1.0, "vertices": ["1:marko", "1:vadas"]}, }, ) @@ -116,7 +131,10 @@ def test_traverser_operations(self): paths_result = self.traverser.paths(marko, josh, 2) self.assertEqual( paths_result["paths"], - [{"objects": ["1:marko", "2:lop", "1:josh"]}, {"objects": ["1:marko", "1:josh"]}], + [ + {"objects": ["1:marko", "2:lop", "1:josh"]}, + {"objects": ["1:marko", "1:josh"]}, + ], ) customized_paths_result = self.traverser.customized_paths( @@ -132,7 +150,8 @@ def test_traverser_operations(self): ], ) self.assertEqual( - customized_paths_result["paths"], [{"objects": ["1:marko", "2:lop"], "weights": [8.0]}] + customized_paths_result["paths"], + [{"objects": ["1:marko", "2:lop"], "weights": [8.0]}], ) sources = {"ids": [], "label": "person", "properties": {"name": "vadas"}} @@ -185,7 +204,9 @@ def test_traverser_operations(self): ) sources = {"ids": ["2:lop", "2:ripple"]} - path_patterns = [{"steps": [{"direction": "IN", "labels": ["created"], "max_degree": -1}]}] + path_patterns = [ + {"steps": [{"direction": "IN", "labels": ["created"], "max_degree": -1}]} + ] customized_crosspoints_result = self.traverser.customized_crosspoints( sources, path_patterns ) @@ -193,7 +214,8 @@ def test_traverser_operations(self): rings_result = self.traverser.rings(marko, 3) self.assertEqual( - rings_result["rings"], [{"objects": ["1:marko", "2:lop", "1:josh", "1:marko"]}] + rings_result["rings"], + [{"objects": ["1:marko", "2:lop", "1:josh", "1:marko"]}], ) rays_result = self.traverser.rays(marko, 2) @@ -253,7 +275,10 @@ def test_traverser_operations(self): "outVLabel": "person", "inV": "2:lop", "inVLabel": "software", - "properties": {"city": "Beijing", "date": "2016-01-10 00:00:00.000"}, + "properties": { + "city": "Beijing", + "date": "2016-01-10 00:00:00.000", + }, } ], ) diff --git a/hugegraph-python-client/src/tests/api/test_version.py b/hugegraph-python-client/src/tests/api/test_version.py index 1d6325df..44c5f376 100644 --- a/hugegraph-python-client/src/tests/api/test_version.py +++ b/hugegraph-python-client/src/tests/api/test_version.py @@ -42,7 +42,7 @@ def tearDown(self): def test_version(self): version = self.version.version() self.assertIsInstance(version, dict) - self.assertIn("version", version['versions']) - self.assertIn("core", version['versions']) - self.assertIn("gremlin", version['versions']) - self.assertIn("api", version['versions']) + self.assertIn("version", version["versions"]) + self.assertIn("core", version["versions"]) + self.assertIn("gremlin", version["versions"]) + self.assertIn("api", version["versions"]) diff --git a/hugegraph-python-client/src/tests/client_utils.py b/hugegraph-python-client/src/tests/client_utils.py index 12b35db1..b02a9f7e 100644 --- a/hugegraph-python-client/src/tests/client_utils.py +++ b/hugegraph-python-client/src/tests/client_utils.py @@ -61,9 +61,9 @@ def init_vertex_label(self): schema.vertexLabel("software").properties("name", "lang", "price").primaryKeys( "name" ).nullableKeys("price").ifNotExist().create() - schema.vertexLabel("book").useCustomizeStringId().properties("name", "price").nullableKeys( - "price" - ).ifNotExist().create() + schema.vertexLabel("book").useCustomizeStringId().properties( + "name", "price" + ).nullableKeys("price").ifNotExist().create() def init_edge_label(self): schema = self.schema @@ -72,21 +72,27 @@ def init_edge_label(self): ).multiTimes().properties("date", "city").sortKeys("date").nullableKeys( "city" ).ifNotExist().create() - schema.edgeLabel("created").sourceLabel("person").targetLabel("software").properties( - "date", "city" - ).nullableKeys("city").ifNotExist().create() + schema.edgeLabel("created").sourceLabel("person").targetLabel( + "software" + ).properties("date", "city").nullableKeys("city").ifNotExist().create() def init_index_label(self): schema = self.schema - schema.indexLabel("personByCity").onV("person").by("city").secondary().ifNotExist().create() - schema.indexLabel("personByAge").onV("person").by("age").range().ifNotExist().create() + schema.indexLabel("personByCity").onV("person").by( + "city" + ).secondary().ifNotExist().create() + schema.indexLabel("personByAge").onV("person").by( + "age" + ).range().ifNotExist().create() schema.indexLabel("softwareByPrice").onV("software").by( "price" ).range().ifNotExist().create() schema.indexLabel("softwareByLang").onV("software").by( "lang" ).secondary().ifNotExist().create() - schema.indexLabel("knowsByDate").onE("knows").by("date").secondary().ifNotExist().create() + schema.indexLabel("knowsByDate").onE("knows").by( + "date" + ).secondary().ifNotExist().create() schema.indexLabel("createdByDate").onE("created").by( "date" ).secondary().ifNotExist().create() @@ -110,17 +116,27 @@ def init_edges(self): self.graph.addEdge("knows", marko_id, vadas_id, {"date": "2012-01-10"}) self.graph.addEdge("knows", marko_id, josh_id, {"date": "2013-01-10"}) - self.graph.addEdge("created", marko_id, lop_id, {"date": "2014-01-10", "city": "Shanghai"}) - self.graph.addEdge("created", josh_id, ripple_id, {"date": "2015-01-10", "city": "Beijing"}) - self.graph.addEdge("created", josh_id, lop_id, {"date": "2016-01-10", "city": "Beijing"}) - self.graph.addEdge("created", peter_id, lop_id, {"date": "2017-01-10", "city": "Hongkong"}) + self.graph.addEdge( + "created", marko_id, lop_id, {"date": "2014-01-10", "city": "Shanghai"} + ) + self.graph.addEdge( + "created", josh_id, ripple_id, {"date": "2015-01-10", "city": "Beijing"} + ) + self.graph.addEdge( + "created", josh_id, lop_id, {"date": "2016-01-10", "city": "Beijing"} + ) + self.graph.addEdge( + "created", peter_id, lop_id, {"date": "2017-01-10", "city": "Hongkong"} + ) def _get_vertex_id(self, label, properties): res = self._get_vertex(label, properties) return res.id def _get_vertex(self, label, properties): - lst = self.graph.getVertexByCondition(label=label, limit=1, properties=properties) + lst = self.graph.getVertexByCondition( + label=label, limit=1, properties=properties + ) assert 1 == len(lst), "Can't find vertex." return lst[0]