File size: 11,658 Bytes
0a97af6 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 |
#!/usr/bin/env python3
"""
Multilingual Paper BibTeX Generator
This script parses anthology+abstracts.bib and generates multilingual_papers.bib
containing only papers related to multilingual NLP research.
Usage:
python generate_multilingual_bib.py
Requirements:
- anthology+abstracts.bib file in the same directory
"""
import re
import os
from typing import List, Dict, Set
from tqdm import tqdm
from collections import defaultdict
# Multilingual keywords for filtering (same as JavaScript version)
MULTILINGUAL_KEYWORDS = [
'multilingual', 'crosslingual', 'multi lingual', 'cross lingual',
'multi-lingual', 'cross-lingual', 'low-resource language', 'low resource language',
# 'low-resource', 'low resource',
'multi-language', 'multi language', 'cross-language', 'cross language',
'language transfer',
'code-switching', 'code switching', 'language adaptation',
'language pair', 'bilingual', 'trilingual', 'polyglot',
# 'machine translation', 'neural machine translation', 'speech translation', 'translation', 'nmt',
'translation', "nmt",
'transliteration',
'multilingual bert', 'xlm', 'mbert', 'xlm-roberta',
'language identification', 'language detection'
]
# Language names for filtering (same as JavaScript version)
LANGUAGE_NAMES = [
'afrikaans', 'albanian', 'amharic', 'arabic', 'armenian', 'azerbaijani', 'basque', 'belarusian', 'bengali', 'bosnian', 'bulgarian', 'catalan', 'cebuano', 'chinese', 'croatian', 'czech', 'danish', 'dutch', 'esperanto', 'estonian', 'filipino', 'finnish', 'french', 'galician', 'georgian', 'german', 'greek', 'gujarati', 'haitian', 'hausa', 'hawaiian', 'hebrew', 'hindi', 'hmong', 'hungarian', 'icelandic', 'igbo', 'indonesian', 'irish', 'italian', 'japanese', 'javanese', 'kannada', 'kazakh', 'khmer', 'korean', 'kurdish', 'kyrgyz', 'lao', 'latin', 'latvian', 'lithuanian', 'luxembourgish', 'macedonian', 'malagasy', 'malay', 'malayalam', 'maltese', 'maori', 'marathi', 'mongolian', 'myanmar', 'nepali', 'norwegian', 'odia', 'pashto', 'persian', 'polish', 'portuguese', 'punjabi', 'romanian', 'russian', 'samoan', 'scots gaelic', 'serbian', 'sesotho', 'shona', 'sindhi', 'sinhala', 'slovak', 'slovenian', 'somali', 'spanish', 'sundanese', 'swahili', 'swedish', 'tagalog', 'tajik', 'tamil', 'telugu', 'thai', 'turkish', 'ukrainian', 'urdu', 'uzbek', 'vietnamese', 'welsh', 'xhosa', 'yiddish', 'yoruba', 'zulu',
# Additional language variations and names
'mandarin', 'cantonese', 'hindi', 'urdu', 'bengali', 'tamil', 'telugu', 'marathi', 'gujarati', 'kannada', 'malayalam', 'punjabi', 'odia', 'assamese', 'maithili', 'sanskrit', 'kashmiri', 'konkani', 'manipuri', 'nepali', 'sindhi', 'dogri', 'bodo', 'santali', 'khasi', 'mizo', 'garo', 'naga', 'tibetan', 'dzongkha', 'sikkimese', 'lepcha', 'limbu', 'tamang', 'gurung', 'magar', 'tharu', 'tulu'
'african', 'indian', "asian", "indigenous",
]
def clean_latex_commands(text: str) -> str:
"""
Clean LaTeX commands from text (same logic as JavaScript version).
"""
if not text:
return ''
# Remove LaTeX commands with braces
text = re.sub(r'\\[a-zA-Z]+\{([^}]*)\}', r'\1', text)
# Remove simple LaTeX commands
text = re.sub(r'\\[a-zA-Z]+', '', text)
# Remove braces
text = re.sub(r'\{\\?([^}]*)\}', r'\1', text)
# Replace escaped characters
text = text.replace('\\"', '"')
text = text.replace("\\'", "'")
text = text.replace('\\&', '&')
text = text.replace('\\%', '%')
text = text.replace('\\_', '_')
text = text.replace('\\$', '$')
# Normalize whitespace
text = re.sub(r'\s+', ' ', text)
return text.strip()
def is_multilingual_paper(paper: Dict[str, str]) -> bool:
"""
Determine if a paper is multilingual (same logic as JavaScript version).
"""
text = f"{paper.get('title', '')} {paper.get('abstract', '')}".lower()
# Check for multilingual keywords
for keyword in MULTILINGUAL_KEYWORDS:
if keyword.lower() in text:
return True, keyword
# Check for language names
for language in LANGUAGE_NAMES:
# require language to be matched perfectly
if language.lower() in text.split():
return True, language
return False, None
def extract_keywords(paper: Dict[str, str]) -> Set[str]:
"""
Extract multilingual keywords from a paper (same logic as JavaScript version).
"""
keywords = set()
text = f"{paper.get('title', '')} {paper.get('abstract', '')}".lower()
# Extract multilingual keywords
for keyword in MULTILINGUAL_KEYWORDS:
if keyword.lower() in text:
keywords.add(keyword)
# Extract language names
for language in LANGUAGE_NAMES:
if language.lower() in text:
keywords.add(language)
return keywords
def parse_bibtex_entry(entry: str) -> Dict[str, str]:
"""
Parse a single BibTeX entry (same logic as JavaScript version).
"""
paper = {}
# Extract entry type and key
type_match = re.match(r'@(\w+)\{([^,]+)', entry)
if type_match:
paper['type'] = type_match.group(1)
paper['key'] = type_match.group(2)
else:
# If we can't parse the type/key, skip this entry
return None
# Extract fields
fields = ['title', 'author', 'abstract', 'year', 'booktitle', 'journal', 'pages']
for field in fields:
# Match both {content} and "content" formats
pattern = rf'{field}\s*=\s*{{([^}}]*)}}|{field}\s*=\s*"([^"]*)"'
match = re.search(pattern, entry, re.IGNORECASE)
if match:
value = match.group(1) or match.group(2)
# Clean up LaTeX commands
value = clean_latex_commands(value)
paper[field] = value.strip()
# Extract year from key if not found in fields
if not paper.get('year') and paper.get('key'):
year_match = re.search(r'\d{4}', paper['key'])
if year_match:
paper['year'] = year_match.group(0)
# Determine if paper is multilingual
paper['is_multilingual'], matched_keyword = is_multilingual_paper(paper)
paper['keywords'] = list(extract_keywords(paper))
paper['matched_keyword'] = matched_keyword
return paper
def parse_bibtex(bib_text: str) -> List[Dict[str, str]]:
"""
Parse BibTeX text into list of paper dictionaries (same logic as JavaScript version).
"""
papers = []
# Split by @ to get individual entries
entries = re.split(r'(?=@)', bib_text)
n_missing, n_total = 0, len(entries)
for entry in tqdm(entries, desc="Parsing BibTeX entries"):
if not entry.strip():
continue
# try:
paper = parse_bibtex_entry(entry)
if paper and (paper.get('title') or paper.get('abstract')):
papers.append(paper)
elif paper is None:
n_missing += 1
# print(f"Warning: Skipping malformed entry (no type/key found)")
# except Exception as e:
# print(f"Warning: Error parsing entry: {e}")
continue
keyword2count = defaultdict(int)
for paper in papers:
if not paper['matched_keyword']: continue
keyword2count[paper['matched_keyword']] += 1
n_multilingual_papers = sum(keyword2count.values())
print(f"Found {len(papers)} papers out of {n_total} total papers. Ratio: {len(papers)/n_total*100:.1f}%")
print(f"Missing {n_missing} papers out of {n_total} total papers. Ratio: {n_missing/n_total*100:.1f}%")
# sort by keyword count
keyword2count = sorted(keyword2count.items(), key=lambda x: x[1], reverse=True)
for keyword, count in keyword2count:
print(f"\t {keyword}: {count} papers ({count/n_multilingual_papers*100:.1f}%)")
return papers
def generate_bibtex_content(papers: List[Dict[str, str]]) -> str:
"""
Generate BibTeX content from paper dictionaries (same logic as JavaScript version).
"""
content = ''
for paper in tqdm(papers, desc="Generating BibTeX content"):
# Check if paper has required fields
if not paper.get('type') or not paper.get('key'):
print(f"Warning: Skipping paper without type or key: {paper.get('title', 'Unknown')[:50]}...")
continue
# Reconstruct the original BibTeX entry
content += f"@{paper['type']}{{{paper['key']},\n"
fields = ['title', 'author', 'abstract', 'year', 'booktitle', 'journal', 'pages']
for field in fields:
if paper.get(field):
content += f" {field} = {{{paper[field]}}},\n"
# Remove trailing comma and add closing brace
content = content.rstrip(',\n') + '\n'
content += '}\n\n'
return content
def main():
"""
Main function to generate multilingual_papers.bib.
"""
input_file = 'data/anthology+abstracts.bib'
output_file = 'data/multilingual_papers.bib'
# Check if input file exists
if not os.path.exists(input_file):
print(f"Error: {input_file} not found in current directory.")
print("Please ensure the file exists and run the script again.")
return
# Check if output file already exists
if os.path.exists(output_file):
print(f"Warning: {output_file} already exists.")
response = input("Do you want to overwrite it? (y/N): ")
if response.lower() != 'y':
print("Operation cancelled.")
return
print(f"Reading {input_file}...")
# try:
if True:
# Read the input file
with open(input_file, 'r', encoding='utf-8') as f:
bib_text = f.read()
all_papers = parse_bibtex(bib_text)
print(f"Found {len(all_papers)} total papers")
# Filter multilingual papers
multilingual_papers = [paper for paper in all_papers if paper['is_multilingual']]
print(f"Found {len(multilingual_papers)} multilingual papers out of {len(all_papers)} total papers. Ratio: {len(multilingual_papers)/len(all_papers)*100:.1f}%")
if not multilingual_papers:
print("No multilingual papers found. Check your keywords and language lists.")
return
# Generate BibTeX content
print("Generating BibTeX content...")
bib_content = generate_bibtex_content(multilingual_papers)
# Write to output file
print(f"Writing to {output_file}...")
with open(output_file, 'w', encoding='utf-8') as f:
f.write(bib_content)
print(f"Successfully generated {output_file} with {len(multilingual_papers)} papers!")
# Show some statistics
print("\nStatistics:")
print(f" Total papers processed: {len(all_papers)}")
print(f" Multilingual papers found: {len(multilingual_papers)}")
print(f" Percentage multilingual: {len(multilingual_papers)/len(all_papers)*100:.1f}%")
# Show top keywords
all_keywords = []
for paper in multilingual_papers:
all_keywords.extend(paper['keywords'])
keyword_counts = {}
for keyword in all_keywords:
keyword_counts[keyword] = keyword_counts.get(keyword, 0) + 1
top_keywords = sorted(keyword_counts.items(), key=lambda x: x[1], reverse=True)[:10]
print("\nTop 10 keywords found:")
for keyword, count in top_keywords:
print(f" {keyword}: {count} papers")
# except Exception as e:
# print(f"Error: {e}")
# return
if __name__ == "__main__":
main() |