init
Browse filesFiles changed (16)
- README.md+60-3
- python_sample.jsonlAdded
- raw/Readme.mdAdded+19
- raw/negative/collect_script.pyAdded+381
- raw/negative/negative_raw.jsonlAdded
- raw/positive/abstract_script.pyAdded+40
- raw/positive/github_repositories.csvAdded
- raw/positive/positive_original.part01.rarAdded+3
- raw/positive/positive_original.part02.rarAdded+3
- raw/positive/positive_original.part03.rarAdded+3
- raw/positive/positive_original.part04.rarAdded+3
- raw/positive/positive_original.part05.rarAdded+3
- raw/positive/positive_original.part06.rarAdded+3
- script/divide.pyAdded+77
- script/extract_members.pyAdded+30
- script/ratio.pyAdded+43
123---license: apache-2.0---123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960# Dataset Scripts## divide.py`divide.py` is a script designed to split a JSONL file into two separate files based on the approximate token count of a specified text field. It detects the appropriate text field from the input JSONL and uses the median token count as a threshold to categorize the entries into "short" and "long".### UsageTo use `divide.py`, run the following command in your terminal:```bashpython divide.py --input <input_jsonl_path> --short_out <output_short_jsonl_path> --long_out <output_long_jsonl_path>```- `--input`: Path to the input JSONL file (required).- `--short_out`: Path to the output JSONL file for short entries (default: `short.jsonl`).- `--long_out`: Path to the output JSONL file for long entries (default: `long.jsonl`).## ratio.py`ratio.py` is a script that creates datasets with specified positive and negative sample ratios from two JSONL files containing positive and negative samples. It randomly samples from the provided datasets to create a new dataset based on the defined configuration.### UsageTo use `ratio.py`, simply run the script:```bashpython ratio.py```This script will read from `positive/positive.jsonl` and `negative/negative.jsonl`, and create datasets based on the configurations defined in the script. The output files will be named `dataset_{name}.jsonl` for each configuration.### Dataset ConfigurationsThe following configurations are available in the script:- `1_1`: 2000 total samples with a 1:1 positive to negative ratio.- `1_5`: 1200 total samples with a 1:5 positive to negative ratio.- `5_1`: 1200 total samples with a 5:1 positive to negative ratio.## extract_members.py`extract_members.py` is a script that extracts members and non-members from a JSONL file based on the `label` field. It reads from `python_sample.jsonl`, where a `label` of `1` indicates a member and a `label` of `0` indicates a non-member. The script outputs two separate JSONL files: one for members and one for non-members.### UsageTo use `extract_members.py`, run the following command in your terminal:```bashpython extract_members.py```This script will read from `dataset/python_sample.jsonl` and create the following output files:- `dataset/member.jsonl`: Contains all entries with `label` equal to `1`.- `dataset/non-member.jsonl`: Contains all entries with `label` equal to `0`.### OutputAfter running the script, you will see a message indicating the number of extracted members and non-members.
12345678910111213141516171819# raw dataset and script## descriptionThis folder contains various original files and scripts used in the dataset creation process. This dataset consists of two parts: positive and negative.
## positiveUnzip positive_original.rar to obtain positive_original.jsonl.
positive_original.jsonl is obtained by filtering Python language data from The Pile's GitHub dataset.
positive.jsonl is derived from positive_original.jsonl: starting from the 1st line, take the first 10 lines out of every 100 lines. A total of 10,000 lines are processed, resulting in 1,000 lines.
abstract_script.py is the script used to generate positive.jsonl from positive_original.jsonl.
For the repository used for The Pile dataset, please refer to github_repositories.csv (from https://github.com/EleutherAI/github-downloader).
## negativenegative_raw.jsonl is obtained from GitHub: filter Python language repositories created after January 1, 2024, sort them in descending order of star count. After finding 10 Python functions in a repository, switch to next repository. A total of 100 repositories are included, resulting in 1,000 entries.
collect_script.py is the script used to collect negative_raw.jsonl.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381import requestsimport jsonimport astfrom datetime import datetimeimport timeimport osfrom requests.adapters import HTTPAdapterfrom requests.packages.urllib3.util.retry import Retry
# Configuration ParametersGITHUB_TOKEN = 'YOUR-GITHUB-TOKEN'
HEADERS = { "Authorization": f"token {GITHUB_TOKEN}", "Accept": "application/vnd.github.v3+json"}
# Search for active Python repositories created after 2024SEARCH_QUERY = "language:python created:>=2024-01-01"OUTPUT_FILE = "negative_raw.jsonl"STATE_FILE = "crawler_state.json" # File to save crawling stateFUNCTIONS_PER_REPO = 10 # Maximum number of functions to collect per repositoryMAX_RETRIES = 10 # Maximum number of retries for requestsRETRY_BACKOFF_FACTOR = 2 # Multiplier for retry waiting timeNETWORK_ERROR_SLEEP = 30 # Waiting time (seconds) after network errors
def create_session(): """Create a requests session with retry mechanism""" session = requests.Session() # Set up retry strategy retry_strategy = Retry( total=MAX_RETRIES, backoff_factor=RETRY_BACKOFF_FACTOR, status_forcelist=[429, 500, 502, 503, 504, 408], allowed_methods=["HEAD", "GET", "OPTIONS"] ) # Apply retry strategy to HTTP and HTTPS connections adapter = HTTPAdapter(max_retries=retry_strategy) session.mount("https://", adapter) session.mount("http://", adapter) return session
def save_state(state): """Save current crawling state to file""" with open(STATE_FILE, 'w') as f: json.dump(state, f)
def load_state(): """Load crawling state from file""" if os.path.exists(STATE_FILE): with open(STATE_FILE, 'r') as f: return json.load(f) return { 'current_page': 1, 'processed_repos': [], 'processed_files': set(), 'repo_function_counts': {} }
def parse_functions(source_code): """Parse Python code and return list of functions""" try: tree = ast.parse(source_code) except Exception as e: print(f"Failed to parse code: {str(e)}") return [] functions = [] source_lines = source_code.split('\n') for node in ast.walk(tree): if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)): if not hasattr(node, 'end_lineno'): continue # Skip functions where end line number cannot be obtained start_line = node.lineno - 1 end_line = node.end_lineno function_code = '\n'.join(source_lines[start_line:end_line]) functions.append({ 'name': node.name, 'code': function_code }) return functions
def fetch_github_api(url, params=None, session=None): """Send GitHub API request and handle rate limits and network exceptions""" if not session: session = create_session() retries = 0 while retries < MAX_RETRIES: try: response = session.get(url, headers=HEADERS, params=params, timeout=60, verify=True) if response.status_code == 403 and 'rate limit' in response.text.lower(): reset_time = int(response.headers.get('X-RateLimit-Reset', 0)) sleep_time = max(reset_time - time.time(), 0) + 5 print(f"Rate limited, waiting {sleep_time:.1f} seconds") time.sleep(sleep_time) continue return response except requests.exceptions.SSLError as e: print(f"SSL Error: {str(e)}, attempting retry {retries+1}/{MAX_RETRIES}") retries += 1 time.sleep(NETWORK_ERROR_SLEEP) # Wait longer after network errors except requests.exceptions.RequestException as e: print(f"Request Exception: {str(e)}, attempting retry {retries+1}/{MAX_RETRIES}") retries += 1 time.sleep(NETWORK_ERROR_SLEEP) # Wait longer after network errors print(f"Reached maximum retry attempts, skipping URL: {url}") return None
def get_file_creation_date(repo_full_name, file_path, commit_sha, session=None): """Get file creation date (first commit date)""" # Get file commit history commits_url = f"https://api.github.com/repos/{repo_full_name}/commits?path={file_path}&per_page=100" commits_response = fetch_github_api(commits_url, session=session) if not commits_response or commits_response.status_code != 200: return None commits = commits_response.json() if not commits: return None # The last commit is the first commit of the file first_commit = commits[-1] return first_commit['commit']['committer']['date']
def main(): # Load saved state state = load_state() page = state['current_page'] processed_repos = state['processed_repos'] processed_files = set(state.get('processed_files', [])) repo_function_counts = state.get('repo_function_counts', {}) session = create_session() with open(OUTPUT_FILE, 'a') as out_file: # Open in append mode while True: # Search for eligible repositories search_url = f"https://api.github.com/search/repositories?q={SEARCH_QUERY}&per_page=100&page={page}" response = fetch_github_api(search_url, session=session) if not response or response.status_code != 200: print(f"Search failed, waiting {NETWORK_ERROR_SLEEP} seconds before retrying") time.sleep(NETWORK_ERROR_SLEEP) continue data = response.json() if not data.get('items'): print(f"No search results on page {page}, exiting") break print(f"Processing page {page}, total {len(data['items'])} repositories") for repo_item in data['items']: repo_full_name = repo_item['full_name'] # Skip already processed repositories if repo_full_name in processed_repos: print(f"Skipping processed repository: {repo_full_name}") continue stars = repo_item['stargazers_count'] print(f"\nProcessing repository: {repo_full_name} (Stars: {stars})") # Get or initialize repository function counter repo_function_count = repo_function_counts.get(repo_full_name, 0) # Get repository's default branch repo_url = f"https://api.github.com/repos/{repo_full_name}" repo_response = fetch_github_api(repo_url, session=session) if not repo_response or repo_response.status_code != 200: print(f"Failed to get repository information, skipping {repo_full_name}") continue default_branch = repo_response.json().get('default_branch', 'main') # Get list of Python files in the repository (recursive retrieval) contents_url = f"https://api.github.com/repos/{repo_full_name}/contents?ref={default_branch}" stack = [contents_url] try: while stack: # Check if function count limit is reached if repo_function_count >= FUNCTIONS_PER_REPO: print(f"Collected {repo_function_count} functions from {repo_full_name}, limit reached, moving to next repository") break current_url = stack.pop() contents_response = fetch_github_api(current_url, session=session) if not contents_response or contents_response.status_code != 200: print(f"Failed to get directory contents, skipping {current_url}") continue items = contents_response.json() for item in items: # Check if function count limit is reached if repo_function_count >= FUNCTIONS_PER_REPO: print(f"Collected {repo_function_count} functions from {repo_full_name}, limit reached, moving to next repository") break if item['type'] == 'dir': # Recursively process subdirectories stack.append(item['url']) elif item['name'].endswith('.py'): file_path = item['path'] file_id = f"{repo_full_name}/{file_path}" if file_id in processed_files: continue # Get file content download_url = item['download_url'] file_response = fetch_github_api(download_url, session=session) if not file_response or file_response.status_code != 200: print(f"Failed to get file content, skipping {file_id}") continue # Get SHA while retrieving file content (for querying commit history) content_data = file_response.json() if 'json' in file_response.headers.get('Content-Type', '') else {} sha = content_data.get('sha', '') # Get file creation date creation_date_str = get_file_creation_date(repo_full_name, file_path, sha, session=session) if not creation_date_str: print(f"Failed to get file creation date, skipping {file_id}") continue creation_date = datetime.strptime(creation_date_str, "%Y-%m-%dT%H:%M:%SZ") # Strictly check file creation date if creation_date < datetime(2024, 1, 1): print(f"File {file_id} was created on {creation_date_str}, which is before 2024-01-01, skipping") continue # Parse functions in the file source_code = file_response.text functions = parse_functions(source_code) if not functions: print(f"No functions found in file {file_id}") continue print(f"Parsed {len(functions)} functions from file {file_id}") # Write function records and update counter for func in functions: if repo_function_count >= FUNCTIONS_PER_REPO: break record = { 'function': func['code'], 'creation_date': creation_date_str, 'repo': repo_full_name, 'file_path': file_path, 'stars': stars, 'label': 0 } out_file.write(json.dumps(record) + '\n') repo_function_count += 1 # Save state after every 10 functions processed if repo_function_count % 10 == 0: state = { 'current_page': page, 'processed_repos': processed_repos, 'processed_files': list(processed_files), 'repo_function_counts': repo_function_counts } save_state(state) print(f"State saved: Collected {repo_function_count} functions from repository {repo_full_name}") # Mark file as processed processed_files.add(file_id) # Save state after processing each directory state = { 'current_page': page, 'processed_repos': processed_repos, 'processed_files': list(processed_files), 'repo_function_counts': repo_function_counts } save_state(state) except KeyboardInterrupt: print("User interruption detected, saving current state...") state = { 'current_page': page, 'processed_repos': processed_repos, 'processed_files': list(processed_files), 'repo_function_counts': repo_function_counts } save_state(state) print("State saved, program exiting. Next run will resume from the last interruption point.") return except Exception as e: print(f"Unexpected error occurred while processing repository {repo_full_name}: {str(e)}") print("Saving current state and skipping this repository...") state = { 'current_page': page, 'processed_repos': processed_repos, 'processed_files': list(processed_files), 'repo_function_counts': repo_function_counts } save_state(state) continue # Update repository function count repo_function_counts[repo_full_name] = repo_function_count # Mark repository as processed processed_repos.append(repo_full_name) # Save state state = { 'current_page': page, 'processed_repos': processed_repos, 'processed_files': list(processed_files), 'repo_function_counts': repo_function_counts } save_state(state) print(f"Completed processing repository {repo_full_name}, collected {repo_function_count} functions in total") # Check if there is a next page if 'next' in response.links: page += 1 # Save page number state state = { 'current_page': page, 'processed_repos': processed_repos, 'processed_files': list(processed_files), 'repo_function_counts': repo_function_counts } save_state(state) print(f"State saved: About to process page {page}") else: print(f"No next page, processing completed") break
if __name__ == "__main__": main()
'''Usage Instructions
1. Run the script normally: ```bash python collect_script.py ```
2. To start over from scratch, delete the state file: ```bash rm crawler_state.json ```
3. After network recovery, simply re-run the script to resume from the interruption point
4. Adjust parameters: ```python # Increase retry count or extend waiting time MAX_RETRIES = 15 NETWORK_ERROR_SLEEP = 60 ```'''12345678910111213141516171819202122232425262728293031323334353637383940import json
def process_jsonl(): """ Process the jsonl file: starting from line 1, extract the first 10 lines from every 100-line block, process a total of 10,000 lines, and extract 1,000 lines in total """ # Define input and output file paths input_file = 'positive_original.jsonl' output_file = 'positive.jsonl' with open(input_file, 'r', encoding='utf-8') as infile, \ open(output_file, 'w', encoding='utf-8') as outfile: # Initialize counters line_count = 0 extracted_count = 0 # Read the first 10,000 lines while line_count < 10000: line = infile.readline() if not line: # End of file break line_count += 1 # Calculate which 100-line block the current line belongs to block_number = (line_count - 1) // 100 # Calculate the position of the current line within its block position_in_block = (line_count - 1) % 100 # If the line is among the first 10 lines in the block, write it to the output file if position_in_block < 10: outfile.write(line) extracted_count += 1 print(f"Processing completed! A total of {line_count} lines were read, and {extracted_count} lines were extracted.") print(f"Extracted data has been saved to {output_file}")
if __name__ == "__main__": process_jsonl() 123version https://git-lfs.github.com/spec/v1oid sha256:f1469ec26d9eaaf0b92447ca021ff4f98edb9ce805230a2e0fd74e12ab5ddbaasize 47185920123version https://git-lfs.github.com/spec/v1oid sha256:fe4e12678c2d7ec16f31170199a3b69939dcbf111d5647266d1613e9921e03dfsize 47185920123version https://git-lfs.github.com/spec/v1oid sha256:cdcb001ff4f6ab681520c2dd21342d052f9a1c2d80489783adc1e8ee3a5e389asize 47185920123version https://git-lfs.github.com/spec/v1oid sha256:baa14b7d82d1c71b9c6118843d53eb22abe8b4de074762de60717eee1132be07size 47185920123version https://git-lfs.github.com/spec/v1oid sha256:2473bb1f788196c620ac9ed1e49948e6046222f920699108bcba1ece070652d6size 47185920123version https://git-lfs.github.com/spec/v1oid sha256:fd5b83429cc003e82f994f3ab23c7c362acd05d0defdc00269bdd2b86f6fafd5size 91534561234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677import json, re, argparse, statistics
def approx_token_count(text: str) -> int: if not text: return 0 return len(re.findall(r"\w+|\S", text, flags=re.UNICODE))
def detect_text_field(obj): for k in ["text", "function", "code", "content", "body"]: if k in obj and isinstance(obj[k], str): return k str_fields = [(k, len(v)) for k, v in obj.items() if isinstance(v, str)] if str_fields: return max(str_fields, key=lambda x: x[1])[0] return None
def main(): ap = argparse.ArgumentParser() ap.add_argument("--input", required=True, help="input JSONL path") ap.add_argument("--short_out", default="short.jsonl", help="output short JSONL") ap.add_argument("--long_out", default="long.jsonl", help="output long JSONL") args = ap.parse_args()
# First pass: detect field and collect lengths detected_field = None lengths = [] total = decode_errors = 0
with open(args.input, "r", encoding="utf-8") as f: for line in f: total += 1 line = line.strip() if not line: continue try: obj = json.loads(line) except json.JSONDecodeError: decode_errors += 1 continue if detected_field is None: detected_field = detect_text_field(obj) or "text" lengths.append(approx_token_count(obj.get(detected_field, "")))
if not lengths: raise SystemExit("No valid samples parsed from input.")
# Use median as threshold threshold = int(statistics.median(lengths))
# Second pass: split short_cnt = long_cnt = 0 with open(args.input, "r", encoding="utf-8") as f_in, \ open(args.short_out, "w", encoding="utf-8") as f_s, \ open(args.long_out, "w", encoding="utf-8") as f_l: for line in f_in: line = line.strip() if not line: continue obj = json.loads(line) L = approx_token_count(obj.get(detected_field, "")) if L <= threshold: f_s.write(json.dumps(obj, ensure_ascii=False) + "\n") short_cnt += 1 else: f_l.write(json.dumps(obj, ensure_ascii=False) + "\n") long_cnt += 1
# Report total_valid = short_cnt + long_cnt print("==== Split Done ====") print(f"Input: {args.input}") print(f"Detected text field: {detected_field}") print(f"Threshold (median approx tokens): {threshold}") print(f"Counts: short={short_cnt}, long={long_cnt}, long_ratio={(long_cnt/total_valid if total_valid else 0):.2%}")
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930import json
def extract_members(input_path, member_output_path, non_member_output_path): with open(input_path, 'r', encoding='utf-8') as f: members = [] non_members = [] for line in f: if line.strip(): # Skip empty lines obj = json.loads(line) # Check the label to determine membership if obj.get('label') == 1: members.append(obj) elif obj.get('label') == 0: non_members.append(obj)
# Write members to member.jsonl with open(member_output_path, 'w', encoding='utf-8') as f: for member in members: f.write(json.dumps(member, ensure_ascii=False) + "\n")
# Write non-members to non-member.jsonl with open(non_member_output_path, 'w', encoding='utf-8') as f: for non_member in non_members: f.write(json.dumps(non_member, ensure_ascii=False) + "\n")
print(f'Extracted {len(members)} members and {len(non_members)} non-members.')
if __name__ == "__main__": extract_members('dataset/python_sample.jsonl', 'dataset/member.jsonl', 'dataset/non-member.jsonl')12345678910111213141516171819202122232425262728293031323334353637383940414243import jsonimport randomimport os
positive_path = 'positive/positive.jsonl'negative_path = 'negative/negative.jsonl'
def read_jsonl(path): with open(path, 'r', encoding='utf-8') as f: return [line for line in f if line.strip()]
positives = read_jsonl(positive_path)negatives = read_jsonl(negative_path)
datasets_config = { '1_1': {'total': 2000, 'pos_ratio': 1, 'neg_ratio': 1}, '1_5': {'total': 1200, 'pos_ratio': 1, 'neg_ratio': 5}, '5_1': {'total': 1200, 'pos_ratio': 5, 'neg_ratio': 1} }
for name, config in datasets_config.items(): total = config['total'] pos_ratio = config['pos_ratio'] neg_ratio = config['neg_ratio'] pos_count = int(total * pos_ratio / (pos_ratio + neg_ratio)) neg_count = total - pos_count pos_count = min(pos_count, len(positives)) neg_count = min(neg_count, len(negatives)) pos_samples = random.sample(positives, pos_count) neg_samples = random.sample(negatives, neg_count) dataset = pos_samples + neg_samples random.shuffle(dataset) out_path = f'dataset_{name}.jsonl' with open(out_path, 'w', encoding='utf-8') as f: for line in dataset: f.write(line if line.endswith('\n') else line + '\n') print(f'{out_path} created: {pos_count} positive, {neg_count} negative samples (total: {len(dataset)})')README.md+60-3
python_sample.jsonlAdded
raw/Readme.mdAdded+19
raw/negative/collect_script.pyAdded+381
raw/negative/negative_raw.jsonlAdded
raw/positive/abstract_script.pyAdded+40
raw/positive/github_repositories.csvAdded
raw/positive/positive_original.part01.rarAdded+3
raw/positive/positive_original.part02.rarAdded+3
raw/positive/positive_original.part03.rarAdded+3
raw/positive/positive_original.part04.rarAdded+3
raw/positive/positive_original.part05.rarAdded+3
raw/positive/positive_original.part06.rarAdded+3
script/divide.pyAdded+77
script/extract_members.pyAdded+30
script/ratio.pyAdded+43