Code similarity detection method, device, equipment, medium and product
By combining the graph structure of the code project with the text content, the accuracy problem of code similarity detection in the existing technology is solved, and efficient and accurate similarity detection of code projects is achieved, which can identify plagiarism behavior such as complex refactoring and variable renaming.
Patent Information
- Application Number
- CN202611093978.6
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2026-07-22
- Publication Date
- 2026-11-24
AI Technical Summary
Existing technologies cannot accurately detect the similarity of code projects, especially when faced with obfuscation techniques such as code refactoring and variable renaming, making it difficult to identify plagiarism across files or modules.
By constructing the graph structure information of the code project, combining it with the code text content, calculating structural similarity and text similarity, and fusing the two to obtain a comprehensive similarity, the graph structure is used to capture project-level dependencies, and the detection accuracy is improved by weighted summation.
It achieves accurate similarity detection of code projects, can identify obfuscation techniques such as variable renaming and format adjustment, effectively detects plagiarism across files and modules, reduces false alarm rate, and improves the accuracy and reliability of detection results.
Smart Images

Figure CN123157264A_ABST
Abstract
Description
Technical Field
[0001] This application relates to the field of financial technology or other related fields, and in particular to a method, apparatus, device, medium and product for detecting code similarity. Background Technology
[0002] Code similarity detection is a key technology for ensuring code originality, preventing infringement, and maintaining compliance within the open-source ecosystem. As software engineering scales up and the demand for code reuse increases, developers often circumvent traditional detection methods by modifying code structure, variable naming, or refactoring. For example, in the fintech sector, if the core transaction systems or risk control models of banks or financial institutions involve unauthorized use of open-source components, it could lead to serious risks and disputes.
[0003] In related technologies, code similarity detection typically employs analysis methods based on code text features or abstract syntax tree structures to compare the similarity of source code.
[0004] However, the code similarity detection methods in related technologies cannot accurately detect the similarity of code projects. Summary of the Invention
[0005] This application provides a method, apparatus, device, medium, and product for detecting code similarity, in order to solve the technical problem that code similarity detection methods in related technologies cannot accurately detect the similarity of code projects.
[0006] In a first aspect, embodiments of this application provide a method for detecting code similarity, comprising:
[0007] Obtain the set of code project files to be compared; wherein, the set of code project files to be compared includes any two code project files;
[0008] The code project file is parsed to obtain the corresponding graph structure information. The graph structure information includes nodes and edges. Nodes are used to represent programming elements in the code project file, and edges are used to represent logical relationships in the code project file.
[0009] Generate the corresponding code graph based on the graph structure information;
[0010] Calculate the first similarity score based on the code graph;
[0011] Determine the code text based on the code project files;
[0012] Calculate the second similarity based on the code text;
[0013] Calculate the overall similarity between any two code project files based on the first and second similarity scores.
[0014] In this embodiment of the application, when comparing code projects, a structural graph of the code project files is first constructed to achieve a first similarity comparison. Then, combined with the text content of the code project files, a second similarity comparison is performed. The first and second similarities are then fused to obtain the final similarity detection result. This embodiment of the application achieves a comprehensive similarity evaluation of code projects from two orthogonal directions: structural and textual dimensions, by simultaneously constructing a structural graph of the code project and extracting the code text content. The structural graph can capture the project-level dependencies between classes and modules, effectively detecting cross-file and cross-module code plagiarism. Through dual-dimensional fusion, the accuracy of similarity detection for code projects is improved.
[0015] In one possible embodiment, the code project file is parsed to obtain the corresponding graph structure information, including:
[0016] The code project file is parsed to extract multiple programming elements, and corresponding nodes are created based on these programming elements.
[0017] Extract the logical relationships between programming elements in the code project file;
[0018] Based on the logical relationships, establish corresponding edges between the nodes.
[0019] In this embodiment, the code entities scattered in various source files and their cross-file relationships are organized into a graph structure, so that subsequent structural similarity calculations can be performed based on a complete project-level dependency graph. This provides a reliable data foundation for accurately assessing the similarity of two code projects at the macro-level organizational structure, and provides a graph structure extraction method specifically for code projects, further improving the accuracy of similarity detection.
[0020] In one possible embodiment, the nodes include class nodes, interface nodes, variable nodes, function / method nodes, and instance nodes, which correspond to programming elements respectively;
[0021] Logical relationships include multiple ones such as instantiation relationship, containment relationship, inheritance relationship, access relationship and invocation relationship.
[0022] This application's embodiments construct a graph model that fully represents the structure of an object-oriented program engineering project by defining nodes specifically as class nodes, interface nodes, variable nodes, function / method nodes, and instance nodes, and edges specifically as instantiation relationships, inclusion relationships, inheritance relationships, access relationships, and invocation relationships. This graph model covers the core programming elements in the code project and their core semantic relationships, breaking through the limitations of traditional abstract syntax trees that only focus on the syntax structure of a single file. It can depict high-level organizational structure information across classes, files, and modules, further improving the accuracy of similarity detection.
[0023] In one possible embodiment, corresponding edges are established between nodes according to logical relationships, including at least one of the following:
[0024] Establish corresponding edges between class nodes and instance nodes that have an instantiation relationship;
[0025] Establish corresponding edges between class nodes and variable nodes and / or function nodes that have an inclusion relationship;
[0026] Establish corresponding edges between class nodes that have inheritance relationships;
[0027] Establish corresponding edges between interface nodes and class nodes that have access relationships;
[0028] Establish corresponding edges between function nodes, instance nodes, and function nodes and variable nodes that have a calling relationship.
[0029] Here, this application embodiment clarifies the edge construction method corresponding to various logical relationships in the code project in the graph, making the construction of the code graph deterministic and repeatable. The call relationship covers five specific subtypes: between functions, between instances and functions, between instances and variables, between functions and instances, and between functions and variables. It can finely depict the multi-directional transmission paths of data flow and control flow in the code project. For code that has undergone refactoring such as method extraction and interface abstraction, although the text content may change significantly, its core call dependency relationship and inheritance hierarchy are usually preserved, which can effectively detect plagiarized code after such deep refactoring.
[0030] In one possible embodiment, calculating a first similarity based on the code graph includes:
[0031] The code graph is standardized to obtain a standardized graph;
[0032] Construct the adjacency tensor based on the standardized graph;
[0033] The adjacency tensor is mapped to obtain the mapping result;
[0034] The first similarity is calculated based on the overlap of the mapping results.
[0035] This application's embodiments utilize an adjacency tensor construction and mapping method for graph similarity calculation. By organizing different edge types as different layers of tensors, it can naturally integrate various semantic relationships such as inheritance, invocation, and instantiation for comparison within the same similarity measurement framework. Through tensor mapping, graph structure similarity calculation is transformed into overlap calculation in vector space, reducing computational complexity and improving the efficiency of similarity detection.
[0036] In one possible embodiment, calculating the second similarity based on the code text includes:
[0037] The code text is preprocessed to obtain preprocessed text; the preprocessing includes removing comments and / or normalizing identifiers.
[0038] Based on the preprocessed text, text similarity is calculated to obtain the second similarity score.
[0039] This application's embodiments eliminate interference from non-semantic factors such as code formatting, comment content, and variable naming styles in text similarity calculations through preprocessing operations such as removing comments and standardizing identifiers. This allows text comparison to focus more on the logical semantic features of the code. After preprocessing, even if two code projects use completely different variable naming styles or different commenting habits, their text-level similarity can still be accurately assessed based on standardized lexical sequences. This effectively addresses common plagiarism obfuscation techniques such as variable renaming and formatting adjustments, improving the accuracy of semantic detection of code projects and further enhancing the accuracy of code project detection.
[0040] In one possible embodiment, the comprehensive similarity of any two code project files is calculated based on a first similarity and a second similarity, including:
[0041] Obtain weight information; wherein, the weight information includes a first weight and a second weight, and the sum of the first weight and the second weight is 1;
[0042] The first similarity and the second similarity are weighted according to the first weight and the second weight to obtain the comprehensive similarity.
[0043] In this embodiment, graph similarity and text similarity are fused using a weighted summation method, achieving synergistic complementarity between structural and textual information in similarity determination. This fusion method is simple to calculate and easy to implement, improving the efficiency and accuracy of similarity detection.
[0044] In one possible embodiment, obtaining weight information includes:
[0045] Obtain the application scenario type corresponding to the set of code project files to be compared;
[0046] The weight information is determined based on the application scenario type and the pre-defined correspondence between the application scenario type and the weight information.
[0047] Here, the embodiments of this application automatically determine the weight information according to the application scenario type, which further improves the intelligence level and scenario adaptability of the solution. Moreover, users in different usage scenarios do not need to manually adjust the weight parameters to obtain similarity evaluation results that are suitable for the current detection target. This realizes the automatic adaptation of similarity detection strategy, which can adapt to a variety of application scenarios and improves the flexibility and accuracy of code engineering similarity detection.
[0048] Secondly, embodiments of this application provide a code similarity detection device, comprising:
[0049] The acquisition module is used to acquire a set of code project files to be compared; wherein, the set of code project files to be compared includes any two code project files;
[0050] The parsing module is used to parse the code project file to obtain the corresponding graph structure information. The graph structure information includes nodes and edges. Nodes are used to represent programming elements in the code project file, and edges are used to represent logical relationships in the code project file.
[0051] The generation module is used to generate the corresponding code graph based on the graph structure information;
[0052] The first calculation module is used to calculate the first similarity based on the code graph;
[0053] The determination module is used to determine the code text based on the code project files;
[0054] The second calculation module is used to calculate the second similarity based on the code text;
[0055] The third calculation module is used to calculate the comprehensive similarity between any two code project files based on the first similarity and the second similarity.
[0056] In one possible embodiment, the parsing module is specifically used for:
[0057] The code project file is parsed to extract multiple programming elements from the code project file, and corresponding nodes are created based on the programming elements;
[0058] Extract the logical relationships between the programming elements in the code project file;
[0059] Based on the logical relationship, corresponding edges are established between the nodes.
[0060] In one possible embodiment, the nodes include class nodes, interface nodes, variable nodes, function / method nodes, and instance nodes, each corresponding to the programming element.
[0061] The logical relationships include multiple relationships such as instantiation, inclusion, inheritance, access, and invocation.
[0062] In one possible embodiment, the parsing module is specifically configured to perform at least one of the following functions:
[0063] Establish corresponding edges between class nodes and instance nodes that have an instantiation relationship;
[0064] Establish corresponding edges between class nodes and variable nodes and / or function nodes that have an inclusion relationship;
[0065] Establish corresponding edges between class nodes that have inheritance relationships;
[0066] Establish corresponding edges between interface nodes and class nodes that have access relationships;
[0067] Establish corresponding edges between function nodes, instance nodes, and function nodes and variable nodes that have a calling relationship.
[0068] In one possible embodiment, the first computing module is specifically used for:
[0069] The code map is standardized to obtain a standardized map;
[0070] Based on the standardized graph, construct the adjacency tensor;
[0071] The adjacency tensor is mapped to obtain the mapping result;
[0072] The first similarity is calculated based on the overlap of the mapping results.
[0073] In one possible embodiment, the second computing module is specifically used for:
[0074] The code text is preprocessed to obtain preprocessed text; wherein, the preprocessing includes comment removal and / or identifier normalization.
[0075] Based on the preprocessed text, text similarity is calculated to obtain the second similarity.
[0076] In one possible embodiment, the third computing module is specifically used for:
[0077] Obtain weight information; wherein the weight information includes a first weight and a second weight, and the sum of the first weight and the second weight is 1;
[0078] The first similarity and the second similarity are weighted according to the first weight and the second weight to obtain the comprehensive similarity.
[0079] In one possible embodiment, the third computing module is further specifically used for:
[0080] Obtain the application scenario type corresponding to the set of code project files to be compared;
[0081] The weight information is determined based on the application scenario type and the preset correspondence between the application scenario type and the weight information.
[0082] Thirdly, embodiments of this application provide an electronic device, including: a memory and a processor;
[0083] The memory stores the instructions that the computer executes;
[0084] The processor executes computer execution instructions stored in memory, causing the processor to perform the method described in the first aspect above.
[0085] Fourthly, embodiments of this application provide a computer-readable storage medium storing computer-executable instructions, which, when executed by a processor, are used to implement the method described in the first aspect above.
[0086] Fifthly, embodiments of this application provide a computer program product, including a computer program that, when executed by a processor, implements the method described in the first aspect above.
[0087] This application provides a method, apparatus, device, medium, and product for code similarity detection. The method, when comparing code projects, first constructs the structural graph information of the code project files to achieve a first similarity comparison. Then, it combines this with the text content of the code project files to perform a second similarity comparison. Finally, it fuses the first and second similarities to obtain the final similarity detection result. This application's embodiments, by simultaneously constructing the structural graph of the code project and extracting the code text content, achieve a comprehensive similarity evaluation of the code project from two orthogonal directions: structural and textual dimensions. The structural graph can capture the project-level dependencies between classes and modules, effectively detecting cross-file and cross-module code plagiarism. Through dual-dimensional fusion, the accuracy of similarity detection for code projects is improved. Attached Figure Description
[0088] The accompanying drawings, which are incorporated in and form part of this specification, illustrate embodiments consistent with this application and, together with the description, serve to explain the principles of this application.
[0089] Figure 1 A schematic diagram of a code similarity detection system architecture provided for an embodiment of this application;
[0090] Figure 2 A flowchart illustrating a code similarity detection method provided in an embodiment of this application;
[0091] Figure 3 A schematic diagram of the structure of a code similarity detection device provided in an embodiment of this application;
[0092] Figure 4 This is a schematic diagram of the structure of a code similarity detection device provided in an embodiment of this application.
[0093] The accompanying drawings illustrate specific embodiments of this application, which will be described in more detail below. These drawings and descriptions are not intended to limit the scope of the concept in any way, but rather to illustrate the concept of this application to those skilled in the art through reference to particular embodiments. Detailed Implementation
[0094] Exemplary embodiments will now be described in detail, examples of which are illustrated in the accompanying drawings. When the following description relates to the drawings, unless otherwise indicated, the same numbers in different drawings denote the same or similar elements. The embodiments described in the following exemplary embodiments do not represent all embodiments consistent with this application. Rather, they are merely examples of apparatuses and methods consistent with some aspects of this application as detailed in the appended claims.
[0095] It should be noted that the user information (including but not limited to user device information, user personal information, etc.) and data (including but not limited to data used for analysis, data stored, data displayed, etc.) involved in this application are all information and data authorized by the user or fully authorized by all parties. Furthermore, the collection, storage, use, processing, transmission, provision, disclosure, and application of the relevant data all comply with relevant laws, regulations, and standards, necessary confidentiality measures have been taken, they do not violate public order and good morals, and corresponding operation portals are provided for users to choose to authorize or refuse.
[0096] It should be noted that the methods, apparatus, equipment, media and products for code similarity detection provided in this application can be used in the field of fintech or other related fields, and can also be used in any field other than fintech. The application fields of the methods, apparatus, equipment, media and products for code similarity detection in this application are not limited.
[0097] The terminology used in the embodiments of this application is explained below:
[0098] Code project: refers to a complete software project consisting of multiple source code files, including programming elements such as classes, interfaces, functions, and variables, and their interrelationships.
[0099] Graph similarity calculation: A method to calculate the degree of similarity between two graph structures by comparing their topological features, node attributes, and edge relationships.
[0100] Text similarity calculation: A method to calculate the degree of similarity between two text contents by comparing their lexical, grammatical, and semantic features.
[0101] Code graph: A graph structure representing various elements and their relationships in a code project, including nodes and edges.
[0102] Currently, code similarity detection mainly employs the following two technical solutions.
[0103] Text similarity-based detection methods treat source code as plain text and calculate text similarity using methods such as string matching, fingerprint hashing, or word frequency statistics. Taking token-based detection as an example, a typical implementation process is as follows: First, lexical analysis is performed on the source code to segment the code file into token sequences; then, the similarity between token sequences is calculated, for example, using cosine similarity or Jaccard similarity as a metric; finally, a similarity threshold is set, and plagiarism is suspected when the similarity score exceeds the threshold. This method is simple to implement and computationally fast, and is widely used in homework plagiarism checking in educational settings.
[0104] The detection method based on Abstract Syntax Trees (ASTs) generates ASTs by parsing code and then compares the similarity of the AST structures. Its typical implementation process is as follows: First, lexical and syntactic analysis is performed on the source code to generate the corresponding ASTs; then, structural features of the ASTs are extracted, such as node type distribution, subtree patterns, and tree paths; finally, similarity scores are calculated between the ASTs, with common calculation methods including tree edit distance and subtree matching scores. This method can identify some plagiarism at the syntactic structure level and has a certain resistance to simple obfuscation such as variable renaming.
[0105] However, both of the aforementioned existing technical solutions have the following shortcomings. For text similarity-based methods, there are at least three drawbacks. First, this method cannot identify plagiarized code that has been processed using simple obfuscation techniques such as format modification, variable renaming, adding irrelevant code, or adjusting statement order. These operations significantly alter the composition and order of the token sequence at the text level, thus lowering the similarity score, but at the semantic level, the code logic remains substantially unchanged. Second, this method completely ignores the syntactic structure and semantic information of the code, easily misjudging functionally unrelated but textually similar code fragments as plagiarism, resulting in a high false positive rate in actual detection. Third, this method is usually limited to text comparison at the level of a single file or code fragment, making it difficult to detect plagiarism across files or modules. This is because engineering-level code reuse often involves the similarity of organizational structures between multiple files, and this information cannot be reflected at the pure text level.
[0106] The abstract syntax tree (API)-based approach also suffers from at least four drawbacks. First, it only considers the syntactic structure of a single file, neglecting project-level organizational information such as inheritance hierarchies between classes and call dependencies between modules. These relationships are crucial for determining the similarity of two code projects at the overall architectural level. Second, lacking a project-level global view, this approach cannot effectively capture complex interactions between classes and modules, and its ability to identify plagiarized code processed through refactoring techniques such as method extraction, interface abstraction, and class hierarchy adjustments is insufficient. Third, the computational complexity of core algorithms such as tree edit distance is high, typically polynomial or even exponential. When the code file size is large or the number of API nodes is large, the computational overhead increases significantly, making it difficult to scale to large codebases containing numerous files and complex dependencies. Fourth, the comparison of API trees only reflects the syntactic structural similarity of a single file and cannot characterize cross-file element reference relationships and the global organizational structure within a code project, resulting in poor detection of plagiarism when the original code is split into multiple files.
[0107] To address the aforementioned issues, embodiments of this application provide a method, apparatus, device, medium, and product for detecting code similarity. This method achieves a comprehensive evaluation of code similarity from two orthogonal directions: structural and textual dimensions, by simultaneously constructing a structural map of the code project and extracting the code text content.
[0108] Furthermore, this application provides a code engineering similarity calculation method that combines graph similarity and text similarity. This method organically combines graph similarity calculation with text similarity calculation by simultaneously constructing a structural graph of the code engineering and extracting the code text content. It can comprehensively evaluate the similarity of the code engineering from two dimensions: macro-engineering structure and micro-implementation details. It can accurately identify plagiarized code that has undergone structural modifications and semantic preservation transformations such as variable renaming, format adjustment, method extraction, interface abstraction, and class hierarchy adjustment. It can effectively detect cross-file and cross-module code plagiarism and unauthorized commercial use of open-source code, while significantly reducing the false alarm rate and improving the accuracy and reliability of the detection results.
[0109] Optional, Figure 1 This is a schematic diagram of a code similarity detection system architecture provided in an embodiment of this application. Figure 1 In the above architecture, at least one of receiving device 101, processor 102 and display device 103 is included.
[0110] It is understood that the structures illustrated in the embodiments of this application do not constitute a specific limitation on the architecture of a code similarity detection system. In other feasible embodiments of this application, the above architecture may include more or fewer components than illustrated, or combine some components, or split some components, or arrange different components, which can be determined according to the actual application scenario and is not limited here. Figure 1 The components shown can be implemented in hardware, software, or a combination of both.
[0111] In the specific implementation process, the receiving device 101 can be an input / output interface or a communication interface.
[0112] The processor 102 can construct the graph structure information of the code project file to achieve the first similarity comparison. Then, it combines the text content of the code project file to perform the second similarity comparison. The first and second similarities are fused to obtain the final similarity detection result.
[0113] The display device 103 can be used to display the above results, etc.
[0114] The display device can also be a touch screen, used to receive user commands while displaying the above content, so as to achieve interaction with the user.
[0115] It should be understood that the aforementioned processor can be implemented by reading instructions from memory and executing those instructions, or it can be implemented through chip circuitry.
[0116] Furthermore, the network architecture and business scenarios described in the embodiments of this application are for the purpose of more clearly illustrating the technical solutions of the embodiments of this application, and do not constitute a limitation on the technical solutions provided in the embodiments of this application. As those skilled in the art will know, with the evolution of network architecture and the emergence of new business scenarios, the technical solutions provided in the embodiments of this application are also applicable to similar technical problems.
[0117] The technical solution of this application will be described in detail below with reference to specific embodiments:
[0118] Optionally, Figure 2 This is a flowchart illustrating a code similarity detection method provided in an embodiment of this application. The execution entity of this embodiment can be... Figure 1 The processor 102 in the code can be specifically executed based on the actual application scenario. For example... Figure 2 As shown, the method includes the following steps:
[0119] S201: Obtain the set of code project files to be compared.
[0120] The set of code project files to be compared includes any two code project files.
[0121] In this embodiment of the application, the code project file set is a set of files that are to be detected, used to carry the comparison input of any two code project files. Specifically, it can be a set of project directories, a set of compressed packages, a set of repository snapshots, or a project set consisting of multiple source files and their configuration files.
[0122] Optionally, the code project file is a code carrier with an engineering organization relationship. It is not limited to a single source file, and may also include files associated with the source code for compilation, execution or calling, as well as directory hierarchy information.
[0123] In some possible implementations, when obtaining the set of code project files to be compared, multiple code project directories uploaded by users can be received via an external input interface, and each directory can be identified as a code project file; multiple snapshots of the projects to be inspected can be read from a pre-established code repository storage unit; or after receiving a comparison task request, multiple corresponding project versions can be retrieved from the database according to the task identifier and combined into a set of code project files to be compared.
[0124] Optionally, for data sources from open-source code repositories, internal enterprise code repositories, or teaching assignment submission systems, file integrity verification is performed first to confirm that the compressed package can be decompressed, the directory hierarchy is accessible, the character encoding is recognizable, and the project identifier is distinguishable. Then, each project is mapped to a unique project number, and the association between the project number and the file path, language type, submission time, and version number is established.
[0125] Based on the subsequent need to perform similarity calculations on any two code project files, this step can also generate a comparison index table after the file set is loaded. The comparison index table records the number, root directory, file list and metadata summary of each code project file, so that subsequent parsing and code text extraction can be performed independently at the project granularity.
[0126] In one possible implementation, when the input object itself is multiple branch versions, project instances can be created separately according to the branch name or commit hash value, so that each project instance maintains an independent file set boundary.
[0127] By first constructing a unified set of inputs to be compared, subsequent processing of structural information and code text can be carried out within the same project boundary, ensuring that the objects used for calculating comprehensive similarity are consistent.
[0128] S202: Parse and process the code project file to obtain the corresponding graph structure information.
[0129] The graph structure information includes nodes and edges. Nodes are used to represent programming elements in the code project file, and edges are used to represent logical relationships in the code project file.
[0130] In this embodiment, the graph structure information is a data result describing the structured relationships in the code project file, used to provide an intermediate representation for the subsequent generation of code graphs.
[0131] Nodes are used to structurally represent programming elements in code project files. Programming elements can be structural units in the code; edges are used to represent the logical relationships between programming elements. Logical relationships can be associations between programming elements.
[0132] Optionally, in specific implementation, each code project file obtained in S201 is parsed separately. First, the programming language and build description used in the project are identified, and then the analysis program corresponding to the language is called to process the source code. For multi-language projects, the corresponding processing method is selected according to the file extension, build configuration or directory rules.
[0133] Preprocessing can be performed before parsing, including unifying character encoding, removing unresolvable control characters, parsing import path mappings, merging fragmented files, and establishing symbol information. Subsequently, based on the parsing results, corresponding node and edge information is generated, and cross-file and cross-module relationships are incorporated into the graph structure information. After parsing, a corresponding graph structure information set is output for each code project file, serving as input for subsequent code graph generation. Based on the above analysis, this step is crucial for transforming unstructured text into comparable structured objects from project-level code. It explicitly reveals the scattered implementation relationships across files, providing a foundation for subsequent similarity judgments at the code graph level.
[0134] S203: Generate the corresponding code map based on the map structure information.
[0135] In this embodiment of the application, the code graph is used to carry code engineering structure information. It is a graph structure object containing nodes, edges and their topological relationships, and is used to provide a structured comparison basis for the first similarity calculation.
[0136] Optionally, the graph structure information output by S202 can be read, and a corresponding code graph can be constructed on a per-code-project-file basis.
[0137] Optionally, during the construction process, the graph structure information is organized into graph objects that can represent the internal structural relationships of the project, while maintaining consistency in the expression format between different code project files. The code graph generated in this way can represent both local logic in a single file within the project and overall call chains and dependency chains across files and modules.
[0138] Once generated, each code project file corresponds to a code graph, which is written to the graph cache or graph database. Simultaneously, an index relationship is established between project numbers and code graph objects to support fast access and comparison between any two code project files. Through this processing, the original parsing results are organized into a stable topological structure, ensuring that structural renaming, format changes, and comment changes do not directly affect the code graph representation. This allows subsequent first-order similarity scores to more effectively reflect the degree of closeness at the project structure level.
[0139] S204: Calculate the first similarity based on the code graph.
[0140] In this embodiment of the application, the first similarity is used to measure the degree of structural similarity between two code project files at the code graph level, reflecting whether the project structures match.
[0141] Optionally, code graphs corresponding to any two code project files are selected from the code project file set and denoted as the first code graph and the second code graph, respectively. The first similarity is calculated by comparing the two based on their similarity in nodes, edges and overall structure.
[0142] Optionally, the final first similarity score can be normalized to the range of 0 to 1, with a higher value indicating a higher degree of structural similarity between the two code project files. Based on the above analysis, this step, through code graph-level comparison, incorporates the logical organization across files and modules into a unified comparison process, thus preserving the ability to identify the actual project structure beyond variable renaming, comment adjustments, and format transformations.
[0143] In one possible embodiment, calculating a first similarity based on a code graph includes: standardizing the code graph to obtain a standardized graph; constructing an adjacency tensor based on the standardized graph; mapping the adjacency tensor to obtain a mapping result; and calculating the first similarity based on the overlap of the mapping result.
[0144] Alternatively, the standardization process can be used to normalize node numbers to ensure that the same programming elements have consistent identifiers in different graphs, and to filter isolated nodes to eliminate noise interference from unrelated elements in similarity calculations.
[0145] In one possible implementation, this embodiment uses a tensor mapping method to calculate the structural similarity between two code graphs. Specifically, it includes the following steps:
[0146] First, the adjacency matrices of the first code graph and the second code graph are constructed respectively. Since the code graph contains various edge types (such as inheritance, implementation, containment, instantiation, and calling relationships), the adjacency matrices corresponding to different edge types are treated as different layers. That is, each edge type corresponds to an independent adjacency matrix layer. Each layer of the matrix has the same number of rows and columns, with rows and columns corresponding to the nodes in the code graph, arranged sequentially along the same dimension.
[0147] For example, a globally unified edge attribute order is pre-defined as: inheritance relation layer, implementation relation layer, contain relation layer, instantiation relation layer, and calling relation layer. Both code graphs organize their adjacency tensors according to this fixed order. This order needs to consider the union of the edge attributes of the two graphs, that is, all edge types appearing in the two graphs are included in the arrangement. For an edge type that does not exist in one graph, the adjacency matrix element of its corresponding level is set to zero to ensure that the two adjacency tensors are comparable in the same semantic dimension. Through the above processing, the first adjacency tensor T1 corresponding to the first code graph and the second adjacency tensor T2 corresponding to the second code graph are formed.
[0148] Second, the first adjacency tensor T1 and the second adjacency tensor T2 are read as vectors according to the edge dimension. In some embodiments, specifically, the element values representing the existence or weight of an edge in each layer of the adjacency matrix are expanded by row or by column and concatenated into a one-dimensional feature vector, which completely preserves the existence information of various logical relationships between all node pairs in the code graph.
[0149] Third, a common mapping space ST is constructed. Optionally, the mapping space ST is a predefined vector space whose dimensions can be configured according to the code project scale and accuracy requirements in the actual application scenario; this mapping space is used to project code graphs of different sizes and different numbers of nodes onto a unified vector space for comparison.
[0150] Fourth, the adjacency tensors of the two code graphs are linearly mapped to the common mapping space ST, and conflict handling is performed on the mapping results. Optionally, conflict handling includes: when multiple nodes or edges are mapped to the same vector position after mapping, the mapping position conflict is resolved by accumulating or taking the maximum value, so as to ensure the uniqueness and stability of the mapping results.
[0151] Fifth, calculate the overlap of the mapping results. For example, calculate the cosine similarity or intersection over union (IoU) between two mapping result vectors. The overlap reflects the degree of structural similarity between the two codemaps in the common mapping space, and this overlap is used as an estimate of the structural similarity between the two codemaps.
[0152] It should be noted that the tensor mapping method described above transforms graph structure similarity calculation into overlap calculation in vector space, avoiding the exponential computational complexity brought about by traditional graph edit distance or subgraph isomorphic matching. This makes the method applicable to large code projects containing a large number of nodes and complex edge relationships.
[0153] When calculating structural similarity, the matching degree of node types and edge relationships are further considered. In some embodiments, specifically, when mapping and calculating the overlap of two code graphs, matching is only allowed between nodes of the same type (e.g., class nodes only match class nodes, function nodes only match function nodes), and matching is allowed between edge relationships of the same type (e.g., inheritance relationship edges only match inheritance relationship edges). Nodes and edges of different types do not participate in the overlap calculation. Through the above type constraints, it is ensured that the comparison of structural similarity is performed at the same semantic level, avoiding mismatches caused by different node types.
[0154] After the above processing, the final output is the project structure similarity score_graph, which takes values in the range of [0,1], where 0 indicates that the two code projects are completely unrelated at the structural level, and 1 indicates that the two code projects are completely identical at the structural level.
[0155] This application's embodiments utilize an adjacency tensor construction and mapping method for graph similarity calculation. By organizing different edge types as different layers of tensors, it can naturally integrate various semantic relationships such as inheritance, invocation, and instantiation for comparison within the same similarity measurement framework. Through tensor mapping, graph structure similarity calculation is transformed into overlap calculation in vector space, reducing computational complexity and improving the efficiency of similarity detection.
[0156] S205: Determine the code text based on the code project file.
[0157] In this embodiment of the application, code text is used to carry the object containing code content text, providing input for the second similarity calculation.
[0158] Optionally, for each code project file, extract the text content that can be used for comparison according to the project boundaries. The extracted objects include the source code text and text content related to the logic implementation. If the project contains binary files, image files, compilation artifact directories, or third-party dependency cache directories, they are removed according to file type rules and directory rules before extraction. For multiple source files with project organizational relationships, they can be sorted by file path and then concatenated into project-level code text, or they can be first organized into local text units according to the internal organization of the project, and then form a set of code text units for subsequent similarity calculation.
[0159] Optionally, after the code text is determined, a text index is generated for each project. The index records the text length, number of terms, file contribution ratio, and boundary positions of each local code text unit. The resulting code text is no longer simply a copy of the original source code, but rather a comparison object organized at the project level. Based on the above analysis, by stably limiting the scope of code text extraction to within the project boundaries, the subsequent second similarity can more effectively reflect the degree of closeness at the implementation detail level.
[0160] S206: Calculate the second similarity based on the code text.
[0161] In this embodiment, the second similarity is used to measure the similarity between two code project files at the code text level, reflecting whether the code implementation details are similar. Specifically, the code text corresponding to any two code project files determined in S205 is read, and a similarity calculation is performed based on the closeness of their text content to obtain the second similarity. When a project contains a large number of modules, the local code text units can be compared separately first to obtain the project-level second similarity. After calculation, the second similarity is normalized to the 0-1 range and saved together with the local matching results used in the calculation for subsequent comprehensive similarity calculation and result tracking. Through this step, the implementation details in the project-level code text content are quantified into a unified value, enabling similarity information from different dimensions of the code graph to enter the same fusion process.
[0162] In one possible embodiment, calculating a second similarity based on the code text includes: preprocessing the code text to obtain preprocessed text; wherein the preprocessing includes removing comments and / or normalizing identifiers; and calculating text similarity based on the preprocessed text to obtain a second similarity.
[0163] Optionally, each source code file in the code project can be preprocessed separately. Preprocessing includes removing comments and standardizing identifiers.
[0164] Among them, the comment removal process is used to remove single-line and multi-line comments in the code to avoid the comment content interfering with the text similarity calculation; the standardized identifier processing is used to uniformly replace user-defined variable names, function names, class names and other identifiers according to preset rules, such as replacing all variable names with uniform placeholders and all function names with uniform placeholders, thereby eliminating the impact of different naming styles on text similarity calculation.
[0165] After preprocessing, code that originally differed significantly at the text level due to different variable names will present similar lexical sequences after standardization. This allows text similarity calculation to focus on the logical semantics of the code rather than naming style. For example, for code with variable names a, b, c and code with variable names userName, userPassword, userAge, after standardization of identifiers, both variable names are replaced with the same placeholders, thus making them more comparable at the text level.
[0166] In this embodiment, either a token-based text similarity algorithm or an abstract syntax tree-based text similarity algorithm can be used to calculate the similarity between preprocessed code text. Specifically, the token-based algorithm segments the preprocessed code text into token sequences and then calculates the cosine similarity or Jaccard similarity between the token sequences; the abstract syntax tree-based algorithm parses the preprocessed code text into an abstract syntax tree, extracts the structural features of the abstract syntax tree, and calculates the similarity between the trees; either algorithm can be used individually or in combination for mutual verification.
[0167] Considering the characteristic of a code project containing multiple source code files, in one possible implementation, this application embodiment calculates the text similarity between each file in the first code project and each file in the second code project, obtaining a file similarity matrix. Then, for each file in the first code project, the maximum similarity value between it and all files in the second code project is selected from the similarity matrix. Finally, the maximum similarity values corresponding to all files in the first code project are weighted and averaged to obtain the text similarity at the entire code project level. This processing method can adapt to differences in the number and organization of files between two code projects. For example, when the file division methods of two code projects are different but the overall code content is similar, the maximum similarity matching and weighted averaging can still effectively evaluate their project-level text similarity.
[0168] After the above processing, the final output is the code-text similarity score, Score_text, which ranges from [0,1], where 0 indicates that the two code projects are completely unrelated at the text level, and 1 indicates that the two code projects are completely identical at the text level.
[0169] This application's embodiments eliminate interference from non-semantic factors such as code formatting, comment content, and variable naming styles in text similarity calculations through preprocessing operations such as removing comments and standardizing identifiers. This allows text comparison to focus more on the logical semantic features of the code. After preprocessing, even if two code projects use completely different variable naming styles or different commenting habits, their text-level similarity can still be accurately assessed based on standardized lexical sequences. This effectively addresses common plagiarism obfuscation techniques such as variable renaming and formatting adjustments, improving the accuracy of semantic detection of code projects and further enhancing the accuracy of code project detection.
[0170] S207: Calculate the overall similarity between any two code project files based on the first similarity and the second similarity.
[0171] In this embodiment of the application, the comprehensive similarity is used to comprehensively reflect the overall similarity between any two code project files, and serves as the final judgment basis.
[0172] In specific implementation, the first similarity score output by S204 and the second similarity score output by S206 are read, and it is first confirmed that both are within the same numerical range. If there are differences in the dimensions or distributions of the two indicators, normalization or standard distribution correction is performed first, and then fusion calculation is performed to obtain the comprehensive similarity score of any two code project files. Further, after calculating the comprehensive similarity score, the result can be compared with a preset threshold. When the comprehensive similarity score is greater than or equal to the threshold, the project pair is marked as a highly similar project pair, and its structural overlap summary and code text overlap summary are saved. In one possible embodiment, auxiliary judgment labels can also be output based on the degree of difference between the first and second similarities.
[0173] In one possible embodiment, calculating the comprehensive similarity of any two code project files based on a first similarity and a second similarity includes: obtaining weight information; wherein the weight information includes a first weight and a second weight, and the sum of the first weight and the second weight is 1; and weighting the first similarity and the second similarity based on the first weight and the second weight to obtain the comprehensive similarity.
[0174] In this embodiment, graph similarity and text similarity are fused using a weighted summation method, achieving synergistic complementarity between structural and textual information in similarity determination. This fusion method is simple to calculate and easy to implement, improving the efficiency and accuracy of similarity detection.
[0175] In one possible embodiment, obtaining weight information includes: obtaining the application scenario type corresponding to the code project file set to be compared; and determining the weight information based on the application scenario type and the preset correspondence between the application scenario type and the weight information.
[0176] It is understood that the correspondence between the preset application scenario type and the weight information can be determined according to the actual situation, and the embodiments of this application do not impose specific restrictions on this.
[0177] Here, the embodiments of this application automatically determine the weight information according to the application scenario type, which further improves the intelligence level and scenario adaptability of the solution. Moreover, users in different usage scenarios do not need to manually adjust the weight parameters to obtain similarity evaluation results that are suitable for the current detection target. This realizes the automatic adaptation of similarity detection strategy, which can adapt to a variety of application scenarios and improves the flexibility and accuracy of code engineering similarity detection.
[0178] After calculating the graph similarity score Score_graph and the text similarity score Score_text separately, this embodiment of the application uses a weighted summation method to fuse the two and calculate the comprehensive similarity Score_total between the two code projects.
[0179] Specifically, the formula for calculating the overall similarity score Score_total is as follows:
[0180] Score_total=α×Score_graph+β×Score_text.
[0181] Where α represents the first weight corresponding to the graph similarity score, β represents the second weight corresponding to the text similarity score, and α+β=1, that is, the sum of the two weights is normalized to 1.
[0182] The above normalization constraints ensure that the overall similarity score always falls within the [0,1] range, facilitating subsequent comparison and judgment with the preset threshold.
[0183] Optionally, by default, α=β=0.5 can be set, meaning that graph similarity and text similarity have the same contribution to the overall similarity, thereby achieving a balanced fusion of structural and textual information in the absence of prior knowledge.
[0184] The weighted summation method described above is simple to calculate, provides intuitive results, and is easy to implement in engineering. It can achieve synergistic complementarity between structural and textual information in similarity determination while ensuring computational efficiency.
[0185] It should be noted that the weight coefficients α and β can be flexibly adjusted according to the actual application scenario. Specifically, the application scenario type corresponding to the code project file set to be compared is obtained, and then the weight information is determined according to the correspondence between the application scenario type and the preset application scenario type and weight information. For example, in the open source license compliance check scenario, since the infringement of open source code often manifests as overall reuse at the structural level, the first weight α can be set to a larger value (e.g., α=0.7, β=0.3) to focus on the evaluation of structural similarity; in the homework plagiarism check scenario, since plagiarism usually manifests as word-for-word code copying or partial modification, the second weight β can be set to a larger value (e.g., α=0.3, β=0.7) to focus on the evaluation of text similarity. Through the above adaptive weight configuration, this method can adapt to diverse application scenario requirements. The preset correspondence between the application scenario type and weight information can be preset according to the actual situation, and this application embodiment does not specifically limit this.
[0186] After calculating the overall similarity score Score_total, this embodiment of the application further determines plagiarism based on the overall similarity score.
[0187] Specifically, a similarity threshold T is preset.
[0188] The threshold T is used as a critical value to distinguish between normal code differences and suspected plagiarism, and can be configured according to the strictness of the actual application scenario.
[0189] In a possible implementation, the threshold T is set to a value in the range of [0.7, 0.9]. For example, in scenarios with high requirements for detection accuracy such as open-source protocol compliance check, the threshold T may be set to 0.85 to reduce the risk of false positives; in scenarios with high requirements for recall rate such as assignment plagiarism check, the threshold T may be set to 0.70 to reduce the risk of false negatives.
[0190] When the comprehensive similarity Score_total is greater than or equal to the threshold T, i.e., Score_total ≥ T, it is determined that there is a suspicion of plagiarism between the two code projects. Otherwise, when Score_total < T, it is determined that there is no suspicion of plagiarism between the two code projects.
[0191] After the determination is completed, this embodiment further outputs a similarity report. The similarity report includes at least the following information:
[0192] First, information about structurally similar parts, i.e., matched subgraphs. The matched subgraphs include matched node sets and edge sets in the two code graphs, which specifically correspond to matched classes, interfaces, functions, variables, and their inheritance relationships, call relationships, instantiation relationships, etc., in the code projects, and are presented in a visual or list form to help users intuitively locate project modules that are similar at the structural level.
[0193] Second, information about textually similar parts, i.e., matched code snippets. The matched code snippets include source code files with high textual similarity in the two code projects and corresponding code line ranges, and are presented in a highlighted or annotated form to help users intuitively locate code implementation details that are similar at the textual level.
[0194] Third, the comprehensive similarity score Score_total. Optionally, the graph similarity score Score_graph and the textual similarity score Score_text are presented separately, so that users can understand the specific composition and source of the similarity.
[0195] By outputting the above similarity report, users can intuitively understand the basis and specific source of the similarity score, which facilitates subsequent manual review, infringement determination, or compliance review, significantly improving the usability and credibility of the detection result.
[0196] Based on the above analysis, it can be known that this step fuses structural similarity information at the code graph level and implementation similarity information at the code text level into a unified metric, forming a final quantitative result for project-level code similarity relationships, so that the detection result covers not only local code text consistency, but also cross-file and cross-module structural relevance.
[0197] In this embodiment of the application, when comparing code projects, a structural graph of the code project files is first constructed to achieve a first similarity comparison. Then, combined with the text content of the code project files, a second similarity comparison is performed. The first and second similarities are then fused to obtain the final similarity detection result. This embodiment of the application achieves a comprehensive similarity evaluation of code projects from two orthogonal directions: structural and textual dimensions, by simultaneously constructing a structural graph of the code project and extracting the code text content. The structural graph can capture the project-level dependencies between classes and modules, effectively detecting cross-file and cross-module code plagiarism. Through dual-dimensional fusion, the accuracy of similarity detection for code projects is improved.
[0198] The following explains steps S202-204:
[0199] In one possible embodiment, the code project file is parsed to obtain the corresponding graph structure information, including: parsing the code project file to extract multiple programming elements in the code project file and establishing corresponding nodes based on the programming elements; extracting the logical relationships between the programming elements in the code project file; and establishing corresponding edges between the nodes based on the logical relationships.
[0200] In this embodiment, the code entities scattered in various source files and their cross-file relationships are organized into a graph structure, so that subsequent structural similarity calculations can be performed based on a complete project-level dependency graph. This provides a reliable data foundation for accurately assessing the similarity of two code projects at the macro-level organizational structure, and provides a graph structure extraction method specifically for code projects, further improving the accuracy of similarity detection.
[0201] In one possible embodiment, nodes include class nodes, interface nodes, variable nodes, function / method nodes, and instance nodes, which correspond to programming elements respectively; logical relationships include multiple relationships among instantiation, inclusion, inheritance, access, and invocation.
[0202] This application's embodiments construct a graph model that fully represents the structure of an object-oriented program engineering project by defining nodes specifically as class nodes, interface nodes, variable nodes, function / method nodes, and instance nodes, and edges specifically as instantiation relationships, inclusion relationships, inheritance relationships, access relationships, and invocation relationships. This graph model covers the core programming elements in the code project and their core semantic relationships, breaking through the limitations of traditional abstract syntax trees that only focus on the syntax structure of a single file. It can depict high-level organizational structure information across classes, files, and modules, further improving the accuracy of similarity detection.
[0203] First, the source code files in the code project are parsed to extract the following programming elements, and a corresponding node is created for each programming element:
[0204] First, extract all class definitions from the code project and create class nodes, with each class node corresponding to a class definition. Optionally, the class definition includes attribute information such as the class name, file path, access modifiers, and generic parameters. This attribute information is stored as additional attributes of the node in the node data structure to enrich the semantic representation of the node.
[0205] Second, extract all interface definitions from the code project and create interface nodes, with each interface node corresponding to one interface definition. Optionally, the interface definition includes attribute information such as the interface name, file path, and generic parameters.
[0206] Third, extract all variable declarations from the code project and create variable nodes, with each variable node corresponding to a variable declaration. Optionally, the variable declaration includes attribute information such as the variable's name, data type, scope, file location, and line number.
[0207] Fourth, extract all function or method definitions from the code project and create function nodes, with each function node corresponding to a function definition. Optionally, the function definition includes attribute information such as the function name, return type, parameter list, file path, and line number.
[0208] Fifth, extract all instantiated objects from the code project and create instance nodes, with each instance node corresponding to one instantiated object. Optionally, the instantiated object includes attribute information such as the class type of the instance, the file where the instantiation occurred, and the line number.
[0209] It should be noted that for function nodes, when a code project contains both functions (independent functions in procedural languages) and methods (class member methods in object-oriented languages), both are uniformly represented using function nodes. The node type does not distinguish between functions and methods, so as to facilitate uniform processing of different types of code projects.
[0210] Through the above extraction operations, the code entities scattered in various source code files are organized according to a unified graph node model, providing a structured data foundation for establishing logical relationships between nodes in the future.
[0211] In one possible embodiment, corresponding edges are established between nodes according to logical relationships, including at least one of the following: establishing corresponding edges between class nodes and instance nodes with instantiation relationships; establishing corresponding edges between class nodes and variable nodes and / or function nodes with inclusion relationships; establishing corresponding edges between class nodes and class nodes with inheritance relationships; establishing corresponding edges between interface nodes and class nodes with access relationships; and establishing corresponding edges between function nodes, instance nodes, function nodes, and variable nodes with calling relationships.
[0212] After extracting all nodes, edges are created between the corresponding nodes based on the logical relationships between programming elements in the code project. This embodiment supports the creation of the following edge types:
[0213] First, instantiation relationships. When it is detected that class A is instantiated as object a, an instantiation relationship edge is established from class node A to instance node a. This relationship represents the dependency between the class definition and its instance, and records instantiation behaviors such as the new keyword or reflection calls in the code.
[0214] Second, the inclusion relationship. When class A contains variable v, an inclusion relationship edge is established from class node A to variable node v; when class A contains function f, an inclusion relationship edge is established from class node A to function node f. This relationship represents the hierarchical relationship between a class and its members, that is, the class acts as a container, and variables and functions are the contained members; the inclusion edge is a directed edge, with the direction pointing from the container node to the member node, and the direction indicates the all-encompassing relationship.
[0215] Third, inheritance relationships. When class B inherits from class A, an inheritance relationship edge is established from class node A to class node B. This relationship represents the inheritance hierarchy between parent and child classes. It should be noted that the direction of the edge is from the parent node to the child node, so that the structural pattern of the inheritance hierarchy can be identified during subsequent graph similarity calculation. For multiple inheritance scenarios, independent inheritance relationship edges are established between each parent class and child class.
[0216] Fourth, the access relationship (i.e., the interface implementation relationship). When class C implements interface I, an access relationship edge is established from interface node I to class node C. This relationship represents the contractual relationship between the interface and the implementing class; the direction of the edge is from the interface node to the class node, so as to identify the pairing structure of the interface and the implementing class during similarity calculation.
[0217] Fifth, call relationships. Call relationships include five specific subtypes, each corresponding to the call or access behavior between different programming elements in the code project:
[0218] (1) Function calling function: When it is detected that function f1 calls function f2, a call relationship edge is established from function node f1 to function node f2. This relationship represents the call dependency between functions, that is, the control flow is transferred from one function to another.
[0219] (2) Instance calling function: When it is detected that instance a calls function f, a calling relationship edge is established from instance node a to function node f. This relationship represents the behavior of the instance object as the caller initiating a method call.
[0220] (3) Instance access to variables: When instance a accesses variable v, a call relationship edge is established from instance node a to variable node v. This relationship represents the instance object's read or write operation on the variable.
[0221] (4) Function returns an instance: When it is detected that function f returns instance a, a call relationship edge is established from function node f to instance node a. This relationship represents the output behavior of returning an instance object after function execution.
[0222] (5) Function access to variable: When function f accesses variable v, a call relationship edge is established from function node f to variable node v. This relationship represents the function's read or write operation on the variable.
[0223] Through refined modeling of the five call relationship subtypes mentioned above, this method can fully depict the multi-directional transmission paths of data flow (variable access, instance return) and control flow (function call, instance call) in code engineering, providing rich semantic information for subsequent structural similarity calculation.
[0224] It is understandable that when establishing the aforementioned edge relationships, each edge corresponds to a specific instance of a logical relationship. For example, when class A simultaneously contains variables v1, v2, and function f, three independent containment edges are established: class node A → variable node v1, class node A → variable node v2, and class node A → function node f. Similarly, for multiple calls within a function, an independent call relationship edge is established for each call. Through this fine-grained edge-building method, the code graph can accurately reflect the specific existence of each logical relationship in the code project, avoiding information loss.
[0225] After the node extraction and edge relationship establishment described above, the code project is completely transformed into a structured code graph. This graph uses nodes to represent various programming elements in the code and directed edges to represent various logical relationships between programming elements, providing structured data input for subsequent graph similarity calculation.
[0226] Here, this application embodiment clarifies the edge construction method corresponding to various logical relationships in the code project in the graph, making the construction of the code graph deterministic and repeatable. The call relationship covers five specific subtypes: between functions, between instances and functions, between instances and variables, between functions and instances, and between functions and variables. It can finely depict the multi-directional transmission paths of data flow and control flow in the code project. For code that has undergone refactoring such as method extraction and interface abstraction, although the text content may change significantly, its core call dependency relationship and inheritance hierarchy are usually preserved, which can effectively detect plagiarized code after such deep refactoring.
[0227] The embodiments of this application can achieve the following beneficial effects:
[0228] The detection dimensions are comprehensive. This method considers both the macro-level organizational structure of the code project (engineering-level information such as class inheritance relationships, interface implementation relationships, and module call dependencies represented by code graphs) and the micro-level implementation details (code-level information such as specific algorithm implementations and logical expressions represented by source code text). It can evaluate the similarity of code projects from two orthogonal directions: structural and textual levels. It can detect plagiarism behavior that has undergone structural reorganization (such as class hierarchy adjustment, module splitting and merging) and local modification (such as statement replacement and logical equivalence transformation), and it can also discover code fragments that are textually similar but structurally different, achieving comprehensive coverage of various types of plagiarism behavior.
[0229] The detection accuracy is high. This method significantly reduces the false positive rate caused by single-dimensional detection through multi-dimensional comprehensive calculation of graph similarity and text similarity. Furthermore, because this method calculates similarity based on code graphs rather than the original text at the structural dimension, the programming elements and logical relationships represented by nodes and edges in the code graph are naturally insensitive to common code obfuscation techniques such as variable renaming, format modification, adding irrelevant comments, and adjusting statement order. This makes the method robust to these obfuscation techniques and effectively identifies plagiarized code that has undergone various obfuscation processes.
[0230] The method boasts high engineering practicality. Firstly, it calculates graph similarity using adjacency tensor mapping, transforming graph structural similarity comparison into overlap calculation in vector space. This avoids the exponential complexity of problems like subgraph isomorphism, allowing for easy scaling to engineering-level similarity detection scenarios in large and medium-sized codebases. Secondly, it eliminates the need for training datasets, model training, and parameter tuning, resulting in a lower deployment threshold and higher engineering practicality compared to code representation methods based on graph neural networks or deep learning. Furthermore, the method supports cross-language detection; it only requires constructing code graphs for different programming languages without altering the core algorithm framework.
[0231] The detection results are interpretable. While outputting a comprehensive similarity score, this method can provide location information for structurally similar parts (such as the specific classes, functions, modules corresponding to the matched subgraphs and the relationships between them) and textually similar parts (such as the file and line number range of the matched code snippets), helping users intuitively understand the source and basis of the similarity score and reducing the risk of misjudgment or questioning of the detection results.
[0232] The method offers flexible parameter configuration. It employs a weighted summation approach to fuse graph similarity scores and text similarity scores, with weight coefficients that can be flexibly adjusted based on specific application scenarios. This allows it to adapt to diverse application needs such as open-source license compliance checks, job deduplication, and code clone detection. Furthermore, this method can be combined with other detection methods (such as code style analysis and commit history analysis), demonstrating excellent scalability.
[0233] It should be noted that the specific implementation methods used in the above embodiments are merely illustrative examples. After understanding the core concept of the embodiments of this application, those skilled in the art can use the following alternative methods to implement the technical solutions of the embodiments of this application, and these alternative methods all fall within the protection scope of this application.
[0234] In the graph similarity calculation stage, in addition to the tensor mapping method used in the above embodiments, the following alternative methods can also be used: use graph neural networks to embed the code graphs, obtain fixed-length graph vectors through graph pooling operations of the graph neural network, and then calculate the similarity between the graph vectors; or, use a precise matching method based on subgraph isomorphism to calculate the structural similarity by finding the maximum common subgraph between two code graphs; or, use graph edit distance as a similarity metric to evaluate the structural similarity by calculating the minimum number of edit operations required to convert one code graph into another.
[0235] In the text similarity calculation stage, in addition to the word-based or abstract syntax tree-based text similarity algorithms used in the above embodiments, the following alternative methods can also be used: adopt deep learning-based code representation methods, such as semantically encoding code text through a pre-trained model, extracting deep semantic features of the code, and then calculating similarity; or, use statistical methods such as n-gram or Term Frequency-Inverse Document Frequency (TF-IDF) to calculate text similarity; or, further combine control flow graph (CFG) on the basis of abstract syntax tree to calculate semantic similarity in order to capture the similarity of code execution logic.
[0236] In the comprehensive similarity calculation stage, in addition to the weighted summation method used in the above embodiments, the following alternative methods can also be used: A multiplicative fusion method can be used, multiplying the graph similarity score by the text similarity score, i.e., Score_total = Score_graph × Score_text. The comprehensive similarity is high only if the similarity of both dimensions is high; or, a maximum value strategy can be used, i.e., Score_total = max(Score_graph, Score_text). Similarity is determined as long as either the graph similarity or text similarity score is high; or, a dynamic weight adjustment mechanism can be introduced to automatically calculate the optimal weight coefficient based on the basic attributes of the two code projects (such as code size, language type, number of files, etc.).
[0237] In the code graph construction phase, in addition to the node and edge types used in the above embodiments, it can be expanded according to actual needs: add more node types, such as adding annotation nodes to represent annotations or decorators in the code, adding namespace nodes to represent the namespace or package structure of the code; add more edge types, such as adding exception handling relationship edges to represent exception handling associations established by try-catch or throw statements, adding dependency relationship edges to represent import or reference dependencies between modules; or, use a property graph model to store additional attributes of nodes and edges.
[0238] Figure 3 This is a schematic diagram of the structure of a code similarity detection device provided in an embodiment of this application, as shown below. Figure 3 As shown, the apparatus in this embodiment includes: an acquisition module 301, a parsing module 302, a generation module 303, a first calculation module 304, a determination module 305, a second calculation module 306, and a third calculation module 307. The code similarity detection device can be the processor itself, or a chip or integrated circuit that implements the processor's functions. It should be noted that the division of the acquisition module 301, parsing module 302, generation module 303, first calculation module 304, determination module 305, second calculation module 306, and third calculation module 307 is only a logical functional division; physically, they can be integrated or independent.
[0239] The acquisition module is used to acquire a set of code project files to be compared; the set of code project files to be compared includes any two code project files.
[0240] The parsing module is used to parse the code project file to obtain the corresponding graph structure information. The graph structure information includes nodes and edges. Nodes are used to represent programming elements in the code project file, and edges are used to represent logical relationships in the code project file.
[0241] The generation module is used to generate the corresponding code graph based on the graph structure information;
[0242] The first calculation module is used to calculate the first similarity based on the code graph;
[0243] The determination module is used to determine the code text based on the code project files;
[0244] The second calculation module is used to calculate the second similarity based on the code text;
[0245] The third calculation module is used to calculate the comprehensive similarity between any two code project files based on the first similarity and the second similarity.
[0246] In one possible embodiment, the parsing module is specifically used for:
[0247] The code project file is parsed to extract multiple programming elements, and corresponding nodes are created based on these programming elements.
[0248] Extract the logical relationships between programming elements in the code project file;
[0249] Based on the logical relationships, establish corresponding edges between the nodes.
[0250] In one possible embodiment, the nodes include class nodes, interface nodes, variable nodes, function / method nodes, and instance nodes, which correspond to programming elements respectively;
[0251] Logical relationships include multiple ones such as instantiation relationship, containment relationship, inheritance relationship, access relationship and invocation relationship.
[0252] In one possible embodiment, the parsing module is specifically used to perform at least one of the following functions:
[0253] Establish corresponding edges between class nodes and instance nodes that have an instantiation relationship;
[0254] Establish corresponding edges between class nodes and variable nodes and / or function nodes that have an inclusion relationship;
[0255] Establish corresponding edges between class nodes that have inheritance relationships;
[0256] Establish corresponding edges between interface nodes and class nodes that have access relationships;
[0257] Establish corresponding edges between function nodes, instance nodes, and function nodes and variable nodes that have a calling relationship.
[0258] In one possible embodiment, the first computing module is specifically used for:
[0259] The code graph is standardized to obtain a standardized graph;
[0260] Construct the adjacency tensor based on the standardized graph;
[0261] The adjacency tensor is mapped to obtain the mapping result;
[0262] The first similarity is calculated based on the overlap of the mapping results.
[0263] In one possible embodiment, the second computing module is specifically used for:
[0264] The code text is preprocessed to obtain preprocessed text; the preprocessing includes removing comments and / or normalizing identifiers.
[0265] Based on the preprocessed text, text similarity is calculated to obtain the second similarity score.
[0266] In one possible embodiment, the third computing module is specifically used for:
[0267] Obtain weight information; wherein, the weight information includes a first weight and a second weight, and the sum of the first weight and the second weight is 1;
[0268] The first similarity and the second similarity are weighted according to the first weight and the second weight to obtain the comprehensive similarity.
[0269] In one possible embodiment, the third computing module is further specifically used for:
[0270] Obtain the application scenario type corresponding to the set of code project files to be compared;
[0271] The weight information is determined based on the application scenario type and the pre-defined correspondence between the application scenario type and the weight information.
[0272] refer to Figure 4 The diagram illustrates a structural schematic of a code similarity detection device 400 suitable for implementing embodiments of the present disclosure. This code similarity detection device 400 can be a terminal device or a server. The terminal device can include, but is not limited to, mobile terminals such as mobile phones, laptops, digital radio receivers, personal digital assistants (PDAs), portable Android devices (PADs), portable media players (PMPs), and in-vehicle terminals (e.g., in-vehicle navigation terminals), as well as fixed terminals such as digital TVs and desktop computers. Figure 4The code similarity detection device shown is merely an example and should not impose any limitation on the functionality and scope of use of the embodiments disclosed herein.
[0273] like Figure 4 As shown, the code similarity detection device 400 may include a processing unit (e.g., a central processing unit, a graphics processing unit, etc.) 401, which can perform various appropriate actions and processes according to a program stored in read-only memory 402 (ROM) or a program loaded from storage device 408 into random access memory (RAM) 403. The random access memory 403 also stores various programs and data required for the operation of the code similarity detection device 400. The processing unit 401, ROM 402, and RAM 403 are interconnected via a bus 404. An input / output (I / O) interface 405 is also connected to the bus 404.
[0274] Typically, the following devices can be connected to I / O interface 405: input devices 406 including, for example, touchscreens, touchpads, keyboards, mice, cameras, microphones, accelerometers, gyroscopes, etc.; output devices 407 including, for example, liquid crystal displays (LCDs), speakers, vibrators, etc.; storage devices 408 including, for example, magnetic tapes, hard disks, etc.; and communication devices 409. Communication device 409 allows code similarity detection device 400 to communicate wirelessly or wiredly with other devices to exchange data. Although Figure 4 A detection device 400 with various means of code similarity is shown; however, it should be understood that implementation or possession of all the means shown is not required. More or fewer means may be implemented alternatively.
[0275] In particular, according to embodiments of this disclosure, the processes described above with reference to the flowcharts can be implemented as computer software programs. For example, embodiments of this disclosure include a computer program product comprising a computer program carried on a computer-readable medium, the computer program containing program code for performing the methods shown in the flowcharts. In such embodiments, the computer program can be downloaded and installed from a network via a communication device 409, or installed from a storage device 408, or installed from a read-only memory 402. When the computer program is executed by the processing device 401, it performs the functions defined in the methods of embodiments of this disclosure.
[0276] It should be noted that the computer-readable medium described in this disclosure can be a computer-readable signal medium or a computer-readable storage medium, or any combination thereof. A computer-readable storage medium can be, for example,—but not limited to—an electrical, magnetic, optical, electromagnetic, infrared, or semiconductor system, apparatus, or device, or any combination thereof. More specific examples of a computer-readable storage medium may include, but are not limited to: an electrical connection having one or more wires, a portable computer disk, a hard disk, random access memory (RAM), read-only memory (ROM), erasable programmable read-only memory (EPROM or flash memory), optical fiber, portable compact disk read-only memory (CD-ROM), optical storage device, magnetic storage device, or any suitable combination thereof. In this disclosure, a computer-readable storage medium can be any tangible medium containing or storing a program that can be used by or in conjunction with an instruction execution system, apparatus, or device. In this disclosure, a computer-readable signal medium can include a data signal propagated in baseband or as part of a carrier wave, carrying computer-readable program code. Such propagated data signals can take various forms, including but not limited to electromagnetic signals, optical signals, or any suitable combination thereof. A computer-readable signal medium can be any computer-readable medium other than a computer-readable storage medium, which can send, propagate, or transmit a program for use by or in connection with an instruction execution system, apparatus, or device. The program code contained on the computer-readable medium can be transmitted using any suitable medium, including but not limited to: wires, optical fibers, RF (radio frequency), etc., or any suitable combination thereof.
[0277] The aforementioned computer-readable medium may be included in the aforementioned code similarity detection device; or it may exist independently and not assembled into the code similarity detection device.
[0278] The aforementioned computer-readable medium carries one or more programs, and when the one or more programs are executed by the code similarity detection device, the code similarity detection device performs the method shown in the above embodiments.
[0279] Computer program code for performing the operations of this disclosure can be written in one or more programming languages or a combination thereof, including object-oriented programming languages such as Java, Smalltalk, and C++, and conventional procedural programming languages such as the "C" language or similar programming languages. The program code can be executed entirely on the user's computer, partially on the user's computer, as a standalone software package, partially on the user's computer and partially on a remote computer, or entirely on a remote computer or server. In cases involving remote computers, the remote computer can be connected to the user's computer via any type of network—including a Local Area Network (LAN) or a Wide Area Network (WAN)—or can be connected to an external computer (e.g., via the Internet using an Internet service provider).
[0280] The flowcharts and block diagrams in the accompanying drawings illustrate the architecture, functionality, and operation of possible implementations of systems, methods, and computer program products according to various embodiments of this disclosure. In this regard, each block in a flowchart or block diagram may represent a module, segment, or portion of code containing one or more executable instructions for implementing a specified logical function. It should also be noted that in some alternative implementations, the functions indicated in the blocks may occur in a different order than those indicated in the drawings. For example, two consecutively indicated blocks may actually be executed substantially in parallel, and they may sometimes be executed in reverse order, depending on the functions involved. It should also be noted that each block in the block diagrams and / or flowcharts, and combinations of blocks in the block diagrams and / or flowcharts, can be implemented using a dedicated hardware-based system that performs the specified function or operation, or using a combination of dedicated hardware and computer instructions.
[0281] The units described in the embodiments of this disclosure can be implemented in software or in hardware. The name of a unit does not necessarily limit the unit itself; for example, the first acquisition unit can also be described as "a unit that acquires at least two Internet Protocol addresses".
[0282] The functions described above in this document can be performed at least in part by one or more hardware logic components. For example, exemplary types of hardware logic components that can be used, without limitation, include: field-programmable gate arrays (FPGAs), application-specific integrated circuits (ASICs), application-specific standard products (ASSPs), system-on-a-chip (SoCs), complex programmable logic devices (CPLDs), and so on.
[0283] In the context of this disclosure, a machine-readable medium can be a tangible medium that may contain or store a program for use by or in conjunction with an instruction execution system, apparatus, or device. A machine-readable medium can be a machine-readable signal medium or a machine-readable storage medium. A machine-readable medium can be, but is not limited to, electronic, magnetic, optical, electromagnetic, infrared, or semiconductor systems, apparatus, or devices, or any suitable combination of the foregoing. More specific examples of machine-readable storage media include electrical connections based on one or more wires, portable computer disks, hard disks, random access memory (RAM), read-only memory (ROM), erasable programmable read-only memory (EPROM or flash memory), optical fiber, portable compact disk read-only memory (CD-ROM), optical storage devices, magnetic storage devices, or any suitable combination of the foregoing.
[0284] The code similarity detection device in this application embodiment can be used to execute the technical solutions in the above-described method embodiments of this application. Its implementation principle and technical effect are similar, and will not be repeated here.
[0285] This application also provides a computer-readable storage medium storing computer-executable instructions, which, when executed by a processor, are used to implement a code similarity detection method for any of the above-mentioned methods.
[0286] This application also provides a computer program product, including a computer program, which, when executed by a processor, is used to implement a code similarity detection method for any of the above-mentioned items.
[0287] In the several embodiments provided in this application, it should be understood that the disclosed systems, apparatuses, and methods can be implemented in other ways. For example, the apparatus embodiments described above are merely illustrative; for instance, the division of units is only a logical functional division, and in actual implementation, there may be other division methods. For example, multiple units or components may be combined or integrated into another system, or some features may be ignored or not executed. Furthermore, the coupling or direct coupling or communication connection shown or discussed may be through some interfaces, or indirect coupling or communication connection between apparatuses or units, and may be electrical, mechanical, or other forms.
[0288] Furthermore, the functional units in the various embodiments of this application can be integrated into one processing unit, or each unit can exist physically separately, or two or more units can be integrated into one unit. The integrated unit can be implemented in hardware or as a software functional unit.
[0289] Other embodiments of this application will readily occur to those skilled in the art upon consideration of the specification and practice of the invention disclosed herein. This application is intended to cover any variations, uses, or adaptations of this application that follow the general principles of this application and include common knowledge or customary techniques in the art not disclosed herein. The specification and examples are to be considered exemplary only, and the true scope and spirit of this application are indicated by the following claims.
[0290] It should be understood that this application is not limited to the precise structure described above and shown in the accompanying drawings, and various modifications and changes can be made without departing from its scope. The scope of this application is limited only by the appended claims.
Claims
1. A method of detecting code similarity, characterized by, include: Obtain a set of code project files to be compared; wherein, the set of code project files to be compared includes any two code project files; The code project file is parsed to obtain the corresponding graph structure information; wherein, the graph structure information includes nodes and edges, the nodes are used to represent the programming elements in the code project file, and the edges are used to represent the logical relationships in the code project file; Based on the graph structure information, a corresponding code graph is generated; Calculate the first similarity based on the code graph; Based on the code project file, determine the code text; Calculate the second similarity based on the code text; Calculate the overall similarity between any two code project files based on the first similarity and the second similarity.
2. The method of claim 1, wherein, The parsing and processing of the code project file to obtain the corresponding graph structure information includes: The code project file is parsed to extract multiple programming elements from the code project file, and corresponding nodes are created based on the programming elements; Extract the logical relationships between the programming elements in the code project file; Based on the logical relationship, corresponding edges are established between the nodes.
3. The method of claim 2, wherein, The nodes include class nodes, interface nodes, variable nodes, function / method nodes, and instance nodes, which correspond to the programming elements respectively; The logical relationships include multiple relationships such as instantiation, inclusion, inheritance, access, and invocation.
4. The method of claim 3, wherein, The step of establishing corresponding edges between the nodes according to the logical relationship includes at least one of the following: Establish corresponding edges between class nodes and instance nodes that have an instantiation relationship; Establish corresponding edges between class nodes and variable nodes and / or function nodes that have an inclusion relationship; Establish corresponding edges between class nodes that have inheritance relationships; Establish corresponding edges between interface nodes and class nodes that have access relationships; Establish corresponding edges between function nodes, instance nodes, and function nodes and variable nodes that have a calling relationship.
5. The method according to any one of claims 1 to 4, characterized in that, The step of calculating the first similarity based on the code graph includes: The code map is standardized to obtain a standardized map; Based on the standardized graph, construct the adjacency tensor; The adjacency tensor is mapped to obtain the mapping result; The first similarity is calculated based on the overlap of the mapping results.
6. The method according to any one of claims 1 to 4, characterized in that, The step of calculating the second similarity based on the code text includes: The code text is preprocessed to obtain preprocessed text; wherein, the preprocessing includes comment removal and / or identifier normalization. Based on the preprocessed text, text similarity is calculated to obtain the second similarity.
7. The method according to any one of claims 1 to 4, characterized in that, The step of calculating the comprehensive similarity between any two code project files based on the first similarity and the second similarity includes: Obtain weight information; wherein the weight information includes a first weight and a second weight, and the sum of the first weight and the second weight is 1; The first similarity and the second similarity are weighted according to the first weight and the second weight to obtain the comprehensive similarity.
8. The method according to claim 7, characterized in that, The acquisition of weight information includes: Obtain the application scenario type corresponding to the set of code project files to be compared; The weight information is determined based on the application scenario type and the preset correspondence between the application scenario type and the weight information.
9. A code similarity detection device, characterized in that, include: The acquisition module is used to acquire a set of code project files to be compared; wherein, the set of code project files to be compared includes any two code project files; The parsing module is used to parse the code project file to obtain the corresponding graph structure information; wherein, the graph structure information includes nodes and edges, the nodes are used to represent the programming elements in the code project file, and the edges are used to represent the logical relationships in the code project file; The generation module is used to generate a corresponding code map based on the map structure information; The first calculation module is used to calculate a first similarity based on the code graph; The determination module is used to determine the code text based on the code project file; The second calculation module is used to calculate a second similarity based on the code text; The third calculation module is used to calculate the comprehensive similarity between any two code project files based on the first similarity and the second similarity.
10. An electronic device, characterized in that, include: A processor, and a memory communicatively connected to the processor; The memory stores computer-executed instructions; The processor executes computer execution instructions stored in the memory to implement the method as described in any one of claims 1 to 8.
11. A computer-readable storage medium, characterized in that, The computer-readable storage medium stores computer-executable instructions, which, when executed by a processor, are used to implement the method as described in any one of claims 1 to 8.
12. A computer program product, characterized in that, Includes a computer program that, when executed by a processor, implements the method of any one of claims 1 to 8.
