-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtransformers.rs
More file actions
407 lines (349 loc) · 15.1 KB
/
transformers.rs
File metadata and controls
407 lines (349 loc) · 15.1 KB
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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
use biblatex::Person;
use biblatex::{Entry, EntryType};
use std::cmp::Ordering;
use std::collections::HashMap;
use utils::BiblatexUtils;
use validators::{MatchedCitation, MatchedCitationDisambiguated};
use crate::utils;
use crate::validators;
use crate::validators::ArticleFileData;
/// Transform a list of entries into a list of strings according to the Chicago bibliography style.
pub fn entries_to_strings(entries: &[MatchedCitationDisambiguated]) -> Vec<String> {
let sorted_entries = sort_entries(entries);
let mut strings_output: Vec<String> = Vec::new();
for matched_citation in sorted_entries {
match matched_citation.entry.entry_type {
EntryType::Book => {
strings_output.push(transform_book_entry(&matched_citation));
}
EntryType::Article => strings_output.push(transform_article_entry(&matched_citation)),
_ => println!(
"Entry type not supported: {:?}",
&matched_citation.entry.entry_type
),
}
}
strings_output
}
/// Finds and replaces bibtex keys with disambiguated inline citations
pub fn transform_keys_to_citations(article_file_data: &ArticleFileData) -> String {
let mut full_content = article_file_data.full_file_content.clone();
for matched_citation in &article_file_data.entries_disambiguated {
if matched_citation.citation_raw.starts_with('@') {
full_content = full_content.replace(
&matched_citation.citation_raw,
&matched_citation.citation_author_date_disambiguated,
);
}
}
full_content
}
/// Transform MatchedCitation vector into MatchedCitationDisambiguated vector
/// This handles all disambiguation logic in one place
pub fn disambiguate_matched_citations(
citations: Vec<MatchedCitation>,
) -> Vec<MatchedCitationDisambiguated> {
// Group citations by author-year for disambiguation analysis
let mut author_year_groups: HashMap<String, Vec<&MatchedCitation>> = HashMap::new();
for citation in &citations {
let author = citation.entry.author().unwrap();
let author_last_name = author[0].name.clone();
let date = citation.entry.date().unwrap();
let year =
BiblatexUtils::extract_year_from_date(&date, citation.entry.key.clone()).unwrap();
let author_year_key = format!("{}-{}", author_last_name, year);
author_year_groups
.entry(author_year_key)
.or_default()
.push(citation);
}
// Create disambiguation mapping
let mut citation_to_disambiguated: HashMap<String, String> = HashMap::new();
let mut year_to_disambiguated: HashMap<String, String> = HashMap::new();
for (_author_year_key, group_citations) in author_year_groups {
if group_citations.len() > 1 {
// Need disambiguation - sort by entry key for consistent ordering
let mut sorted_citations = group_citations;
sorted_citations.sort_by(|a, b| a.entry.key.cmp(&b.entry.key));
for (index, citation) in sorted_citations.iter().enumerate() {
let letter = char::from(b'a' + index as u8);
let disambiguated = create_disambiguated_citation(letter, &citation.entry);
citation_to_disambiguated.insert(citation.citation_raw.clone(), disambiguated);
let disambiguated_year = create_disambiguated_year(letter, &citation.entry);
year_to_disambiguated.insert(citation.citation_raw.clone(), disambiguated_year);
}
} else {
// No disambiguation needed - convert to standard format
let citation = group_citations[0];
let standard = create_standard_citation(&citation.citation_raw, &citation.entry);
citation_to_disambiguated.insert(citation.citation_raw.clone(), standard);
}
}
// Transform all citations using the disambiguation map
citations
.into_iter()
.map(|matched_citation| {
let disambiguated = citation_to_disambiguated
.get(&matched_citation.citation_raw)
.cloned()
.unwrap_or_else(|| matched_citation.citation_raw.clone()); // Fallback
let disambiguated_year = year_to_disambiguated
.get(&matched_citation.citation_raw)
.cloned()
.unwrap_or_else(|| extract_date(&matched_citation.entry).to_string());
MatchedCitationDisambiguated {
citation_raw: matched_citation.citation_raw,
citation_author_date_disambiguated: disambiguated,
year_disambiguated: disambiguated_year,
entry: matched_citation.entry,
}
})
.collect()
}
/// Transform a book entry into a string according to the Chicago bibliography style.
fn transform_book_entry(matched_citation: &MatchedCitationDisambiguated) -> String {
let mut book_string = String::new();
let author = matched_citation.entry.author().unwrap();
let year = matched_citation.year_disambiguated.clone();
let title = extract_title(&matched_citation.entry);
let publisher = extract_publisher(&matched_citation.entry);
let address = extract_address(&matched_citation.entry);
let translators = matched_citation.entry.translator().unwrap_or_default();
let doi = matched_citation.entry.doi().unwrap_or("".to_string());
add_authors(author, &mut book_string);
add_year(year, &mut book_string);
add_book_title(title, &mut book_string);
add_translators(translators, &mut book_string);
add_address_and_publisher(address, publisher, &mut book_string);
add_doi(doi, &mut book_string);
book_string.trim_end().to_string()
}
/// Transform an article entry into a string according to the Chicago bibliography style.
fn transform_article_entry(matched_citation: &MatchedCitationDisambiguated) -> String {
let mut article_string = String::new();
let author = matched_citation.entry.author().unwrap();
let year = matched_citation.year_disambiguated.clone();
let title = extract_title(&matched_citation.entry);
let journal = extract_journal(&matched_citation.entry);
let volume = extract_volume(&matched_citation.entry);
let number = extract_number(&matched_citation.entry);
let pages = extract_pages(&matched_citation.entry);
let translators = matched_citation.entry.translator().unwrap_or_default();
let doi = matched_citation.entry.doi().unwrap_or("".to_string());
add_authors(author, &mut article_string);
add_year(year, &mut article_string);
add_article_title(title, &mut article_string);
add_journal_volume_number_pages(journal, volume, number, pages, &mut article_string);
add_translators(translators, &mut article_string);
add_doi(doi, &mut article_string);
article_string.trim_end().to_string()
}
/// Generate a string of a type of contributors.
/// E.g. "Edited", "Translated" become "Edited by", "Translated by".
/// Handles the case when there are multiple contributors.
fn generate_contributors(
contributors: Vec<biblatex::Person>,
contributor_description: String,
) -> String {
let mut contributors_str = String::new();
match contributors.len().cmp(&1) {
Ordering::Greater => {
contributors_str.push_str(&format!("{} by ", contributor_description));
for (i, person) in contributors.iter().enumerate() {
if i == contributors.len() - 1 {
contributors_str
.push_str(&format!("and {} {}. ", person.given_name, person.name));
} else {
contributors_str.push_str(&format!("{} {}, ", person.given_name, person.name));
}
}
}
Ordering::Equal => {
contributors_str.push_str(&format!(
"{} by {} {}. ",
contributor_description, contributors[0].given_name, contributors[0].name
));
}
Ordering::Less => {}
}
contributors_str
}
fn add_year(year: String, target_string: &mut String) {
target_string.push_str(&format!("{}. ", year));
}
// Adds author(s). Handles multiple.
fn add_authors(author: Vec<biblatex::Person>, bib_html: &mut String) {
bib_html.push_str(&format_authors(author))
}
/// Returns Chicago style format for authors. Handles the case when there are multiple authors.
fn format_authors(author: Vec<biblatex::Person>) -> String {
match author.len().cmp(&2) {
Ordering::Greater => {
format!("{}, {} et al. ", author[0].name, author[0].given_name)
}
Ordering::Equal => {
// In Chicago style, when listing multiple authors in a bibliography entry,
// only the first author's name is inverted (i.e., "Last, First"). The second and subsequent
// authors' names are written in standard order (i.e., "First Last").
// This rule helps differentiate the primary author from co-authors.
format!(
"{}, {} and {} {}. ",
author[0].name, author[0].given_name, author[1].given_name, author[1].name
)
}
Ordering::Less => {
format!("{}, {}. ", author[0].name, author[0].given_name)
}
}
}
/// Returns Chicago style format for authors. Handles the case when there are multiple authors.
fn format_authors_last_name_only(author: Vec<biblatex::Person>) -> String {
match author.len().cmp(&2) {
Ordering::Greater => {
format!("{} et al.", author[0].name)
}
Ordering::Equal => {
format!("{} and {}", author[0].name, author[1].name)
}
Ordering::Less => author[0].name.to_string(),
}
}
/// Add translators to the target string if they exist.
fn add_translators(translators: Vec<biblatex::Person>, target_string: &mut String) {
let translators_mdx = generate_contributors(translators, "Translated".to_string());
if !translators_mdx.is_empty() {
target_string.push_str(&translators_mdx);
}
}
/// Add DOI to the target string if it exists.
fn add_doi(doi: String, target_string: &mut String) {
if !doi.is_empty() {
target_string.push_str(&format!(" https://doi.org/{}.", doi));
}
}
/// Add book title to the target string. Mainly used for books.
fn add_book_title(title: String, target_string: &mut String) {
target_string.push_str(&format!("_{}_. ", title));
}
/// Add article title to the target string. Mainly used for articles.
fn add_article_title(title: String, target_string: &mut String) {
target_string.push_str(&format!("\"{}\". ", title));
}
/// Add address and publisher to the target string. Mainly used for books.
fn add_address_and_publisher(address: String, publisher: String, target_string: &mut String) {
target_string.push_str(&format!("{}: {}. ", address, publisher));
}
/// Add journal, volume, number, year, and pages to the target string. Mainly used for articles.
fn add_journal_volume_number_pages(
journal: String,
volume: i64,
number: String,
pages: String,
target_string: &mut String,
) {
target_string.push_str(&format!(
"_{}_ {} ({}): {}. ",
journal, volume, number, pages
));
}
/// Sort entries by author's last name.
fn sort_entries(entries: &[MatchedCitationDisambiguated]) -> Vec<MatchedCitationDisambiguated> {
let mut sorted_entries = entries.to_vec();
sorted_entries.sort_by(|a, b| {
let a_authors = a.entry.author().unwrap_or_default();
let b_authors = b.entry.author().unwrap_or_default();
// Get author names for comparison
let a_author_key = author_key(&a_authors);
let b_author_key = author_key(&b_authors);
// Compare by author(s)
let cmp_author = a_author_key.cmp(&b_author_key);
if cmp_author != std::cmp::Ordering::Equal {
return cmp_author;
}
// Compare by year
let a_year = &a.year_disambiguated;
let b_year = &b.year_disambiguated;
let cmp_year = a_year.cmp(b_year);
if cmp_year != std::cmp::Ordering::Equal {
return cmp_year;
}
// Compare by title (for disambiguation)
let a_title = extract_title(&a.entry).to_lowercase();
let b_title = extract_title(&b.entry).to_lowercase();
a_title.cmp(&b_title)
});
sorted_entries
}
/// Helper to generate a sortable author string
fn author_key(authors: &[Person]) -> String {
authors
.first()
.map(|p| p.name.clone().to_lowercase())
.unwrap_or_default()
}
/// Title of the entry.
fn extract_title(entry: &Entry) -> String {
let title_spanned = entry.title().unwrap();
BiblatexUtils::extract_spanned_chunk(title_spanned)
}
/// Publisher of the entry.
fn extract_publisher(entry: &Entry) -> String {
let publisher_spanned = entry.publisher().unwrap();
BiblatexUtils::extract_publisher(&publisher_spanned)
}
/// Address of the publisher.
fn extract_address(entry: &Entry) -> String {
let address_spanned = entry.address().unwrap();
BiblatexUtils::extract_spanned_chunk(address_spanned)
}
/// Year of entry.
fn extract_date(entry: &Entry) -> i32 {
let date = entry.date().unwrap();
BiblatexUtils::extract_year_from_date(&date, entry.key.clone()).unwrap()
}
/// Name of the journal of the article.
fn extract_journal(entry: &Entry) -> String {
let journal_spanned = entry.journal().unwrap();
BiblatexUtils::extract_spanned_chunk(journal_spanned)
}
/// Volume of the journal.
fn extract_volume(entry: &Entry) -> i64 {
let volume_permissive = entry.volume().unwrap();
BiblatexUtils::extract_volume(&volume_permissive)
}
/// Number of the journal.
fn extract_number(entry: &Entry) -> String {
let number_spanned = entry.number().unwrap();
BiblatexUtils::extract_spanned_chunk(number_spanned)
}
/// Pages of the article.
fn extract_pages(entry: &Entry) -> String {
let pages_permissive = entry.pages().unwrap();
BiblatexUtils::extract_pages(&pages_permissive)
}
/// Create disambiguated citation with letter (e.g., "@hegel2020logic, 123" -> "Hegel 2020a")
fn create_disambiguated_citation(letter: char, entry: &Entry) -> String {
let author = format_authors_last_name_only(entry.author().unwrap());
let year = extract_date(entry);
format!("{} {}{}", author, year, letter)
}
/// Create a disambiguated year (e.g., "2018a")
fn create_disambiguated_year(letter: char, entry: &Entry) -> String {
let year = extract_date(entry);
format!("{}{}", year, letter)
}
/// Create standard citation format (no disambiguation needed)
fn create_standard_citation(raw_citation: &str, entry: &Entry) -> String {
if raw_citation.starts_with('@') {
// Convert @key to Author Year format
let author = entry.author().unwrap();
let author_last_name = author[0].name.clone();
let date = entry.date().unwrap();
let year = BiblatexUtils::extract_year_from_date(&date, entry.key.clone()).unwrap();
format!("{} {}", author_last_name, year)
} else {
// Already in standard format, return as-is
raw_citation.to_string()
}
}
// TODO build test suite for creating disambiguate_matched_citations