papers 0.1.1

A library to allow creation and updates of Wikidata items for scientific publications, authors, and related info
Documentation
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
408
409
410
411
412
413
414
use std::collections::HashMap;

use async_trait::async_trait;
use semanticscholar::*;

use self::identifiers::{GenericWorkIdentifier, GenericWorkType, IdProp};
use crate::{
    adapter_helpers::wb_time_from_partial, generic_author_info::GenericAuthorInfo,
    scientific_publication_adapter::ScientificPublicationAdapter, *,
};

pub struct Semanticscholar2Wikidata {
    author_cache: HashMap<String, String>,
    work_cache: HashMap<String, Work>,
    client: Client,
}

impl Default for Semanticscholar2Wikidata {
    fn default() -> Self {
        // Wire the shared papers reqwest::Client into the SDK so the
        // adapter and the rest of the bot share one connection pool,
        // one User-Agent, and one timeout config. See audit P2-10b.
        let client = Client::new().http_client(crate::http_client::http_client().clone());
        Self::new_with_client(client)
    }
}

impl Semanticscholar2Wikidata {
    pub fn new() -> Self {
        Self::default()
    }

    /// New adapter with a caller-provided SDK client. Tests construct
    /// a `semanticscholar::Client::new().base_url(mock.uri())` and pass
    /// it here; production goes through `Default::default()` which
    /// shares the bot-wide HTTP client.
    pub fn new_with_client(client: Client) -> Self {
        Semanticscholar2Wikidata {
            author_cache: HashMap::new(),
            work_cache: HashMap::new(),
            client,
        }
    }

    pub fn get_cached_publication_from_id(&self, publication_id: &str) -> Option<&Work> {
        self.work_cache.get(publication_id)
    }

    async fn publication_ids_from_doi(&mut self, doi: &str) -> Vec<String> {
        let work = match self.client.work(doi).await {
            Ok(w) => w,
            _ => return vec![], // No such work
        };

        let publication_id = match &work.paper_id {
            Some(paper_id) => paper_id.to_string(),
            None => return vec![], // No ID
        };

        self.work_cache.insert(publication_id.clone(), work);
        vec![publication_id]
    }

}

#[async_trait(?Send)]
impl ScientificPublicationAdapter for Semanticscholar2Wikidata {
    fn name(&self) -> &str {
        "Semanticscholar2Wikidata"
    }

    fn author_property(&self) -> Option<String> {
        Some("P4012".to_string())
    }

    fn publication_property(&self) -> Option<IdProp> {
        Some(IdProp::SemanticScholar)
    }

    // TODO load direct from SS via own ID
    // fn publication_id_from_item(&mut self, item: &Entity) -> Option<String> {
    // let publication_id = match self
    // .get_external_identifier_from_item(item,
    // &self.publication_property().unwrap()) {
    // Some(s) => s,
    // None => return None,
    // };
    // self.publication_id_from_pubmed(&publication_id)
    // }

    fn topic_property(&self) -> Option<String> {
        Some("P6611".to_string())
    }

    fn author_cache(&self) -> &HashMap<String, String> {
        &self.author_cache
    }

    fn author_cache_mut(&mut self) -> &mut HashMap<String, String> {
        &mut self.author_cache
    }

    fn has_cached_publication(&self, publication_id: &str) -> bool {
        self.get_cached_publication_from_id(publication_id).is_some()
    }

    fn extract_extra_ids(&self, publication_id: &str) -> Vec<GenericWorkIdentifier> {
        let Some(work) = self.get_cached_publication_from_id(publication_id) else {
            return vec![];
        };
        let mut extras = Vec::new();
        if let Some(doi) = &work.doi {
            extras.push(GenericWorkIdentifier::new_prop(IdProp::DOI, doi));
        }
        extras
    }

    async fn get_identifier_list(
        &mut self,
        ids: &[GenericWorkIdentifier],
    ) -> Vec<GenericWorkIdentifier> {
        let mut ret: Vec<GenericWorkIdentifier> = vec![];
        for id in ids {
            if let GenericWorkType::Property(prop) = id.work_type() {
                if *prop == IdProp::DOI {
                    for publication_id in self.publication_ids_from_doi(id.id()).await {
                        self.add_identifiers_from_cached_publication(&publication_id, &mut ret);
                    }
                }
            }
        }
        ret
    }

    async fn do_cache_work(&mut self, publication_id: &str) -> Option<String> {
        let work = match self.client.work(publication_id).await {
            Ok(w) => w,
            _ => return None, // No such work
        };

        let publication_id = match &work.paper_id {
            Some(paper_id) => paper_id.to_string(),
            None => return None, // No ID
        };

        self.work_cache.insert(publication_id.clone(), work);
        Some(publication_id)
    }

    fn get_work_titles(&self, publication_id: &str) -> Vec<LocaleString> {
        match self.get_cached_publication_from_id(publication_id) {
            Some(work) => match &work.title {
                Some(title) => vec![LocaleString::new("en", title)],
                None => vec![],
            },
            None => vec![],
        }
    }

    async fn update_statements_for_publication_id(&self, publication_id: &str, item: &mut Entity) {
        let work = match self.get_cached_publication_from_id(publication_id) {
            Some(w) => w,
            None => return,
        };

        if !item.has_claims_with_property("P577") {
            if let Some(year) = work.year {
                let statement =
                    wb_time_from_partial("P577", year as u32, None, None, self.reference());
                item.add_claim(statement);
            }
        }
    }

    async fn get_author_list(&mut self, publication_id: &str) -> Vec<GenericAuthorInfo> {
        let mut ret: Vec<GenericAuthorInfo> = vec![];
        let work = match self.get_cached_publication_from_id(publication_id) {
            Some(w) => w,
            None => return ret,
        };

        let author_property = match self.author_property() {
            Some(p) => p,
            None => return ret,
        };

        for (num, author) in work.authors.iter().enumerate() {
            let mut entry = GenericAuthorInfo::new();
            entry.set_name(author.name.clone());
            entry.set_list_number(Some((num + 1).to_string()));
            if let Some(id) = &author.author_id {
                entry.prop2id_mut().insert(author_property.to_owned(), id.to_string());
            }
            ret.push(entry);
        }

        ret
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn make_work(title: Option<&str>, doi: Option<&str>, paper_id: Option<&str>) -> Work {
        Work {
            arxiv_id: None,
            authors: vec![],
            citation_velocity: None,
            citations: vec![],
            doi: doi.map(|s| s.to_string()),
            influential_citation_count: None,
            paper_id: paper_id.map(|s| s.to_string()),
            references: vec![],
            title: title.map(|s| s.to_string()),
            topics: vec![],
            url: None,
            venue: None,
            year: None,
        }
    }

    fn make_ss(id: &str, work: Work) -> Semanticscholar2Wikidata {
        let mut ss = Semanticscholar2Wikidata::new();
        ss.work_cache.insert(id.to_string(), work);
        ss
    }

    // === property getters ===

    #[test]
    fn name_returns_expected_string() {
        let ss = Semanticscholar2Wikidata::new();
        assert_eq!(ss.name(), "Semanticscholar2Wikidata");
    }

    #[test]
    fn author_property_returns_p4012() {
        let ss = Semanticscholar2Wikidata::new();
        assert_eq!(ss.author_property(), Some("P4012".to_string()));
    }

    #[test]
    fn publication_property_returns_semantic_scholar() {
        let ss = Semanticscholar2Wikidata::new();
        assert_eq!(ss.publication_property(), Some(IdProp::SemanticScholar));
    }

    #[test]
    fn topic_property_returns_p6611() {
        let ss = Semanticscholar2Wikidata::new();
        assert_eq!(ss.topic_property(), Some("P6611".to_string()));
    }

    // === get_work_titles ===

    #[test]
    fn get_work_titles_returns_title() {
        let ss = make_ss("abc123", make_work(Some("A paper title"), None, None));
        let titles = ss.get_work_titles("abc123");
        assert_eq!(titles.len(), 1);
        assert_eq!(titles[0].value(), "A paper title");
        assert_eq!(titles[0].language(), "en");
    }

    #[test]
    fn get_work_titles_returns_empty_when_no_title() {
        let ss = make_ss("abc123", make_work(None, None, None));
        assert!(ss.get_work_titles("abc123").is_empty());
    }

    #[test]
    fn get_work_titles_returns_empty_for_missing_publication() {
        let ss = Semanticscholar2Wikidata::new();
        assert!(ss.get_work_titles("nonexistent").is_empty());
    }

    // === add_identifiers_from_cached_publication ===

    #[test]
    fn add_identifiers_includes_semantic_scholar_id() {
        let ss = make_ss("abc123", make_work(None, None, None));
        let mut ret = vec![];
        ss.add_identifiers_from_cached_publication("abc123", &mut ret);
        assert!(ret.iter().any(|id| id.work_type()
            == &identifiers::GenericWorkType::Property(IdProp::SemanticScholar)
            && id.id() == "abc123"));
    }

    #[test]
    fn add_identifiers_includes_doi_when_present() {
        let ss = make_ss("abc123", make_work(None, Some("10.1234/test"), None));
        let mut ret = vec![];
        ss.add_identifiers_from_cached_publication("abc123", &mut ret);
        assert!(ret
            .iter()
            .any(|id| id.work_type() == &identifiers::GenericWorkType::Property(IdProp::DOI)));
    }

    #[test]
    fn add_identifiers_no_doi_when_absent() {
        let ss = make_ss("abc123", make_work(None, None, None));
        let mut ret = vec![];
        ss.add_identifiers_from_cached_publication("abc123", &mut ret);
        assert!(!ret
            .iter()
            .any(|id| id.work_type() == &identifiers::GenericWorkType::Property(IdProp::DOI)));
    }

    #[test]
    fn add_identifiers_does_nothing_for_missing_publication() {
        // Defensive check: the function bails out via has_cached_publication
        // when the work isn't cached, so callers can't accidentally fabricate
        // claims for non-existent publications.
        let ss = Semanticscholar2Wikidata::new();
        let mut ret = vec![];
        ss.add_identifiers_from_cached_publication("nonexistent", &mut ret);
        assert!(ret.is_empty());
    }

    // === get_author_list ===

    #[tokio::test]
    async fn get_author_list_returns_authors_with_names() {
        let work = Work {
            authors: vec![
                Author {
                    author_id: Some("auth1".to_string()),
                    name: Some("Alice Smith".to_string()),
                    url: None,
                },
                Author {
                    author_id: None,
                    name: Some("Bob Jones".to_string()),
                    url: None,
                },
            ],
            ..make_work(None, None, None)
        };
        let mut ss = make_ss("abc123", work);
        let authors = ss.get_author_list("abc123").await;
        assert_eq!(authors.len(), 2);
        assert_eq!(authors[0].name(), Some("Alice Smith"));
        assert_eq!(authors[0].list_number(), Some("1"));
        assert_eq!(authors[1].name(), Some("Bob Jones"));
        assert_eq!(authors[1].list_number(), Some("2"));
    }

    #[tokio::test]
    async fn get_author_list_includes_author_id_in_prop2id() {
        let work = Work {
            authors: vec![Author {
                author_id: Some("ss_auth_42".to_string()),
                name: Some("Carol White".to_string()),
                url: None,
            }],
            ..make_work(None, None, None)
        };
        let mut ss = make_ss("abc123", work);
        let authors = ss.get_author_list("abc123").await;
        assert_eq!(authors.len(), 1);
        assert_eq!(authors[0].prop2id().get("P4012"), Some(&"ss_auth_42".to_string()));
    }

    #[tokio::test]
    async fn get_author_list_empty_for_missing_publication() {
        let mut ss = Semanticscholar2Wikidata::new();
        assert!(ss.get_author_list("nonexistent").await.is_empty());
    }

    // === P2-10b: SDK DI via base_url ======================================
    //
    // Verifies the new_with_client injection actually routes the SDK's HTTP
    // calls through a caller-controlled endpoint. wiremock stands in for the
    // real Semantic Scholar API.

    use wiremock::matchers::{method as wm_method, path as wm_path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    #[tokio::test]
    async fn publication_ids_from_doi_hits_injected_base_url() {
        let server = MockServer::start().await;
        Mock::given(wm_method("GET"))
            .and(wm_path("/paper/10.1234/test"))
            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
                "paperId": "abc123",
                "authors": [],
                "topics": [],
            })))
            .expect(1)
            .mount(&server)
            .await;

        let sdk = Client::new().base_url(server.uri());
        let mut adapter = Semanticscholar2Wikidata::new_with_client(sdk);
        let ids = adapter.publication_ids_from_doi("10.1234/test").await;
        assert_eq!(ids, vec!["abc123".to_string()]);
        assert!(adapter.get_cached_publication_from_id("abc123").is_some());
    }

    #[tokio::test]
    async fn publication_ids_from_doi_returns_empty_on_sdk_500() {
        let server = MockServer::start().await;
        Mock::given(wm_method("GET"))
            .respond_with(ResponseTemplate::new(500))
            .mount(&server)
            .await;

        let sdk = Client::new().base_url(server.uri());
        let mut adapter = Semanticscholar2Wikidata::new_with_client(sdk);
        let ids = adapter.publication_ids_from_doi("10.1234/test").await;
        assert!(ids.is_empty(), "expected empty on 500, got {ids:?}");
    }
}