Datasets:
Upload 6 files
Browse filesFiles changed (7)
- .gitattributes+1
- README.md+182-8
- create_metadata_table.pyAdded+138
- custom_tokens_vocab.txtAdded
- github_python_metadata.csvAdded
- mega_licensed_corpus_redacted.txtAdded+3
- python_files.txtAdded
56 unmodified lines57585956 unmodified lines# Video files - compressed*.mp4 filter=lfs diff=lfs merge=lfs -text*.webm filter=lfs diff=lfs merge=lfs -text56 unmodified lines5758596056 unmodified lines# Video files - compressed*.mp4 filter=lfs diff=lfs merge=lfs -text*.webm filter=lfs diff=lfs merge=lfs -textmega_licensed_corpus_redacted.txt filter=lfs diff=lfs merge=lfs -text
12345678910---license: gpl-3.0task_categories:- text-generation- fill-mask- feature-extraction- sentence-similaritysize_categories:- 10M<n<100M---123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184---annotations_creators:- authorlicense:- gpl-3.0multilinguality:- monolingualpretty_name: GitHub-Pythondataset_name: github-pythondataset_type: codetags:- code- python- code-generationsize_categories:- 100K<n⩽1Mtask_categories:- text-generationtask_ids:- code-completion---# GitHub-PythonA **767 MB** corpus of permissively-licensed Python code drawn from public GitHub repositories.The dataset was created to support training and evaluation of **code-completion / generation** models.## Dataset at a glance| | Value || ---------------- | --------------------------------------------- || Files | 53,017 `.py` files || Repositories | 16,447 || Owners | 12,515 || Compressed size | 732 MB (`mega_licensed_corpus_redacted.txt`) || Vocabulary | 443,431 tokens (`custom_tokens_vocab.txt`) || Time period | Commits ≥ 2015-01-01 || License coverage | MIT, Apache-2.0, BSD, ISC, Unlicense || Removed secrets | ✅ – all hard-coded secrets/API keys redacted |Numbers were obtained from the final redacted corpus and companion metadata.---## Dataset structure```huggingface_dataset/├─ mega_licensed_corpus_redacted.txt # concatenated code corpus├─ python_files.txt # list of raw file URLs (1-per-line)└─ custom_tokens_vocab.txt # `<token>\t<id>` vocabulary file```### File separatorIndividual files are concatenated with the sentinel line:```# <FILESEP>```Anything following the sentinel until the next sentinel (or EOF) is the sourcecode of one file.---## Collection methodology1. **Repository discovery**- Queried GitHub REST API for projects with **≥ 10 stars**(earlier iterations used 100+, later expanded for coverage).- Only repositories with primary language _Python_ and last commit ≥ 2015.2. **File filtering**- Retain files whose **size ∈ [1 KB, 100 KB]**.- Exclude common build/packaging scripts (`setup.py`, `__init__.py`, etc.).3. **License compliance**- Allowed: MIT, Apache-2.0, BSD-2/3-Clause, ISC, Unlicense.- GPL, LGPL, AGPL and proprietary licenses were **excluded**.4. **Deduplication**- Unique file SHA hashes; duplicates skipped.5. **Formatting & cleaning**- Formatted with _autopep8_ to normalise whitespace.- Custom script removed trailing whitespace & normalised newlines.6. **Secret redaction**- `truffleHog` + custom regex pass removed >150 active credentials.- Redacted corpus stored as `mega_licensed_corpus_redacted.txt`.---## Custom tokenisationThe accompanying `custom_tokens_vocab.txt` implements a **Python-awaresub-token scheme**:1. Strip doc-strings & comments.2. Split on:- Camel-Case boundaries (`Camel` → `Camel`, `Case`)- Underscores, spaces- Indentation & newlines (preserved as `<newline>` token)3. Rare tokens (frequency < 10) were dropped → 443 k vocabulary.Example:```pythondef helloWorld(value):return value + 1```tokenises to:```def hello world ( value ) <newline> return value + 1 <newline>```---## Usage```pythonfrom datasets import load_datasetds = load_dataset("jblitzar/github-python", split="train")print(ds[0]["code"][:300]) # raw source code```If you prefer token level examples (small reasons: memory), map the tokenizer:```pythonfrom tokenizers import Tokenizertok = Tokenizer.from_file("custom_tokens_vocab.txt")def encode(ex):ex["input_ids"] = tok.encode(ex["code"]).idsreturn exds = ds.map(encode, remove_columns=["code"])```---## Ethical considerations & limitations- **Licenses respected** – only permissive licenses included; retain NOTICEfiles when redistributing derivative works.- **Secrets removed** – automated & manual audits performed, yet users **mustnot assume zero secrets**; re-audit before public deployments.- **Code quality** – projects vary in style & correctness. Generated modelsmay replicate bugs or vulnerable patterns.---## CitationIf you use this dataset, please cite:```@misc{github-python-2024,author = {JBlitzar},title = {GitHub-Python: A Permissively Licensed Corpus of Python Code},year = {2024},howpublished = {\url{https://huggingface.co/datasets/jblitzar/github-python}},note = {Version 1.0}}```---## LicenseDataset card and aggregation scripts: **GPLv3**.Each code snippet remains under its **original repository license** (MIT,Apache-2.0, BSD, ISC, etc.). Users must comply with upstream notices whenredistributing code or derivatives.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138#!/usr/bin/env python3"""Create a metadata table from GitHub Python file URLs.
This script processes the file URLs from python_files.txt and creates a tabularCSV file with repository metadata including owner, name, file path, and URLs."""
import osimport reimport csvimport pandas as pdfrom collections import Counterfrom urllib.parse import urlparsefrom tqdm import tqdm
def parse_github_url(url): """ Parse a GitHub URL to extract repository owner, name, and file path. Handles both raw.githubusercontent.com and github.com URLs. Args: url (str): GitHub URL Returns: dict: Dictionary with repo_owner, repo_name, file_path, repo_url """ url = url.strip() # Initialize default values result = { "repo_owner": "unknown", "repo_name": "unknown", "file_path": "", "file_url": url, "repo_url": "" } try: # Parse URL to get components parsed = urlparse(url) path_parts = parsed.path.strip('/').split('/') # Handle raw.githubusercontent.com URLs # Format: https://raw.githubusercontent.com/owner/repo/branch/path/to/file.py if 'raw.githubusercontent.com' in url: if len(path_parts) >= 3: result["repo_owner"] = path_parts[0] result["repo_name"] = path_parts[1] # Skip branch (path_parts[2]) and get the rest as file path result["file_path"] = '/'.join(path_parts[3:]) result["repo_url"] = f"https://github.com/{path_parts[0]}/{path_parts[1]}" # Handle github.com URLs # Format: https://github.com/owner/repo/blob/branch/path/to/file.py elif 'github.com' in url: if len(path_parts) >= 4 and path_parts[2] == 'blob': result["repo_owner"] = path_parts[0] result["repo_name"] = path_parts[1] # Skip 'blob' and branch, get the rest as file path result["file_path"] = '/'.join(path_parts[4:]) result["repo_url"] = f"https://github.com/{path_parts[0]}/{path_parts[1]}" return result except Exception as e: print(f"Error parsing URL {url}: {e}") return result
def process_file_urls(input_file, output_file): """ Process GitHub file URLs and create a metadata CSV file. Args: input_file (str): Path to the file containing GitHub URLs output_file (str): Path to the output CSV file """ print(f"Processing URLs from {input_file}...") # Read file URLs with open(input_file, 'r', encoding='utf-8') as f: urls = [line.strip() for line in f if line.strip()] # Parse each URL metadata = [] for url in tqdm(urls, desc="Parsing URLs"): metadata.append(parse_github_url(url)) # Convert to DataFrame df = pd.DataFrame(metadata) # Save to CSV # Use minimal quoting to remain compatible with the standard csv module df.to_csv(output_file, index=False, quoting=csv.QUOTE_MINIMAL) print(f"Metadata saved to {output_file}") # Print statistics unique_repos = df[['repo_owner', 'repo_name']].drop_duplicates() unique_owners = df['repo_owner'].nunique() print("\n=== Dataset Statistics ===") print(f"Total files: {len(df)}") print(f"Unique repositories: {len(unique_repos)}") print(f"Unique repository owners: {unique_owners}") # Top repositories by file count repo_counts = Counter(zip(df['repo_owner'], df['repo_name'])) print("\nTop 10 repositories by file count:") for (owner, repo), count in repo_counts.most_common(10): print(f" {owner}/{repo}: {count} files") # File extensions extensions = Counter([os.path.splitext(path)[1] for path in df['file_path'] if path]) print("\nFile extensions:") for ext, count in extensions.most_common(5): print(f" {ext or 'No extension'}: {count} files") # Repository owners with most repositories owner_repo_counts = Counter(df['repo_owner']) print("\nTop 5 repository owners:") for owner, count in owner_repo_counts.most_common(5): print(f" {owner}: {count} files")
if __name__ == "__main__": input_file = "python_files.txt" output_file = "github_python_metadata.csv" # Check if input file exists if not os.path.exists(input_file): print(f"Error: Input file {input_file} not found.") print("Please make sure the file exists in the current directory.") exit(1) process_file_urls(input_file, output_file)123version https://git-lfs.github.com/spec/v1oid sha256:25872f695fefeb4106ddd7006c798767be925a67abadf5d22da240541cad6717size 767255913.gitattributes+1
README.md+182-8
create_metadata_table.pyAdded+138
custom_tokens_vocab.txtAdded
github_python_metadata.csvAdded
mega_licensed_corpus_redacted.txtAdded+3
python_files.txtAdded