Spaces:
Sleeping
Sleeping
Add code chunking functionality
Browse filesFiles changed (18)
- .github/workflows/main.ymlAdded+20
- .idea/.gitignoreAdded+8
- .idea/code-chunker.imlAdded+15
- .idea/misc.xmlAdded+9
- .idea/modules.xmlAdded+8
- .idea/vcs.xmlAdded+6
- Chunker.py+14-14
- LICENSE+21-201
- README.md+30-9
- __pycache__/Chunker.cpython-312.pyc
- __pycache__/test_code_chunker.cpython-312.pyc
- __pycache__/utils.cpython-312.pyc
- app.pyAdded+88
- cintra/documentation.jsonAdded+7
- mock_codefiles.json+29-26
- requirements.txt+24-46
- test_code_chunker.py+70
- utils.py-2
1234567891011121314151617181920name: Sync to Hugging Face hubon: push: branches: [main]
# to run this workflow manually from the Actions tab workflow_dispatch:
jobs: sync-to-hub: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 with: fetch-depth: 0 lfs: true - name: Push to hub env: HF_TOKEN: ${{ secrets.HF_TOKEN }} run: git push https://jsham042:$HF_TOKEN@huggingface.co/spaces/CintraAI/code-chunker main12345678# Default ignored files/shelf//workspace.xml# Editor-based HTTP Client requests/httpRequests/# Datasource local storage ignored files/dataSources//dataSources.local.xml123456789101112131415<?xml version="1.0" encoding="UTF-8"?><module type="JAVA_MODULE" version="4"> <component name="NewModuleRootManager" inherit-compiler-output="true"> <exclude-output /> <content url="file://$MODULE_DIR$"> <excludeFolder url="file://$MODULE_DIR$/venv" /> </content> <orderEntry type="inheritedJdk" /> <orderEntry type="sourceFolder" forTests="false" /> </component> <component name="PackageRequirementsSettings"> <option name="removeUnused" value="true" /> <option name="modifyBaseFiles" value="true" /> </component></module>123456789<?xml version="1.0" encoding="UTF-8"?><project version="4"> <component name="Black"> <option name="sdkName" value="Python 3.12 (code-chunker)" /> </component> <component name="ProjectRootManager" version="2" languageLevel="JDK_21" project-jdk-name="Python 3.12 (code-chunker)" project-jdk-type="Python SDK"> <output url="file://$PROJECT_DIR$/out" /> </component></project>12345678<?xml version="1.0" encoding="UTF-8"?><project version="4"> <component name="ProjectModuleManager"> <modules> <module fileurl="file://$PROJECT_DIR$/.idea/code-chunker.iml" filepath="$PROJECT_DIR$/.idea/code-chunker.iml" /> </modules> </component></project>123456<?xml version="1.0" encoding="UTF-8"?><project version="4"> <component name="VcsDirectoryMappings"> <mapping directory="" vcs="Git" /> </component></project>2 unmodified lines345678910 unmodified lines2021222324252627282930313233343536373821 unmodified lines6061626364656667686970717273744 unmodified lines79808182838485868788899091929394959697984 unmodified lines1031041051061071081096 unmodified lines1161171181191201211221231242 unmodified linesfrom utils import count_tokensclass Chunker(ABC):def __init__(self, encoding_name="gpt-4"):self.encoding_name = encoding_name10 unmodified linesdef print_chunks(chunks):for chunk_number, chunk_code in chunks.items():print(f"Chunk {chunk_number}:")print("="*40)print(chunk_code)print("="*40)@staticmethoddef consolidate_chunks_into_file(chunks):return "\n".join(chunks.values())@staticmethoddef count_lines(consolidated_chunks):lines = consolidated_chunks.split("\n")return len(lines)class CodeChunker(Chunker):def __init__(self, file_extension, encoding_name="gpt-4"):super().__init__(encoding_name)21 unmodified linesif highest_comment_line: # If a highest comment line exists, add itadjusted_breakpoints.append(highest_comment_line)else:adjusted_breakpoints.append(bp) # If no comments were found before the breakpoint, add the original breakpointbreakpoints = sorted(set(adjusted_breakpoints)) # Ensure breakpoints are unique and sortedwhile i < len(lines):line = lines[i]new_token_count = count_tokens(line, self.encoding_name)if token_count + new_token_count > token_limit:# Set the stop line to the last breakpoint before the current lineif i in breakpoints:stop_line = i4 unmodified linesif stop_line == start_line and i not in breakpoints:token_count += new_token_counti += 1# If the stop line is the same as the start line and the current line is a breakpoint, it means we can create a chunk with just the current lineelif stop_line == start_line and i == stop_line:token_count += new_token_counti += 1# If the stop line is the same as the start line and the current line is a breakpoint, it means we can create a chunk with just the current lineelif stop_line == start_line and i in breakpoints:current_chunk = "\n".join(lines[start_line:stop_line])if current_chunk.strip(): # If the current chunk is not just whitespacechunks[chunk_number] = current_chunk # Using chunk_number as keychunk_number += 1token_count = 0start_line = ii += 14 unmodified linesif current_chunk.strip():chunks[chunk_number] = current_chunk # Using chunk_number as keychunk_number += 1i = stop_linetoken_count = 0start_line = stop_line6 unmodified linescurrent_chunk_code = "\n".join(lines[start_line:])if current_chunk_code.strip(): # Checks if the chunk is not just whitespacechunks[chunk_number] = current_chunk_code # Using chunk_number as keyreturn chunksdef get_chunk(self, chunked_codebase, chunk_number):return chunked_codebase[chunk_number]2 unmodified lines34567810 unmodified lines192021222324252627282930313233343536373821 unmodified lines606162636465666768697071727374754 unmodified lines80818283848586878889909192939495969798994 unmodified lines1041051061071081091106 unmodified lines1171181191201211221231242 unmodified linesfrom utils import count_tokensclass Chunker(ABC):def __init__(self, encoding_name="gpt-4"):self.encoding_name = encoding_name10 unmodified linesdef print_chunks(chunks):for chunk_number, chunk_code in chunks.items():print(f"Chunk {chunk_number}:")print("=" * 40)print(chunk_code)print("=" * 40)@staticmethoddef consolidate_chunks_into_file(chunks):return "\n".join(chunks.values())@staticmethoddef count_lines(consolidated_chunks):lines = consolidated_chunks.split("\n")return len(lines)class CodeChunker(Chunker):def __init__(self, file_extension, encoding_name="gpt-4"):super().__init__(encoding_name)21 unmodified linesif highest_comment_line: # If a highest comment line exists, add itadjusted_breakpoints.append(highest_comment_line)else:adjusted_breakpoints.append(bp) # If no comments were found before the breakpoint, add the original breakpointbreakpoints = sorted(set(adjusted_breakpoints)) # Ensure breakpoints are unique and sortedwhile i < len(lines):line = lines[i]new_token_count = count_tokens(line, self.encoding_name)if token_count + new_token_count > token_limit:# Set the stop line to the last breakpoint before the current lineif i in breakpoints:stop_line = i4 unmodified linesif stop_line == start_line and i not in breakpoints:token_count += new_token_counti += 1# If the stop line is the same as the start line and the current line is a breakpoint, it means we can create a chunk with just the current lineelif stop_line == start_line and i == stop_line:token_count += new_token_counti += 1# If the stop line is the same as the start line and the current line is a breakpoint, it means we can create a chunk with just the current lineelif stop_line == start_line and i in breakpoints:current_chunk = "\n".join(lines[start_line:stop_line])if current_chunk.strip(): # If the current chunk is not just whitespacechunks[chunk_number] = current_chunk # Using chunk_number as keychunk_number += 1token_count = 0start_line = ii += 14 unmodified linesif current_chunk.strip():chunks[chunk_number] = current_chunk # Using chunk_number as keychunk_number += 1i = stop_linetoken_count = 0start_line = stop_line6 unmodified linescurrent_chunk_code = "\n".join(lines[start_line:])if current_chunk_code.strip(): # Checks if the chunk is not just whitespacechunks[chunk_number] = current_chunk_code # Using chunk_number as keyreturn chunksdef get_chunk(self, chunked_codebase, chunk_number):return chunked_codebase[chunk_number]
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201Apache LicenseVersion 2.0, January 2004http://www.apache.org/licenses/TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION1. Definitions."License" shall mean the terms and conditions for use, reproduction,and distribution as defined by Sections 1 through 9 of this document."Licensor" shall mean the copyright owner or entity authorized bythe copyright owner that is granting the License."Legal Entity" shall mean the union of the acting entity and allother entities that control, are controlled by, or are under commoncontrol with that entity. For the purposes of this definition,"control" means (i) the power, direct or indirect, to cause thedirection or management of such entity, whether by contract orotherwise, or (ii) ownership of fifty percent (50%) or more of theoutstanding shares, or (iii) beneficial ownership of such entity."You" (or "Your") shall mean an individual or Legal Entityexercising permissions granted by this License."Source" form shall mean the preferred form for making modifications,including but not limited to software source code, documentationsource, and configuration files."Object" form shall mean any form resulting from mechanicaltransformation or translation of a Source form, including butnot limited to compiled object code, generated documentation,and conversions to other media types."Work" shall mean the work of authorship, whether in Source orObject form, made available under the License, as indicated by acopyright notice that is included in or attached to the work(an example is provided in the Appendix below)."Derivative Works" shall mean any work, whether in Source or Objectform, that is based on (or derived from) the Work and for which theeditorial revisions, annotations, elaborations, or other modificationsrepresent, as a whole, an original work of authorship. For the purposesof this License, Derivative Works shall not include works that remainseparable from, or merely link (or bind by name) to the interfaces of,the Work and Derivative Works thereof."Contribution" shall mean any work of authorship, includingthe original version of the Work and any modifications or additionsto that Work or Derivative Works thereof, that is intentionallysubmitted to Licensor for inclusion in the Work by the copyright owneror by an individual or Legal Entity authorized to submit on behalf ofthe copyright owner. For the purposes of this definition, "submitted"means any form of electronic, verbal, or written communication sentto the Licensor or its representatives, including but not limited tocommunication on electronic mailing lists, source code control systems,and issue tracking systems that are managed by, or on behalf of, theLicensor for the purpose of discussing and improving the Work, butexcluding communication that is conspicuously marked or otherwisedesignated in writing by the copyright owner as "Not a Contribution.""Contributor" shall mean Licensor and any individual or Legal Entityon behalf of whom a Contribution has been received by Licensor andsubsequently incorporated within the Work.2. Grant of Copyright License. Subject to the terms and conditions ofthis License, each Contributor hereby grants to You a perpetual,worldwide, non-exclusive, no-charge, royalty-free, irrevocablecopyright license to reproduce, prepare Derivative Works of,publicly display, publicly perform, sublicense, and distribute theWork and such Derivative Works in Source or Object form.3. Grant of Patent License. Subject to the terms and conditions ofthis License, each Contributor hereby grants to You a perpetual,worldwide, non-exclusive, no-charge, royalty-free, irrevocable(except as stated in this section) patent license to make, have made,use, offer to sell, sell, import, and otherwise transfer the Work,where such license applies only to those patent claims licensableby such Contributor that are necessarily infringed by theirContribution(s) alone or by combination of their Contribution(s)with the Work to which such Contribution(s) was submitted. If Youinstitute patent litigation against any entity (including across-claim or counterclaim in a lawsuit) alleging that the Workor a Contribution incorporated within the Work constitutes director contributory patent infringement, then any patent licensesgranted to You under this License for that Work shall terminateas of the date such litigation is filed.4. Redistribution. You may reproduce and distribute copies of theWork or Derivative Works thereof in any medium, with or withoutmodifications, and in Source or Object form, provided that Youmeet the following conditions:(a) You must give any other recipients of the Work orDerivative Works a copy of this License; and(b) You must cause any modified files to carry prominent noticesstating that You changed the files; and(c) You must retain, in the Source form of any Derivative Worksthat You distribute, all copyright, patent, trademark, andattribution notices from the Source form of the Work,excluding those notices that do not pertain to any part ofthe Derivative Works; and(d) If the Work includes a "NOTICE" text file as part of itsdistribution, then any Derivative Works that You distribute mustinclude a readable copy of the attribution notices containedwithin such NOTICE file, excluding those notices that do notpertain to any part of the Derivative Works, in at least oneof the following places: within a NOTICE text file distributedas part of the Derivative Works; within the Source form ordocumentation, if provided along with the Derivative Works; or,within a display generated by the Derivative Works, if andwherever such third-party notices normally appear. The contentsof the NOTICE file are for informational purposes only anddo not modify the License. You may add Your own attributionnotices within Derivative Works that You distribute, alongsideor as an addendum to the NOTICE text from the Work, providedthat such additional attribution notices cannot be construedas modifying the License.You may add Your own copyright statement to Your modifications andmay provide additional or different license terms and conditionsfor use, reproduction, or distribution of Your modifications, orfor any such Derivative Works as a whole, provided Your use,reproduction, and distribution of the Work otherwise complies withthe conditions stated in this License.5. Submission of Contributions. Unless You explicitly state otherwise,any Contribution intentionally submitted for inclusion in the Workby You to the Licensor shall be under the terms and conditions ofthis License, without any additional terms or conditions.Notwithstanding the above, nothing herein shall supersede or modifythe terms of any separate license agreement you may have executedwith Licensor regarding such Contributions.6. Trademarks. This License does not grant permission to use the tradenames, trademarks, service marks, or product names of the Licensor,except as required for reasonable and customary use in describing theorigin of the Work and reproducing the content of the NOTICE file.7. Disclaimer of Warranty. Unless required by applicable law oragreed to in writing, Licensor provides the Work (and eachContributor provides its Contributions) on an "AS IS" BASIS,WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express orimplied, including, without limitation, any warranties or conditionsof TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR APARTICULAR PURPOSE. You are solely responsible for determining theappropriateness of using or redistributing the Work and assume anyrisks associated with Your exercise of permissions under this License.8. Limitation of Liability. In no event and under no legal theory,whether in tort (including negligence), contract, or otherwise,unless required by applicable law (such as deliberate and grosslynegligent acts) or agreed to in writing, shall any Contributor beliable to You for damages, including any direct, indirect, special,incidental, or consequential damages of any character arising as aresult of this License or out of the use or inability to use theWork (including but not limited to damages for loss of goodwill,work stoppage, computer failure or malfunction, or any and allother commercial damages or losses), even if such Contributorhas been advised of the possibility of such damages.9. Accepting Warranty or Additional Liability. While redistributingthe Work or Derivative Works thereof, You may choose to offer,and charge a fee for, acceptance of support, warranty, indemnity,or other liability obligations and/or rights consistent with thisLicense. However, in accepting such obligations, You may act onlyon Your own behalf and on Your sole responsibility, not on behalfof any other Contributor, and only if You agree to indemnify,defend, and hold each Contributor harmless for any liabilityincurred by, or claims asserted against, such Contributor by reasonof your accepting any such warranty or additional liability.END OF TERMS AND CONDITIONSAPPENDIX: How to apply the Apache License to your work.To apply the Apache License to your work, attach the followingboilerplate notice, with the fields enclosed by brackets "[]"replaced with your own identifying information. (Don't includethe brackets!) The text should be enclosed in the appropriatecomment syntax for the file format. We also recommend that afile or class name and description of purpose be included on thesame "printed page" as the copyright notice for easieridentification within third-party archives.Copyright [yyyy] [name of copyright owner]Licensed under the Apache License, Version 2.0 (the "License");you may not use this file except in compliance with the License.You may obtain a copy of the License athttp://www.apache.org/licenses/LICENSE-2.0Unless required by applicable law or agreed to in writing, softwaredistributed under the License is distributed on an "AS IS" BASIS,WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.See the License for the specific language governing permissions andlimitations under the License.123456789101112131415161718192021MIT LicenseCopyright (c) 2024 CINTRAAI Code ChunkerPermission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.
1233 unmodified lines7891011121314151617181920212223242526272829304 unmodified lines35363738394041423 unmodified lines464748495051525354555657585960616263646566# CintraAI Code ChunkerCintra's Code Chunker is a novel open-source tool designed to enhance code readability and maintainability by intelligently chunking code files based on key points of interest. This tool leverages advanced parsing techniques to identify significant elements in your code, such as functions, classes, and comments, to organize your codebase into manageable, easily understandable chunks. It's an invaluable resource for applications such as RAG, code patching, and other use cases.3 unmodified lines- **Intelligent Chunking:** Break down your code files into chunks around key points of interest like function definitions, class declarations, and crucial comments.- **Customizable Token Limits:** Control the size of each chunk with customizable token limits, ensuring that chunks remain manageable and focused.- **Support for Multiple Languages:** Initially supporting Python, JavaScript, and CSS, with plans to expand to more programming languages.## Getting Started### Prerequisites- Python 3.8+- OpenAI API key (for token counting features)### Installation1. Clone the repository:```shgit clone https://github.com/yourgithubusername/code-chunker-parser.git```2. Navigate to the project directory```shpip install -r requirements.txt```4. Install the required dependencies```sh4 unmodified linesUse the CodeChunker class to chunk a specific code file. You can specify the file extension and token limit for chunking.Example:```pyfrom backend.app.util.TextChunker.Chunker import CodeChunkerchunker = CodeChunker(file_extension='py', encoding_name='gpt-4')chunks = chunker.chunk(your_code_here, token_limit=1000)CodeChunker.print_chunks(chunks)3 unmodified linesThe CodeParser class allows you to parse code to identify points of interest and comments, which can then be used for chunking or other analysis.Example:```from backend.app.util.CodeParsing.CodeParser import CodeParserparser = CodeParser(['py'])tree = parser.parse_code(your_code_here, 'py')points_of_interest = parser.extract_points_of_interest(tree, 'py')```## ContributingWe welcome contributions from the community, whether it's through reporting bugs, submitting feature requests, or sending pull requests. Please check the CONTRIBUTING.md file for more details on how to contribute to the project.## LicenseThis project is licensed under the Apache 2.0 license. See the License file for details## Acknowledgments- This project utilizes the tree-sitter project for parsing code.- This also uses tiktoken to count tokens for determining chunk sizes.123456789101112131415163 unmodified lines20212223242526272829303132333435363738394041424344454647484 unmodified lines5354555657583 unmodified lines6263646566676869707172737475767778798081828384858687---title: CintraAI Code Chunkeremoji: 🧩colorFrom: bluecolorTo: indigosdk: streamlitsdk_version: 1.33.0app_file: app.pypinned: falselicense: mit---# CintraAI Code ChunkerCintra's Code Chunker is a novel open-source tool designed to enhance code readability and maintainability by intelligently chunking code files based on key points of interest. This tool leverages advanced parsing techniques to identify significant elements in your code, such as functions, classes, and comments, to organize your codebase into manageable, easily understandable chunks. It's an invaluable resource for applications such as RAG, code patching, and other use cases.3 unmodified lines- **Intelligent Chunking:** Break down your code files into chunks around key points of interest like function definitions, class declarations, and crucial comments.- **Customizable Token Limits:** Control the size of each chunk with customizable token limits, ensuring that chunks remain manageable and focused.- **Support for Multiple Languages:** Initially supporting Python, JavaScript, and CSS, with plans to expand to more programming languages.## Try Out Code Chunker!Interested in seeing how it works? Check out our interactive demo on **Hugging Face Spaces**.[**Click here to try it out!**](https://huggingface.co/spaces/CintraAI/code-chunker)## Getting Started### Prerequisites- Python 3.8+### Installation1. Clone the repository:```shgit clone https://github.com/yourgithubusername/code-chunker.git```2. Navigate to the project directory```shcd code-chunker```4. Install the required dependencies```sh4 unmodified linesUse the CodeChunker class to chunk a specific code file. You can specify the file extension and token limit for chunking.Example:```pychunker = CodeChunker(file_extension='py', encoding_name='gpt-4')chunks = chunker.chunk(your_code_here, token_limit=1000)CodeChunker.print_chunks(chunks)3 unmodified linesThe CodeParser class allows you to parse code to identify points of interest and comments, which can then be used for chunking or other analysis.Example:```parser = CodeParser(['py'])tree = parser.parse_code(your_code_here, 'py')points_of_interest = parser.extract_points_of_interest(tree, 'py')```3. Understanding the Token Limit in Chunking:In the `chunk` method of the `Chunker` class, a `token_limit` parameter is used to control the size of each chunk of code. A 'token' can be thought of as the smallest unit of processing. In the context of text processing, a token could be a word, a sentence, or a similar unit.The `token_limit` parameter limits the number of these tokens for each chunk. If the limit is, for instance, 100 tokens, that means each chunk of content produced by the `chunk` method should contain no more than 100 tokens.It is worth noting that the way content is tokenized and how a token is defined depends on the specific implementation and the type of content being processed.## ContributingWe welcome contributions from the community, whether it's through reporting bugs, submitting feature requests, or sending pull requests. Please check the CONTRIBUTING.md file for more details on how to contribute to the project.## LicenseThis project is licensed under the MIT license. See the License file for details## Acknowledgments- This project utilizes the tree-sitter project for parsing code.- This also uses tiktoken to count tokens for determining chunk sizes.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788import streamlit as stimport jsonimport osfrom Chunker import CodeChunker
# Set Streamlit page config at the very beginningst.set_page_config(page_title="Cintra Code Chunker", layout="wide")
# Function to load JSON datadef load_json_file(file_path): with open(file_path, 'r') as file: return json.load(file)
# Function to read code from an uploaded filedef read_code_from_file(uploaded_file): return uploaded_file.getvalue().decode("utf-8")
st.link_button('Contribute on GitHub', 'https://github.com/CintraAI/code-chunker', help=None, type="secondary", disabled=False, use_container_width=False)
json_file_path = os.path.join(os.path.dirname(__file__), 'mock_codefiles.json')code_files_data = load_json_file(json_file_path)
# Extract filenames and contentscode_files = list(code_files_data.keys())
st.title('Cintra Code Chunker')
selection_col, upload_col = st.columns(2)with selection_col: # File selection dropdown selected_file_name = st.selectbox("Select an example code file", code_files)
with upload_col: # File upload uploaded_file = st.file_uploader("Or upload your code file", type=['py', 'js', 'css', 'jsx'])
# Determine the content and file extension based on selection or uploadif uploaded_file is not None: code_content = read_code_from_file(uploaded_file) file_extension = uploaded_file.name.split('.')[-1]else: code_content = code_files_data.get(selected_file_name, "") file_extension = selected_file_name.split('.')[-1] if selected_file_name else None
# Determine the language for syntax highlightingdef get_language_by_extension(file_extension): if file_extension in ['py', 'python']: return 'python' elif file_extension in ['js', 'jsx', 'javascript']: return 'javascript' elif file_extension == 'css': return 'css' else: return None
language = get_language_by_extension(file_extension)
st.write("""### Choose Chunk Size Target""")token_chunk_size = st.number_input('Target Chunk Size Target', min_value=5, max_value=1000, value=25, help="The token limit guides the chunk size in tokens (tiktoken, gpt-4), aiming for readability without enforcing a strict upper limit.")
with st.expander("Learn more about the chunk size target"): st.markdown("""The `token_limit` parameter in the `chunk` function serves as a guideline to optimize the size of code chunks produced. It is not a hard limit but rather an ideal target, attempting to achieve a balance between chunk size and maintaining logical coherence within the code.
- **Adherence to Logical Breakpoints:** The chunking logic respects logical breakpoints in the code, ensuring that chunks are coherent and maintain readability.- **Flexibility in Chunk Size:** Chunks might be slightly smaller or larger than the specified `token_limit` to avoid breaking the code in the middle of logical sections.- **Handling Final Chunks:** The last chunk of code captures any remaining code, which may vary significantly in size depending on the remaining code's structure.
This approach allows for flexibility in how code is segmented into chunks, emphasizing the balance between readable, logical code segments and size constraints. """)
original_col, chunked_col = st.columns(2)
with original_col: st.subheader('Original File') st.code(code_content, language=language)
# Initialize the code chunkercode_chunker = CodeChunker(file_extension=file_extension)
# Chunk the code contentchunked_code_dict = code_chunker.chunk(code_content, token_chunk_size)
with chunked_col: st.subheader('Chunked Code') for chunk_key, chunk_code in chunked_code_dict.items(): st.code(chunk_code, language=language)1234567{ "Chunker.py": "Description: This file provides functionality for chunking code into manageable segments based on token limits and breakpoints.\n\nDependencies: CodeParser, Utils\n\nFunctions:\n- Name: chunk\n Description: Divides code into chunks based on token limits and breakpoints.\n Parameters: content (str) - The code content to be chunked, token_limit (int) - The maximum number of tokens allowed in a chunk.\n Returns: dict - A dictionary containing the chunked code segments.\n\n- Name: get_chunk\n Description: Retrieves a specific chunk from the chunked codebase.\n Parameters: chunked_content (dict) - The dictionary of chunked code segments, chunk_number (int) - The number of the desired chunk.\n Returns: str - The code segment corresponding to the specified chunk number.\n\n- Name: print_chunks\n Description: Prints out the chunked code segments with a header for each chunk.\n Parameters: chunks (dict) - The dictionary of chunked code segments.\n Returns: None\n\n- Name: consolidate_chunks_into_file\n Description: Combines all chunked code segments into a single string for output.\n Parameters: chunks (dict) - The dictionary of chunked code segments.\n Returns: str - The consolidated code segments as a single string.\n\n- Name: count_lines\n Description: Counts the number of lines in the consolidated code segments.\n Parameters: consolidated_chunks (str) - The consolidated code segments as a single string.\n Returns: int - The total number of lines in the consolidated code.", "CodeParser.py": "Description: This file serves as a code parser for various programming languages, allowing for the extraction of points of interest and comments from code files.\n\nDependencies: os, subprocess, typing, tree_sitter, logging\n\nFunctions:\n- Name: \\_\\_init\\_\\_\n Description: Initializes the CodeParser object with the specified file extensions.\n Parameters: file_extensions (Union[None, List[str], str]) - The file extensions to parse.\n Returns: None\n\n- Name: parse_code\n Description: Parses the provided code based on the file extension.\n Parameters: code (str) - The code to parse, file_extension (str) - The extension of the code file.\n Returns: Union[None, Node] - The root node of the parsed code.\n\n- Name: extract_points_of_interest\n Description: Recursively extracts points of interest from the parsed code.\n Parameters: node (Node) - The current node being processed, file_extension (str) - The extension of the code file.\n Returns: List[Tuple[Node, str]] - A list of tuples containing nodes of interest and their types.\n\n- Name: extract_comments\n Description: Recursively extracts comments from the parsed code.\n Parameters: node (Node) - The current node being processed, file_extension (str) - The extension of the code file.\n Returns: List[Tuple[Node, str]] - A list of tuples containing comments and their types.\n\n- Name: get_lines_for_points_of_interest\n Description: Retrieves the line numbers of points of interest in the code.\n Parameters: code (str) - The code to analyze, file_extension (str) - The extension of the code file.\n Returns: List[int] - A list of line numbers with points of interest.\n\n- Name: get_lines_for_comments\n Description: Retrieves the line numbers of comments in the code.\n Parameters: code (str) - The code to analyze, file_extension (str) - The extension of the code file.\n Returns: List[int] - A list of line numbers with comments.\n\n- Name: print_all_line_types\n Description: Prints the line numbers with their corresponding node types.\n Parameters: code (str) - The code to analyze, file_extension (str) - The extension of the code file.\n Returns: None\n\n- Name: map_line_to_node_type\n Description: Maps line numbers to node types recursively.\n Parameters: node (Node) - The current node being processed, line_to_node_type (Dict) - Mapping of line numbers to node types, depth (int) - The depth of recursion.\n Returns: Dict[int, List[str]] - A dictionary mapping line numbers to node types.\n\n- Name: print_simple_line_numbers_with_code\n Description: Prints the line numbers with their corresponding code lines.\n Parameters: code (str) - The code to display.\n Returns: None", "app.py": "Description: This file utilizes the Streamlit library to create a simple user interface for selecting a value and displaying its square.\n\nDependencies: streamlit\n\nFunctions:\n- Name: slider\n Description: Creates a slider widget for selecting a numerical value.\n Parameters: None\n Returns: The selected value (int or float)\n\n- Name: write\n Description: Writes the provided values to the user interface.\n Parameters: values (any) - The values to be displayed.\n Returns: None", "test_code_chunker.py": "Description: This file contains unit tests for the CodeChunker class, which is responsible for chunking code files based on token limits.\n\nDependencies: unittest, unittest.mock, Chunker, CodeChunker, load_json, tiktoken, json, os\n\nFunctions:\n- Name: mock_count_tokens\n Description: Mocks the count_tokens function to return the number of tokens in a text string.\n Parameters: string (str) - The text string to count tokens for, encoding_name (str) - The name of the encoding model (default: 'gpt-4').\n Returns: int - The number of tokens in the text string.\n\n- Name: TestCodeChunkerPython\n Description: Python test class for testing code chunking functionality.\n Parameters: N/A\n Returns: N/A\n\n- Name: TestCodeChunkerJavaScript\n Description: JavaScript test class for testing code chunking functionality.\n Parameters: N/A\n Returns: N/A\n\n- Name: TestCodeChunkerCSS\n Description: CSS test class for testing code chunking functionality.\n Parameters: N/A\n Returns: N/A\n\nEach test method within the test classes follows a similar structure:\n- Description: Tests chunking code with specific characteristics (e.g., simple code, routes, models, main, utilities, big class, react component, media query, simple styles).\n- Parameters: py_code/js_code/css_code (str) - The code to be chunked, token_limit (int) - The limit of tokens per chunk.\n- Returns: N/A", "utils.py": "Description: This file provides functions for tokenizing text strings and loading JSON files.\n\nDependencies: tiktoken, json\n\nFunctions:\n- Name: count_tokens\n Description: Returns the number of tokens in a text string.\n Parameters: string (str) - The text string to tokenize, encoding_name (str) - The name of the encoding model to use.\n Returns: int - The number of tokens in the text string.\n\n- Name: load_json\n Description: Loads and parses a JSON file.\n Parameters: json_file (str) - The path to the JSON file to load.\n Returns: dict - The parsed JSON data from the file."}123456789101112131415161718192021222324252627{"simple.py": "import sys\n\n# This is a sample Python file\n\ndef main():\n print('Hello, world!')\n\nif __name__ == '__main__':\n main()","text_only.py": "# This file is empty and should test the chunker's ability to handle empty files\n","routes.py": "from flask import Flask, jsonify, request, redirect, url_for\napp = Flask(__name__)\n\n@app.route('/', methods=['GET'])\ndef home():\n return '<h1>Welcome to the Home Page</h1>', 200\n\n@authenticate # Hypothetical decorator for authentication\n@log_access # Hypothetical decorator for logging access\n@app.route('/api/data', methods=['GET'])\ndef get_data():\n # Simulate fetching data from a database or external service\n data = {'key': 'This is some data'}\n return jsonify(data), 200\n\n@app.route('/api/data/<int:data_id>', methods=['GET'])\ndef get_data_by_id(data_id):\n # Simulate fetching specific data by ID\n data = {'id': data_id, 'value': 'Specific data based on ID'}\n return jsonify(data), 200\n\n@app.route('/api/data', methods=['POST'])\ndef post_data():\n data = request.json\n # Simulate saving data to a database\n return jsonify({'message': 'Data saved successfully', 'data': data}), 201\n\n@app.route('/api/data/<int:data_id>', methods=['PUT'])\ndef update_data(data_id):\n data = request.json\n # Simulate updating data in a database\n return jsonify({'message': 'Data updated successfully', 'id': data_id, 'data': data}), 200\n\n@app.route('/api/data/<int:data_id>', methods=['DELETE'])\ndef delete_data(data_id):\n # Simulate deleting data by ID\n return jsonify({'message': 'Data deleted successfully', 'id': data_id}), 200\n\n@app.route('/redirect', methods=['GET'])\ndef example_redirect():\n return redirect(url_for('home'))\n\nif __name__ == '__main__':\n app.run(debug=True)","models.py": "from sqlalchemy import Column, Integer, String, ForeignKey\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import relationship\n\nBase = declarative_base()\n\nclass User(Base):\n __tablename__ = 'users'\n id = Column(Integer, primary_key=True)\n username = Column(String, unique=True, nullable=False)\n email = Column(String, unique=True, nullable=False)\n\n posts = relationship('Post', backref='author')\n\nclass Post(Base):\n __tablename__ = 'posts'\n id = Column(Integer, primary_key=True)\n title = Column(String, nullable=False)\n content = Column(String, nullable=False)\n user_id = Column(Integer, ForeignKey('users.id'))","big_class.py": "class BigClass:\n def __init__(self, name, age):\n self.name = name\n self.age = age\n\n def get_name(self):\n return self.name\n\n def get_age(self):\n return self.age\n\n def set_name(self, name):\n self.name = name\n\n def set_age(self, age):\n self.age = age\n\n def __str__(self):\n return f'Name: {self.name}, Age: {self.age}'","main.py": "from flask import Flask\nfrom routes import app as routes_app\n\n# Create the Flask application\napp = Flask(__name__)\n\n# Register the routes from the routes.py file\napp.register_blueprint(routes_app)\n\n# Configuration settings for the app can go here\napp.config['DEBUG'] = True\napp.config['SECRET_KEY'] = 'your_secret_key'\n\n# More complex app initialization steps can be added here\n# For example, database initialization, login manager setups, etc.\n\n# This function can be used to create a database schema\n def create_database(app):\n if not path.exists('yourdatabase.db'):\n db.create_all(app=app)\n print('Created Database!')\n\nif __name__ == '__main__':\n # Optionally, call database creation or other setup functions here\n create_database(app)\n app.run()","utilities.py": "import hashlib\nimport uuid\nimport re\nfrom datetime import datetime, timedelta\n\n# Function to hash a password\ndef hash_password(password):\n salt = uuid.uuid4().hex\n return hashlib.sha256(salt.encode() + password.encode()).hexdigest() + ':' + salt\n\n# Function to check a hashed password\ndef check_password(hashed_password, user_password):\n password, salt = hashed_password.split(':')\n return password == hashlib.sha256(salt.encode() + user_password.encode()).hexdigest()\n\n# Function to validate an email address\ndef validate_email(email):\n pattern = r\"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$\"\n return re.match(pattern, email) is not None\n\n# Function to generate a token expiration date\ndef generate_expiration_date(days=1):\n return datetime.now() + timedelta(days=days)\n\n# Function to convert a string to datetime\ndef string_to_datetime(date_string, format='%Y-%m-%d %H:%M:%S'):\n return datetime.strptime(date_string, format)\n\n# Function to convert datetime to string\ndef datetime_to_string(date, format='%Y-%m-%d %H:%M:%S'):\n return date.strftime(format)","services.py": "import requests\nfrom flask_sqlalchemy import SQLAlchemy\n\n# Assuming an initialized Flask app with SQLAlchemy\ndb = SQLAlchemy()\n\n# Example of a model for database operations\nclass UserData(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String(100), nullable=False)\n email = db.Column(db.String(100), unique=True, nullable=False)\n\n def __repr__(self):\n return f'<User {self.name}>'\n\n# Function to fetch data from an external API\ndef fetch_external_data(api_url):\n response = requests.get(api_url)\n if response.status_code == 200:\n return response.json()\n else:\n return {'error': 'Failed to fetch data'}\n\n# Function to save user data to the database\ndef save_user_data(name, email):\n new_user = UserData(name=name, email=email)\n db.session.add(new_user)\n try:\n db.session.commit()\n return {'message': 'User saved successfully'}\n except Exception as e:\n db.session.rollback()\n return {'error': str(e)}\n\n# Function to update user data in the database\ndef update_user_data(user_id, name=None, email=None):\n user = UserData.query.get(user_id)\n if not user:\n return {'error': 'User not found'}\n if name:\n user.name = name\n if email:\n user.email = email\n try:\n db.session.commit()\n return {'message': 'User updated successfully'}\n except Exception as e:\n db.session.rollback()\n return {'error': str(e)}\n\n# Function to delete user data from the database\ndef delete_user_data(user_id):\n user = UserData.query.get(user_id)\n if not user:\n return {'error': 'User not found'}\n try:\n db.session.delete(user)\n db.session.commit()\n return {'message': 'User deleted successfully'}\n except Exception as e:\n db.session.rollback()\n return {'error': str(e)}","simple.js": "// This is a sample JavaScript file\n\nfunction main() {\n console.log('Hello, world!');\n}\n\nmain();","text_only.js": "// This file is empty and should test the chunker's ability to handle empty files\n","routes.js": "const express = require('express');\nconst router = express.Router();\n\n// Example of a simple route\nrouter.get('/', (req, res) => {\n res.send('Welcome to the Home Page');\n});\n\n// Example of a route with a parameter\nrouter.get('/api/data/:data_id', (req, res) => {\n const dataId = req.params.data_id;\n res.json({ id: dataId, value: 'Specific data based on ID' });\n});\n\n// Example of a route that handles POST requests\nrouter.post('/api/data', (req, res) => {\n const data = req.body;\n res.status(201).json({ message: 'Data saved successfully', data: data });\n});\n\n// Example of a route that handles PUT requests\nrouter.put('/api/data/:data_id', (req, res) => {\n const dataId = req.params.data_id;\n const data = req.body;\n res.json({ message: 'Data updated successfully', id: dataId, data: data });\n});\n\n// Example of a route that handles DELETE requests\nrouter.delete('/api/data/:data_id', (req, res) => {\n const dataId = req.params.data_id;\n res.json({ message: 'Data deleted successfully', id: dataId });\n});\n\nmodule.exports = router;","models.js": "const mongoose = require('mongoose');\n\n// Example of a simple Mongoose model\nconst userSchema = new mongoose.Schema({\n username: { type: String, required: true, unique: true },\n email: { type: String, required: true, unique: true }\n});\n\nconst User = mongoose.model('User', userSchema);\n\nmodule.exports = User;","big_class.js": "// This is a sample JavaScript class with a large number of methods\n\nclass BigClass {\n constructor(name, age) {\n this.name = name;\n this.age = age;\n }\n\n getName() {\n return this.name;\n }\n\n getAge() {\n return this.age;\n }\n\n setName(name) {\n this.name = name;\n }\n\n setAge(age) {\n this.age = age;\n }\n\n toString() {\n return `Name: ${this.name}, Age: ${this.age}`;\n }\n}\n\nmodule.exports = BigClass;","main.js": "const express = require('express');\nconst routes = require('./routes');\n\n// Create the Express application\nconst app = express();\n\n// Register the routes from the routes.js file\napp.use('/', routes);\n\n// Configuration settings for the app can go here\napp.set('port', process.env.PORT || 3000);\n\n// More complex app initialization steps can be added here\n// For example, database initialization, middleware setups, etc.\n\n// This function can be used to create a database schema\nfunction createDatabase() {\n // Code to create database schema\n console.log('Created Database!');\n}\n\n// Optionally, call database creation or other setup functions here\ncreateDatabase();\n\n// Start the server\napp.listen(app.get('port'), () => {\n console.log(`Server running on port ${app.get('port')}`);\n});","utilities.js": "// Example of utility functions for common tasks\n\n// Function to hash a password\nfunction hashPassword(password) {\n const salt = uuidv4();\n return sha256(salt + password) + ':' + salt;\n}\n\n// Function to check a hashed password\nfunction checkPassword(hashedPassword, userPassword) {\n const [password, salt] = hashedPassword.split(':');\n return sha256(salt + userPassword) === password;\n}\n\n// Function to validate an email address\nfunction validateEmail(email) {\n const pattern = /^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$/;\n return pattern.test(email);\n}\n\n// Function to generate a token expiration date\nfunction generateExpirationDate(days = 1) {\n const expirationDate = new Date();\n expirationDate.setDate(expirationDate.getDate() + days);\n return expirationDate;\n}\n\n// Function to convert a string to a Date object\nfunction stringToDate(dateString, format = 'YYYY-MM-DD HH:mm:ss') {\n return new Date(dateString);\n}\n\n// Function to convert a Date object to a string\nfunction dateToString(date, format = 'YYYY-MM-DD HH:mm:ss') {\n return date.toISOString();\n}","services.js": "// Example of service functions for handling data operations\n\n// Function to fetch data from an external API\nasync function fetchExternalData(apiUrl) {\n try {\n const response = await fetch(apiUrl);\n if (response.ok) {\n return await response.json();\n } else {\n return { error: 'Failed to fetch data' };\n }\n } catch (error) {\n return { error: error.message };\n }\n}\n\n// Function to save user data to the database\nasync function saveUserData(name, email) {\n try {\n const newUser = new UserData({ name, email });\n await newUser.save();\n return { message: 'User saved successfully' };\n } catch (error) {\n return { error: error.message };\n }\n}\n\n// Function to update user data in the database\nasync function updateUserData(userId, name, email) {\n try {\n const user = await UserData.findById(userId);\n if (!user) {\n return { error: 'User not found' };\n }\n if (name) {\n user.name = name;\n }\n if (email) {\n user.email = email;\n }\n await user.save();\n return { message: 'User updated successfully' };\n } catch (error) {\n return { error: error.message };\n }\n}\n\n// Function to delete user data from the database\nasync function deleteUserData(userId) {\n try {\n const user = await UserData.findById(userId);\n if (!user) {\n return { error: 'User not found' };\n }\n await user.remove();\n return { message: 'User deleted successfully' };\n } catch (error) {\n return { error: error.message };\n }\n}","react_component.js": "import React from 'react';\n\nimport './SearchResults.css';\n\nimport TrackList from '../TrackList/TrackList.js';\n\n constructor(props) {\n super(props);\n this.addTopFive = this.addTopFive.bind(this);\n this.addTopTen = this.addTopTen.bind(this);\n this.addAll = this.addAll.bind(this);\n }\n\n //add the top five tracks to the playlist\n addTopFive() {\n this.props.onAdd(this.props.searchResults.slice(0, 5));\n }\n\n //add top 10 tracks to the playlist\n addTopTen() {\n this.props.onAdd(this.props.searchResults.slice(0, 10));\n }\n\n addAll() {\n this.props.onAdd(this.props.searchResults);\n }\n render() {\n return (\n <div className=\"SearchResults\">\n <h2>Results</h2>\n <TrackList tracks={this.props.searchResults} onAdd={this.props.onAdd} onToggle={this.props.onToggle} currentTrack={this.props.currentTrack}/>\n </div>\n );\n }\n}\n\nexport default SearchResults;'","simple_styles.css": "/* Example of CSS styles for a web page */\n\nbody {\n font-family: Arial, sans-serif;\n background-color: #f4f4f4;\n margin: 0;\n padding: 0;\n}\n\nh1 {\n color: #333;\n text-align: center;\n}\n\nbutton {\n padding: 10px 20px;\n font-size: 16px;\n background-color: #007bff;\n color: #fff;\n border: none;\n cursor: pointer;\n}\n\nbutton:hover {\n background-color: #0056b3;\n}","media_queries.css": "/* Example of CSS styles with media queries for responsive design */\n\nbody {\n font-family: Arial, sans-serif;\n background-color: #f4f4f4;\n margin: 0;\n padding: 0;\n}\n\nh1 {\n color: #333;\n text-align: center;\n}\n\nbutton {\n padding: 10px 20px;\n font-size: 16px;\n background-color: #007bff;\n color: #fff;\n border: none;\n cursor: pointer;\n}\n\nbutton:hover {\n background-color: #0056b3;\n}\n\n/* Media query for smaller screens */\n@media (max-width: 768px) {\n button {\n padding: 8px 16px;\n font-size: 14px;\n }\n}","single_syntax_error_example.py": "# This is a sample Python file\n\nprint('Hello, world!'\n\n","multiple_syntax_errors.py": "def calculate_sum(lst):\n total = 0\n for num in lst\n total += num\n return total\n\nprint(calculate_sum([1, 2, 3, 4])\n\ndef string_manipulator(s):\n new_string = ''\n for char in s:\n if char == 'a':\n new_string += 'z'\n else:\n new_string += char\n return new_string\n\nprint(string_manipulate('banana'))\n\ndef find_max(numbers):\n max_num = numbers[0]\n for num in numbers\n if num > max_num\n max_num = num\n return max_num\n\nprint(find_max([1, 2, 3, 4, 5])","single_syntax_error_example.js": "//This is a sample JavaScript file\n\nfunction main() {\n console.log('Hello, world!');\n if (true) {\n console.log('hi');\n \n}\n\nmain();","multiple_syntax_errors.js": "function calculateSum(arr) {\n let total = 0;\n for (let i = 0; i < arr.length; i++ {\n total += arr[i];\n }\n return total;\n}\n\nconsole.log(calculateSum([1, 2, 3, 4);\n\nfunction stringManipulator(str) {\n let newString = '';\n for (let i = 0; i < str.length; i++) {\n if (str.charAt(i) === 'a')\n newString += 'z';\n } else {\n newString += str.charAt(i);\n }\n }\n return newString;\n}\n\nconsole.log(stringManipulator('banana'));\n\nfunction findMax(numbers) {\n let maxNum = numbers[0];\n for (let i = 1; i < numbers.length; i++) {\n if (numbers[i] > maxNum) {\n maxNum = numbers[i];\n }\n }\n return maxNum;\n}\n\nconsole.log(findMax([1, 2, 3, 4, 5]);","single_syntax_error_example.css": "\n\nbody {\n font-family: Arial, sans-serif;\n background-color: #f4f4f4;\n margin: 0;\n padding: 0;\n}\n\nh1 {\n color: #333;\n text-align: center;\n}\n\nbutton {\n padding: 10px 20px;\n font-size: 16px;\n background-color: #007bff;\n color: #fff;\n border: none;\n cursor: pointer;\n :hover {\n background-color: #0056b3;\n}\n","multiple_syntax_errors.css": "body {\n font-family: Arial, sans-serif;\n background-color: #f4f4f4;\n margin: 0;\n padding: 0;\n}\n\nh1 {\n color: #333;\n text-align: center;\n}\n\nbutton {\n padding: 10px 20px;\n font-size: 16px;\n background-color: #007bff;\n color: #fff;\n border: none;\n cursor: pointer;\n :hover {\n background-color: #0056b3;\n}\n\n/* Media query for smaller screens */\n@media (max-width: 768px) {\n button {\n padding: 8px 16px;\n font-size: 14px;\n }\n}"}123456789101112131415161718192021222324252627282930{"simple.py": "import sys\n\n# This is a sample Python file\n\ndef main():\n print('Hello, world!')\n\nif __name__ == '__main__':\n main()","text_only.py": "# This file is empty and should test the chunker's ability to handle empty files\n","routes.py": "from flask import Flask, jsonify, request, redirect, url_for\napp = Flask(__name__)\n\n@app.route('/', methods=['GET'])\ndef home():\n return '<h1>Welcome to the Home Page</h1>', 200\n\n@authenticate # Hypothetical decorator for authentication\n@log_access # Hypothetical decorator for logging access\n@app.route('/api/data', methods=['GET'])\ndef get_data():\n # Simulate fetching data from a database or external service\n data = {'key': 'This is some data'}\n return jsonify(data), 200\n\n@app.route('/api/data/<int:data_id>', methods=['GET'])\ndef get_data_by_id(data_id):\n # Simulate fetching specific data by ID\n data = {'id': data_id, 'value': 'Specific data based on ID'}\n return jsonify(data), 200\n\n@app.route('/api/data', methods=['POST'])\ndef post_data():\n data = request.json\n # Simulate saving data to a database\n return jsonify({'message': 'Data saved successfully', 'data': data}), 201\n\n@app.route('/api/data/<int:data_id>', methods=['PUT'])\ndef update_data(data_id):\n data = request.json\n # Simulate updating data in a database\n return jsonify({'message': 'Data updated successfully', 'id': data_id, 'data': data}), 200\n\n@app.route('/api/data/<int:data_id>', methods=['DELETE'])\ndef delete_data(data_id):\n # Simulate deleting data by ID\n return jsonify({'message': 'Data deleted successfully', 'id': data_id}), 200\n\n@app.route('/redirect', methods=['GET'])\ndef example_redirect():\n return redirect(url_for('home'))\n\nif __name__ == '__main__':\n app.run(debug=True)","models.py": "from sqlalchemy import Column, Integer, String, ForeignKey\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import relationship\n\nBase = declarative_base()\n\nclass User(Base):\n __tablename__ = 'users'\n id = Column(Integer, primary_key=True)\n username = Column(String, unique=True, nullable=False)\n email = Column(String, unique=True, nullable=False)\n\n posts = relationship('Post', backref='author')\n\nclass Post(Base):\n __tablename__ = 'posts'\n id = Column(Integer, primary_key=True)\n title = Column(String, nullable=False)\n content = Column(String, nullable=False)\n user_id = Column(Integer, ForeignKey('users.id'))","big_class.py": "class BigClass:\n def __init__(self, name, age):\n self.name = name\n self.age = age\n\n def get_name(self):\n return self.name\n\n def get_age(self):\n return self.age\n\n def set_name(self, name):\n self.name = name\n\n def set_age(self, age):\n self.age = age\n\n def __str__(self):\n return f'Name: {self.name}, Age: {self.age}'","main.py": "from flask import Flask\nfrom routes import app as routes_app\n\n# Create the Flask application\napp = Flask(__name__)\n\n# Register the routes from the routes.py file\napp.register_blueprint(routes_app)\n\n# Configuration settings for the app can go here\napp.config['DEBUG'] = True\napp.config['SECRET_KEY'] = 'your_secret_key'\n\n# More complex app initialization steps can be added here\n# For example, database initialization, login manager setups, etc.\n\n# This function can be used to create a database schema\n def create_database(app):\n if not path.exists('yourdatabase.db'):\n db.create_all(app=app)\n print('Created Database!')\n\nif __name__ == '__main__':\n # Optionally, call database creation or other setup functions here\n create_database(app)\n app.run()","utilities.py": "import hashlib\nimport uuid\nimport re\nfrom datetime import datetime, timedelta\n\n# Function to hash a password\ndef hash_password(password):\n salt = uuid.uuid4().hex\n return hashlib.sha256(salt.encode() + password.encode()).hexdigest() + ':' + salt\n\n# Function to check a hashed password\ndef check_password(hashed_password, user_password):\n password, salt = hashed_password.split(':')\n return password == hashlib.sha256(salt.encode() + user_password.encode()).hexdigest()\n\n# Function to validate an email address\ndef validate_email(email):\n pattern = r\"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$\"\n return re.match(pattern, email) is not None\n\n# Function to generate a token expiration date\ndef generate_expiration_date(days=1):\n return datetime.now() + timedelta(days=days)\n\n# Function to convert a string to datetime\ndef string_to_datetime(date_string, format='%Y-%m-%d %H:%M:%S'):\n return datetime.strptime(date_string, format)\n\n# Function to convert datetime to string\ndef datetime_to_string(date, format='%Y-%m-%d %H:%M:%S'):\n return date.strftime(format)","services.py": "import requests\nfrom flask_sqlalchemy import SQLAlchemy\n\n# Assuming an initialized Flask app with SQLAlchemy\ndb = SQLAlchemy()\n\n# Example of a model for database operations\nclass UserData(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String(100), nullable=False)\n email = db.Column(db.String(100), unique=True, nullable=False)\n\n def __repr__(self):\n return f'<User {self.name}>'\n\n# Function to fetch data from an external API\ndef fetch_external_data(api_url):\n response = requests.get(api_url)\n if response.status_code == 200:\n return response.json()\n else:\n return {'error': 'Failed to fetch data'}\n\n# Function to save user data to the database\ndef save_user_data(name, email):\n new_user = UserData(name=name, email=email)\n db.session.add(new_user)\n try:\n db.session.commit()\n return {'message': 'User saved successfully'}\n except Exception as e:\n db.session.rollback()\n return {'error': str(e)}\n\n# Function to update user data in the database\ndef update_user_data(user_id, name=None, email=None):\n user = UserData.query.get(user_id)\n if not user:\n return {'error': 'User not found'}\n if name:\n user.name = name\n if email:\n user.email = email\n try:\n db.session.commit()\n return {'message': 'User updated successfully'}\n except Exception as e:\n db.session.rollback()\n return {'error': str(e)}\n\n# Function to delete user data from the database\ndef delete_user_data(user_id):\n user = UserData.query.get(user_id)\n if not user:\n return {'error': 'User not found'}\n try:\n db.session.delete(user)\n db.session.commit()\n return {'message': 'User deleted successfully'}\n except Exception as e:\n db.session.rollback()\n return {'error': str(e)}","simple.js": "// This is a sample JavaScript file\n\nfunction main() {\n console.log('Hello, world!');\n}\n\nmain();","text_only.js": "// This file is empty and should test the chunker's ability to handle empty files\n","routes.js": "const express = require('express');\nconst router = express.Router();\n\n// Example of a simple route\nrouter.get('/', (req, res) => {\n res.send('Welcome to the Home Page');\n});\n\n// Example of a route with a parameter\nrouter.get('/api/data/:data_id', (req, res) => {\n const dataId = req.params.data_id;\n res.json({ id: dataId, value: 'Specific data based on ID' });\n});\n\n// Example of a route that handles POST requests\nrouter.post('/api/data', (req, res) => {\n const data = req.body;\n res.status(201).json({ message: 'Data saved successfully', data: data });\n});\n\n// Example of a route that handles PUT requests\nrouter.put('/api/data/:data_id', (req, res) => {\n const dataId = req.params.data_id;\n const data = req.body;\n res.json({ message: 'Data updated successfully', id: dataId, data: data });\n});\n\n// Example of a route that handles DELETE requests\nrouter.delete('/api/data/:data_id', (req, res) => {\n const dataId = req.params.data_id;\n res.json({ message: 'Data deleted successfully', id: dataId });\n});\n\nmodule.exports = router;","models.js": "const mongoose = require('mongoose');\n\n// Example of a simple Mongoose model\nconst userSchema = new mongoose.Schema({\n username: { type: String, required: true, unique: true },\n email: { type: String, required: true, unique: true }\n});\n\nconst User = mongoose.model('User', userSchema);\n\nmodule.exports = User;","big_class.js": "// This is a sample JavaScript class with a large number of methods\n\nclass BigClass {\n constructor(name, age) {\n this.name = name;\n this.age = age;\n }\n\n getName() {\n return this.name;\n }\n\n getAge() {\n return this.age;\n }\n\n setName(name) {\n this.name = name;\n }\n\n setAge(age) {\n this.age = age;\n }\n\n toString() {\n return `Name: ${this.name}, Age: ${this.age}`;\n }\n}\n\nmodule.exports = BigClass;","main.js": "const express = require('express');\nconst routes = require('./routes');\n\n// Create the Express application\nconst app = express();\n\n// Register the routes from the routes.js file\napp.use('/', routes);\n\n// Configuration settings for the app can go here\napp.set('port', process.env.PORT || 3000);\n\n// More complex app initialization steps can be added here\n// For example, database initialization, middleware setups, etc.\n\n// This function can be used to create a database schema\nfunction createDatabase() {\n // Code to create database schema\n console.log('Created Database!');\n}\n\n// Optionally, call database creation or other setup functions here\ncreateDatabase();\n\n// Start the server\napp.listen(app.get('port'), () => {\n console.log(`Server running on port ${app.get('port')}`);\n});","utilities.js": "// Example of utility functions for common tasks\n\n// Function to hash a password\nfunction hashPassword(password) {\n const salt = uuidv4();\n return sha256(salt + password) + ':' + salt;\n}\n\n// Function to check a hashed password\nfunction checkPassword(hashedPassword, userPassword) {\n const [password, salt] = hashedPassword.split(':');\n return sha256(salt + userPassword) === password;\n}\n\n// Function to validate an email address\nfunction validateEmail(email) {\n const pattern = /^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$/;\n return pattern.test(email);\n}\n\n// Function to generate a token expiration date\nfunction generateExpirationDate(days = 1) {\n const expirationDate = new Date();\n expirationDate.setDate(expirationDate.getDate() + days);\n return expirationDate;\n}\n\n// Function to convert a string to a Date object\nfunction stringToDate(dateString, format = 'YYYY-MM-DD HH:mm:ss') {\n return new Date(dateString);\n}\n\n// Function to convert a Date object to a string\nfunction dateToString(date, format = 'YYYY-MM-DD HH:mm:ss') {\n return date.toISOString();\n}","services.js": "// Example of service functions for handling data operations\n\n// Function to fetch data from an external API\nasync function fetchExternalData(apiUrl) {\n try {\n const response = await fetch(apiUrl);\n if (response.ok) {\n return await response.json();\n } else {\n return { error: 'Failed to fetch data' };\n }\n } catch (error) {\n return { error: error.message };\n }\n}\n\n// Function to save user data to the database\nasync function saveUserData(name, email) {\n try {\n const newUser = new UserData({ name, email });\n await newUser.save();\n return { message: 'User saved successfully' };\n } catch (error) {\n return { error: error.message };\n }\n}\n\n// Function to update user data in the database\nasync function updateUserData(userId, name, email) {\n try {\n const user = await UserData.findById(userId);\n if (!user) {\n return { error: 'User not found' };\n }\n if (name) {\n user.name = name;\n }\n if (email) {\n user.email = email;\n }\n await user.save();\n return { message: 'User updated successfully' };\n } catch (error) {\n return { error: error.message };\n }\n}\n\n// Function to delete user data from the database\nasync function deleteUserData(userId) {\n try {\n const user = await UserData.findById(userId);\n if (!user) {\n return { error: 'User not found' };\n }\n await user.remove();\n return { message: 'User deleted successfully' };\n } catch (error) {\n return { error: error.message };\n }\n}","react_component.js": "import React from 'react';\n\nimport './SearchResults.css';\n\nimport TrackList from '../TrackList/TrackList.js';\n\n constructor(props) {\n super(props);\n this.addTopFive = this.addTopFive.bind(this);\n this.addTopTen = this.addTopTen.bind(this);\n this.addAll = this.addAll.bind(this);\n }\n\n //add the top five tracks to the playlist\n addTopFive() {\n this.props.onAdd(this.props.searchResults.slice(0, 5));\n }\n\n //add top 10 tracks to the playlist\n addTopTen() {\n this.props.onAdd(this.props.searchResults.slice(0, 10));\n }\n\n addAll() {\n this.props.onAdd(this.props.searchResults);\n }\n render() {\n return (\n <div className=\"SearchResults\">\n <h2>Results</h2>\n <TrackList tracks={this.props.searchResults} onAdd={this.props.onAdd} onToggle={this.props.onToggle} currentTrack={this.props.currentTrack}/>\n </div>\n );\n }\n}\n\nexport default SearchResults;'","simple_styles.css": "/* Example of CSS styles for a web page */\n\nbody {\n font-family: Arial, sans-serif;\n background-color: #f4f4f4;\n margin: 0;\n padding: 0;\n}\n\nh1 {\n color: #333;\n text-align: center;\n}\n\nbutton {\n padding: 10px 20px;\n font-size: 16px;\n background-color: #007bff;\n color: #fff;\n border: none;\n cursor: pointer;\n}\n\nbutton:hover {\n background-color: #0056b3;\n}","media_queries.css": "/* Example of CSS styles with media queries for responsive design */\n\nbody {\n font-family: Arial, sans-serif;\n background-color: #f4f4f4;\n margin: 0;\n padding: 0;\n}\n\nh1 {\n color: #333;\n text-align: center;\n}\n\nbutton {\n padding: 10px 20px;\n font-size: 16px;\n background-color: #007bff;\n color: #fff;\n border: none;\n cursor: pointer;\n}\n\nbutton:hover {\n background-color: #0056b3;\n}\n\n/* Media query for smaller screens */\n@media (max-width: 768px) {\n button {\n padding: 8px 16px;\n font-size: 14px;\n }\n}","single_syntax_error_example.py": "# This is a sample Python file\n\nprint('Hello, world!'\n\n","multiple_syntax_errors.py": "def calculate_sum(lst):\n total = 0\n for num in lst\n total += num\n return total\n\nprint(calculate_sum([1, 2, 3, 4])\n\ndef string_manipulator(s):\n new_string = ''\n for char in s:\n if char == 'a':\n new_string += 'z'\n else:\n new_string += char\n return new_string\n\nprint(string_manipulate('banana'))\n\ndef find_max(numbers):\n max_num = numbers[0]\n for num in numbers\n if num > max_num\n max_num = num\n return max_num\n\nprint(find_max([1, 2, 3, 4, 5])","single_syntax_error_example.js": "//This is a sample JavaScript file\n\nfunction main() {\n console.log('Hello, world!');\n if (true) {\n console.log('hi');\n \n}\n\nmain();","multiple_syntax_errors.js": "function calculateSum(arr) {\n let total = 0;\n for (let i = 0; i < arr.length; i++ {\n total += arr[i];\n }\n return total;\n}\n\nconsole.log(calculateSum([1, 2, 3, 4);\n\nfunction stringManipulator(str) {\n let newString = '';\n for (let i = 0; i < str.length; i++) {\n if (str.charAt(i) === 'a')\n newString += 'z';\n } else {\n newString += str.charAt(i);\n }\n }\n return newString;\n}\n\nconsole.log(stringManipulator('banana'));\n\nfunction findMax(numbers) {\n let maxNum = numbers[0];\n for (let i = 1; i < numbers.length; i++) {\n if (numbers[i] > maxNum) {\n maxNum = numbers[i];\n }\n }\n return maxNum;\n}\n\nconsole.log(findMax([1, 2, 3, 4, 5]);","single_syntax_error_example.css": "\n\nbody {\n font-family: Arial, sans-serif;\n background-color: #f4f4f4;\n margin: 0;\n padding: 0;\n}\n\nh1 {\n color: #333;\n text-align: center;\n}\n\nbutton {\n padding: 10px 20px;\n font-size: 16px;\n background-color: #007bff;\n color: #fff;\n border: none;\n cursor: pointer;\n :hover {\n background-color: #0056b3;\n}\n","multiple_syntax_errors.css": "body {\n font-family: Arial, sans-serif;\n background-color: #f4f4f4;\n margin: 0;\n padding: 0;\n}\n\nh1 {\n color: #333;\n text-align: center;\n}\n\nbutton {\n padding: 10px 20px;\n font-size: 16px;\n background-color: #007bff;\n color: #fff;\n border: none;\n cursor: pointer;\n :hover {\n background-color: #0056b3;\n}\n\n/* Media query for smaller screens */\n@media (max-width: 768px) {\n button {\n padding: 8px 16px;\n font-size: 14px;\n }\n}","example.ts": "interface User {\n id: number;\n name: string;\n email: string;\n}\n\nclass UserManager {\n private users: User[] = [];\n\n addUser(user: User): void {\n this.users.push(user);\n }\n\n getUser(id: number): User | undefined {\n return this.users.find(user => user.id === id);\n }\n\n updateUser(id: number, updatedUser: Partial<User>): void {\n const userIndex = this.users.findIndex(user => user.id === id);\n if (userIndex !== -1) {\n this.users[userIndex] = { ...this.users[userIndex], ...updatedUser };\n }\n }\n\n deleteUser(id: number): void {\n this.users = this.users.filter(user => user.id !== id);\n }\n}\n\nconst userManager = new UserManager();\nuserManager.addUser({ id: 1, name: 'John Doe', email: 'john@example.com' });\nconsole.log(userManager.getUser(1));","example.rb": "class User\n attr_accessor :id, :name, :email\n\n def initialize(id, name, email)\n @id = id\n @name = name\n @email = email\n end\n\n def to_s\n \"User: #{@name} (#{@email})\"\n end\nend\n\nclass UserManager\n def initialize\n @users = []\n end\n\n def add_user(user)\n @users << user\n end\n\n def get_user(id)\n @users.find { |user| user.id == id }\n end\n\n def update_user(id, updated_user)\n user = get_user(id)\n user.name = updated_user.name if updated_user.name\n user.email = updated_user.email if updated_user.email\n end\n\n def delete_user(id)\n @users.delete_if { |user| user.id == id }\n end\nend\n\nuser_manager = UserManager.new\nuser_manager.add_user(User.new(1, 'John Doe', 'john@example.com'))\nputs user_manager.get_user(1)","example.php": "<?php\n\nclass User {\n public $id;\n public $name;\n public $email;\n\n public function __construct($id, $name, $email) {\n $this->id = $id;\n $this->name = $name;\n $this->email = $email;\n }\n}\n\nclass UserManager {\n private $users = [];\n\n public function addUser($user) {\n $this->users[] = $user;\n }\n\n public function getUser($id) {\n foreach ($this->users as $user) {\n if ($user->id === $id) {\n return $user;\n }\n }\n return null;\n }\n\n public function updateUser($id, $updatedUser) {\n foreach ($this->users as &$user) {\n if ($user->id === $id) {\n $user->name = $updatedUser->name ?? $user->name;\n $user->email = $updatedUser->email ?? $user->email;\n break;\n }\n }\n }\n\n public function deleteUser($id) {\n $this->users = array_filter($this->users, function($user) use ($id) {\n return $user->id !== $id;\n });\n }\n}\n\n$userManager = new UserManager();\n$userManager->addUser(new User(1, 'John Doe', 'john@example.com'));\nvar_dump($userManager->getUser(1));\n?>"}
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768aiofiles==23.2.1altair==5.2.0annotated-types==0.6.0anyio==4.3.0attrs==23.2.0certifi==2024.2.2charset-normalizer==3.3.2click==8.1.7colorama==0.4.6contourpy==1.2.0cycler==0.12.1fastapi==0.110.0ffmpy==0.3.2filelock==3.13.1fonttools==4.49.0fsspec==2024.2.0gradio==4.19.2gradio_client==0.10.1h11==0.14.0httpcore==1.0.4httpx==0.27.0huggingface-hub==0.20.3idna==3.6importlib_resources==6.1.2Jinja2==3.1.3jsonschema==4.21.1jsonschema-specifications==2023.12.1kiwisolver==1.4.5markdown-it-py==3.0.0MarkupSafe==2.1.5matplotlib==3.8.3mdurl==0.1.2numpy==1.26.4orjson==3.9.15packaging==23.2pandas==2.2.1pillow==10.2.0pydantic==2.6.2pydantic_core==2.16.3pydub==0.25.1Pygments==2.17.2pyparsing==3.1.1python-dateutil==2.8.2python-multipart==0.0.9pytz==2024.1PyYAML==6.0.1referencing==0.33.0regex==2023.12.25requests==2.31.0rich==13.7.0rpds-py==0.18.0ruff==0.2.2semantic-version==2.10.0setuptools==69.1.1shellingham==1.5.4six==1.16.0sniffio==1.3.1starlette==0.36.3tomlkit==0.12.0toolz==0.12.1tqdm==4.66.2tree-sitter==0.20.4typer==0.9.0typing_extensions==4.10.0tzdata==2024.1urllib3==2.2.1uvicorn==0.27.1websockets==11.0.312345678910111213141516171819202122232425262728293031323334353637383940414243444546altair==5.3.0attrs==23.2.0blinker==1.7.0cachetools==5.3.3certifi==2024.2.2charset-normalizer==3.3.2click==8.1.7colorama==0.4.6gitdb==4.0.11GitPython==3.1.43idna==3.6Jinja2==3.1.3jsonschema==4.21.1jsonschema-specifications==2023.12.1markdown-it-py==3.0.0MarkupSafe==2.1.5mdurl==0.1.2numpy==1.26.4packaging==24.0pandas==2.2.1pillow==10.3.0protobuf==4.25.3pyarrow==15.0.2pydeck==0.8.1b0Pygments==2.17.2python-dateutil==2.9.0.post0pytz==2024.1referencing==0.34.0requests==2.31.0rich==13.7.1rpds-py==0.18.0six==1.16.0smmap==5.0.1streamlit==1.33.0tenacity==8.2.3regex==2023.12.25tiktoken==0.6.0tree-sitter==0.21.3toml==0.10.2toolz==0.12.1tornado==6.4typing_extensions==4.11.0tzdata==2024.1urllib3==2.2.1watchdog==4.0.0setuptools==69.2.0
207 unmodified lines208209210211212207 unmodified linesself.assertEqual(num_lines, len(css_code.split("\n")))self.assertIn(css_code, final_code)if __name__ == '__main__':unittest.main()207 unmodified lines208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282207 unmodified linesself.assertEqual(num_lines, len(css_code.split("\n")))self.assertIn(css_code, final_code)# TypeScript Test Classclass TestCodeChunkerTypeScript(unittest.TestCase):def setUp(self):self.patcher = patch('app.util.TextChunker.Chunker.count_tokens', side_effect=mock_count_tokens)self.mock_count_tokens = self.patcher.start()self.code_chunker = CodeChunker(file_extension='ts')self.mock_codebase = load_json('mock_codefiles.json')def tearDown(self):self.patcher.stop()def test_chunk_typescript_code(self):ts_code = self.mock_codebase['example.ts']chunks = self.code_chunker.chunk(ts_code, token_limit=20)Chunker.print_chunks(chunks)final_code = Chunker.consolidate_chunks_into_file(chunks)num_lines = Chunker.count_lines(final_code)self.assertEqual(num_lines, len(ts_code.split("\n")))self.assertIn(ts_code, final_code)self.assertGreater(len(chunks), 1) # Ensure the code is actually chunked# Ruby Test Classclass TestCodeChunkerRuby(unittest.TestCase):def setUp(self):self.patcher = patch('app.util.TextChunker.Chunker.count_tokens', side_effect=mock_count_tokens)self.mock_count_tokens = self.patcher.start()self.code_chunker = CodeChunker(file_extension='rb')self.mock_codebase = load_json('mock_codefiles.json')def tearDown(self):self.patcher.stop()def test_chunk_ruby_code(self):rb_code = self.mock_codebase['example.rb']chunks = self.code_chunker.chunk(rb_code, token_limit=20)Chunker.print_chunks(chunks)final_code = Chunker.consolidate_chunks_into_file(chunks)num_lines = Chunker.count_lines(final_code)self.assertEqual(num_lines, len(rb_code.split("\n")))self.assertIn(rb_code, final_code)self.assertGreater(len(chunks), 1) # Ensure the code is actually chunked# PHP Test Classclass TestCodeChunkerPHP(unittest.TestCase):def setUp(self):self.patcher = patch('app.util.TextChunker.Chunker.count_tokens', side_effect=mock_count_tokens)self.mock_count_tokens = self.patcher.start()self.code_chunker = CodeChunker(file_extension='php')self.mock_codebase = load_json('mock_codefiles.json')def tearDown(self):self.patcher.stop()def test_chunk_php_code(self):php_code = self.mock_codebase['example.php']chunks = self.code_chunker.chunk(php_code, token_limit=20)Chunker.print_chunks(chunks)final_code = Chunker.consolidate_chunks_into_file(chunks)num_lines = Chunker.count_lines(final_code)self.assertEqual(num_lines, len(php_code.split("\n")))self.assertIn(php_code, final_code)self.assertGreater(len(chunks), 1) # Ensure the code is actually chunkedif __name__ == '__main__':unittest.main()
6 unmodified lines78910111213146 unmodified linesnum_tokens = len(encoding.encode(string))return num_tokensdef load_json(json_file):with open(json_file) as f:return json.load(f)6 unmodified lines7891011126 unmodified linesnum_tokens = len(encoding.encode(string))return num_tokensdef load_json(json_file):with open(json_file) as f:return json.load(f)
.github/workflows/main.ymlAdded+20
.idea/.gitignoreAdded+8
.idea/code-chunker.imlAdded+15
.idea/misc.xmlAdded+9
.idea/modules.xmlAdded+8
.idea/vcs.xmlAdded+6
Chunker.py+14-14
LICENSE+21-201
README.md+30-9
__pycache__/Chunker.cpython-312.pyc
__pycache__/test_code_chunker.cpython-312.pyc
__pycache__/utils.cpython-312.pyc
app.pyAdded+88
cintra/documentation.jsonAdded+7
mock_codefiles.json+29-26
requirements.txt+24-46
test_code_chunker.py+70
utils.py-2