Zotero + PapersWithCode Integration

date
Mar 28, 2022
slug
zotero-paperswithcode-integration
status
Published
tags
🆒 Gadgets
summary
Search code/open source just one tap in your Zotero~
type
Post

Instructions

  1. Open your Zotero, and select the collection that you want to search the code availability for.
  1. Open the JavaScript editor in Zotero as following.
notion image
 
  1. Copy & paste the following code into the editor.
    1. ⚠️
      The Code/YES tag would be added if this paper have an open source code. The extra field would be replaced by the url of the code, TAKE CARE!
let collection = ZoteroPane.getSelectedCollection();

let itemIDs = collection.getChildItems(true);
const fieldName = 'extra'
const fieldID = Zotero.ItemFields.getID(fieldName);
// itemIDs

function extractCodeURL(data) {
    if (!data || data.length == 0) return "";
    if (data[0].repository && data[0].repository.url) return data[0].repository.url;
    return "";
}

async function getCodeURL(title) {
    const url = 'https://paperswithcode.com/api/v1/search/?q=' + title
    return fetch(url)
            .then(res => res.json())
            .then(data => data.results)
            .then(results => results.filter(
                item => item.paper.title === title
            ))
            .then(filterdResults => extractCodeURL(filterdResults))
}

let results = []

await Zotero.DB.executeTransaction(async function () {
    for (let id of itemIDs) {
        let item = await Zotero.Items.getAsync(id);
        let codeURL = await getCodeURL(item.getField('title'))
        if (codeURL) {
            results.push(codeURL);
						// Add `Code/YES` tag
            item.addTag('Code/YES', 0);
        }
        let mappedFieldID = Zotero.ItemFields.getFieldIDFromTypeAndBase(item.itemTypeID, fieldName);
        item.setField(mappedFieldID ? mappedFieldID : fieldID, codeURL);
        await item.save({
            skipDateModifiedUpdate: true
        });
    }
});

return results;
 
  1. Make sure the Run as async function button is checked.
notion image
  1. And just press the Run button (shortcut on macOS: ⌘Command + R), take a sip of coffee and just wait. The waiting time is respect to the number of paper in the selected collection.
notion image

© Zack Zhou 2021 - 2022