Web2Cit/Docs/Templates

From Meta, a Wikimedia project coordination wiki
This page is a translated version of the page Web2Cit/Docs/Templates and the translation is 100% complete.

Translation templates are based on specific webpages and include a series of translation procedures for each translation field. These translation procedures include a series of selection and and transformation steps which specify how to extract values from the template webpage and how to transform them to get valid outputs for the corresponding translation field.

Although translation templates are based on specific webpages, they may be used to translate other webpages from the same domain, according to the applicability criteria outlined below.

Multiple translation templates may be defined for a website/domain. As introduced in the Basics documentation page, when a target webpage is given to Web2Cit for translation, translation templates belonging to the same URL path patterns as the target web page are tried one after the other until one that applies is found.

Template definition

The templates configuration file for a website or domain may include one or more translation templates.

Template path

Each translation template is defined based on a specific webpage. This webpage's path is the translation template's path.

If multiple translation templates have been defined for the same or equivalent template paths, Web2Cit core only considers the first one and ignores the others.

Note that query strings are used by Web2Cit (i.e., they are passed to selection steps such as Citoid, XPath, and URL), but fragment identifiers are ignored.

Template label

Optionally, translation templates may have a label, which help Web2Cit collaborators understand why the template may have been defined.

Template fields

Translation templates include a series of template fields, matching the translation fields supported by Web2Cit. See our Fields documentation for a list of supported template fields and corresponding valid outputs.

Each template field has a validation rule, indicating what translation outputs are valid for that field.

If multiple template fields are defined for the same translation field, Web2Cit core currently considers the first one only.

Field requirement

Template fields may be marked as required or not. A required field is a field that must return a valid output for the template that it belongs to to be marked as applicable for the target webpage.

Mandatory fields

Mandatory fields are fields that must always be present in a translation template. Translation templates that do not include them will be ignored by Web2Cit. These fields are itemType and title.

Mandatory fields are also always marked as required.

Control field

The control field is a special type of template field that is not included in the template output. However, because the control field does count to decide whether a template is applicable or not for a given target webpage, it is useful to control which translation templates should be used to translate a given target webpage, in cases where URL path patterns cannot be used.

Translation procedures

Each template field may include one or more translation procedures (typically one). Translation procedures include a series of selection and transformation steps which respectively select elements on the target webpage that contain the relevant metadata, and transform them into a format that is valid for the current template field.

Read the following sections to find out about the selection and transformation steps available and how to use them.

선택 단계

선택 단계는 "번역 대상" 웹 페이지를 입력으로 사용하고 해당 웹 페이지에서 0개 이상의 선택된 값(문자열) 목록을 반환합니다.

다양한 선택 단계 type가 있으며 해당 동작은 config 매개변수를 사용하여 사용자 정의됩니다. 구성 값이 유효성 검사에 실패한 선택 단계는 무시됩니다.

시토이드 선택

Citoid 선택 단계는 "translation target"에 대한 Citoid 응답에서 필드를 선택합니다.

  • type: citoid
  • config: 모든 유효한 Citoid/Zotero 기본 필드 이름.[note 1] 위키미디어 REST API의 citation 엔드포인트를 사용하여 주어진 URL에 대해 Citoid가 반환하는 것을 확인할 수 있습니다. [1]mediawiki-basefields 형식을 사용해야 합니다. 모든 작성자 필드는 creatorFirstcreatorLast 필드로 분할됩니다. 예를 들어 author 필드는 authorFirstauthorLast 필드로 분할됩니다.

XPath 선택

XPath 선택 단계는 XPath를 사용하여 "번역 대상" HTML에서 노드를 선택합니다.

  • type: xpath
  • config: 모든 유효한 XPath v1.0 표현식. 웹 브라우저의 인스펙터(일부 브라우저에서는 F12로 표시)를 사용하여 HTML 노드에 대한 XPath 표현식을 얻을 수 있습니다. 동일한 노드에 대해 둘 이상의 XPath가 사용될 수 있으며 일부는 다른 것보다 더 강력할 수 있습니다. 또한 일부 브라우저 확장을 사용하여 일치하는 모든 노드를 강조 표시하여 XPath 표현식을 테스트할 수 있습니다.[note 2]

일부 웹 페이지에서는 자바스크립트를 사용하여 콘텐츠가 즉석에서 추가됩니다. Web2Cit은 시토이드와 마찬가지로 웹 페이지에서 자바스크립트를 실행하지 않습니다. 따라서 이러한 경우 사용자가 보는 것이 Web2Cit에서 보는 것과 다를 수 있습니다. 예를 들어 uBlock Origin과 같은 브라우저 확장을 사용하여 자바스크립트를 일시적으로 비활성화하는 것을 고려하세요.

고정 선택

고정 선택 단계는 항상 미리 정의된 동일한 값을 반환합니다.

  • type: fixed
  • config: 반환될 미리 정의된 값입니다.

JSON-LD selection

The JSON-LD selection selects one or more elements from JSON-LD objects present in the target webpage.

  • type: json-ld
  • config: any valid JMESPath expression, to be evaluated against an array including all JSON-LD objects found in the target webpage.

To test JMESPath expressions:

  1. Open the target webpage
  2. Use the Copy JSON-LD bookmarklet (see below) to copy an array including all JSON-LD objects available into your clipboard.
  3. On the JMESPath website, paste the array copied above
  4. Try different JMESPath expressions and check the results.[note 3]

Note that JSON-LD selection will always return an array of stringified values, ignoring not found (i.e., null) elements.

Copy JSON-LD bookmarklet

The following Copy JSON-LD bookmarklet would help you copy an array including all JSON-LD objects found on a target webpage, as described above:

  1. Add a new bookmark to your browser, preferably to your bookmark toolbar for easier access. You may name it "Copy JSON-LD".
  2. In the bookmark's URL field, type `javascript:` followed by the code below:
function concatAndCopy() {
  const nodes = Array.from(
    document.querySelectorAll('script[type="application/ld+json"')
  );
  let jsonld = [];
  const errors = [];
  nodes.forEach((script, index) => {
    let content = script.textContent;
    if (content !== null) {
      try {
        content = content.replace(/[\x00-\x1F\x7F\x80-\x9F]/g, " ");
        const json = JSON.parse(content);
        jsonld = jsonld.concat(json);
      } catch {
        errors.push(index);
      }
    }
  });
  navigator.clipboard.writeText(JSON.stringify(jsonld, undefined, 2)).then(
    () => {
      let message = "JSON-LD copied to clipboard!";
      if (errors.length > 0) {
        message += (
          "\n\nCould not parse JSON-LD objects: " +
          `${errors.map((index) => `#${index + 1}`).join(", ")}`
        );
      }
      alert(message);
    }
  );
};
concatAndCopy();

URL selection (proposed)

The URL selection is a proposed selection step that would allow selecting components from the target webpage's URL, such as its path or query string parameters. See T304326.

CSS selection (proposed)

The CSS selection is a proposed selection step that would allow selecting nodes from the target webpage's HTML using CSS (instead of XPath) selectors. See T308668.

Header selection (proposed)

The Header selection is a proposed selection step that would allow selecting headers from the target webpage's server response. See T304333.

Text fragment selection (proposed)

See T309658.

변환 단계

변환 단계는 0개 이상의 값 목록을 입력으로 사용합니다. 즉, 하나 이상의 선택 단계의 출력(1) 또는 다른 변환 단계의 출력(2)입니다. 0개 이상의 값(문자열)의 변환된 목록을 반환합니다.

다양한 선택 단계 type가 있으며 그 동작은 (1) config 매개변수, 및 (2) 입력 항목별로 변환을 적용해야 하는지 여부를 나타내는 itemwise 매개변수, 또는 전체 입력에 대해. 구성 값이 유효성 검사에 실패한 변환 단계는 무시됩니다.

변환에 참여

조인 변환 단계는 지정된 구분 기호를 사용하여 목록에 있는 둘 이상의 항목을 하나로 조인합니다.

  • type: join
  • config: 사용할 구분 기호
  • itemwise "(설정 = false)": true로 설정하면 변환이 입력 목록의 각 문자열에 독립적으로 적용되어 각 문자열을 문자 목록으로 사용합니다.

분할 변환

분할 변환 단계는 지정된 구분 기호에서 문자열을 둘 이상의 하위 문자열로 분할합니다.

  • type: split
  • config: 사용할 구분 기호
  • itemwise "(설정 = true)": false로 설정하면 문자열의 입력 목록이 먼저 분할이 적용되는 단일 문자열로 결합됩니다.

날짜 변환

날짜 변환 단계는 Sugar library[2]를 사용하여 자연어 날짜를 표준 YYYY-MM-DD 형식으로 구문 분석합니다. 가능하지 않으면 원래 값을 반환합니다.

  • type: date
  • config: 현재 지원되는 로케일 중 하나: ca, da, de, en, es, fi, fr, it, ja, ko, nl, no, pl, pt, ru, sv, zh-CN, zh-TW.
  • itemwise "(설정 = true)"

범위 변환

범위 변환은 하나 이상의 항목 또는 항목 범위를 선택하고 지정된 순서대로 반환합니다. 번호 매기기는 1부터 시작합니다(즉, 첫 번째 항목은 1).

  • type: range
  • config: 쉼표로 구분된 하나 이상의 범위입니다. 범위는 다음 형식 중 하나일 수 있습니다:
    • start:end: start부터 end, end까지의 요소를 선택합니다.
    • start:: start에서 목록의 마지막 항목까지 요소를 선택합니다.
    • :end: 목록의 처음부터 end, end까지의 요소를 선택합니다.
    • start: start 인덱스에서 단일 요소를 선택합니다.
  • itemwise "(설정 = false)": true로 설정하면 변환이 입력 목록의 각 문자열에 독립적으로 적용되어 각 문자열을 문자 목록으로 사용합니다.

변환 일치

일치 변환은 대상과 일치하는 하나 이상의 하위 문자열을 반환합니다.

  • type: match.
  • config: 일치하는 대상, 일반 문자열 또는 정규식으로 표현됩니다.(자바스크립트 "취향"에서) 정규식을 사용하려면 / 사이에 패턴을 래핑하고 그 뒤에 선택적 플래그가 옵니다.[3] 예를 들어, /(sub)?string/i는 대소문자를 구분하지 않고 string 또는 substring과 일치합니다.[note 4] 정규식으로 해석될 수 있는 문자열(즉, 패턴 \/.*\/[a-z]*과 일치하는 문자열)과 일치해야 하는 경우 대신 정규식으로 표현합니다. 예를 들어, 문자열 /.*/를 문자 그대로 일치시키고 정규식 .*으로 해석되지 않도록 하려면 대신 정규식 //\\.\\+//로 표현하세요(이중 이스케이프된 특수 문자: [4] \\.\\+ 참고).
  • itemwise "(설정 = true)"


각 일치 항목은 별도의 출력 항목으로 반환됩니다. 예를 들어, 대상 string에 대해 문자열 내부의 하위 문자열을 일치시키면 두 항목 배열 출력이 반환됩니다: ["string", "string"], 각 일치 항목에 대해 하나씩. 정규식에서 캡처링 그룹을 사용하는 경우 [5] 그룹 일치만 반환됩니다(즉, 전체 일치가 아님).

주어진 입력 항목에 대해 일치하는 항목이 없으면 입력 항목이 무시됩니다(즉, 변환 출력에 포함되지 않음). 예를 들어, 대상 substring에 대해 두 항목 배열 입력 ["a string with a substring", "a string without it"]을 일치시키면 한 항목 배열 출력이 반환됩니다: ["substring"].

변환 교체(제안)

대체 변환은 위에서 설명한 일치 변환과 유사하지만 대상 일치를 대체할 추가 replace 매개변수가 있을 예정입니다. See T302691.

In the meantime, you may consider using a Split transformation followed by a Join transformation as a workaround.

Case transformation (proposed)

The Case transformation is a proposed transformation step that would transform input strings into lower, UPPER, Sentence or Title Case. See T302692.

Custom transformation (proposed)

The Custom transformation is a proposed transformation step that would apply a custom defined JavaScript function. It has also been proposed that these custom functions may be collaboratively maintained. See T305883 and T305886.

Fallback template

The fallback template is a default translation template that will be used to translate a given target webpage when no applicable templates have been found for it (see the Translation section below).

This fallback template is meant to return a translation as close to the Citoid translation as Web2Cit allows, by using Citoid selection in all its template fields. The fallback template should be applicable for most target webpages, except a few cases (see T305168).

The fallback template is defined in the Web2Cit Core repository as follows:

Fieldname Selection

(type: config)

Transformation

(type: config)

Notes
Item type Citoid: itemType -
Title Citoid: title -
Author first names Citoid: authorFirst -
Author last names Citoid: authorLast -
Publication date Citoid: date Date: en[note 5]
Published in
  1. Citoid: publicationTitle
  2. Citoid: code
  3. Citoid: reporter
Range: 1[note 5] Citoid/Zotero includes "container title" metadata in different base fields depending on the source's type.[6]
Published by Citoid: publisher -
Language Citoid: language

Note that there is a proposal to change the fallback approach of Web2Cit translation; see T302019.

Translation

Translation templates are based on specific webpages, but they may be used to translate other target webpages from the same domain and URL path pattern group, provided that some applicability criteria is met.

Briefly, given a target webpage, first a list of candidate templates to try translating it with is set up. Then, each of these templates is tried on the target webpage in order, returning an output for each of its template fields. Finally, translation ends when an applicable template is found, or when no candidate templates are left to try.

Candidate templates

First, a list of translation templates that will be tried on the target webpage is set up:

  1. If a translation template has been defined for the target webpage, it will be tried first.
  2. Next, all translation templates sorted into the same URL path pattern group as the target webpage, in the order in which they have been defined.
  3. Finally, the fallback template.

Then, these templates are tried one by one on the target webpage, as described below.

Template field outputs

Translation templates include template fields, which in turn include translation procedures, as described in the Template definition section above. For each of these translation procedures:

  1. First, selection steps are applied on the target webpage. The outputs from all selection steps are concatenated into a single selection output,[note 6] and passed to the first transformation step below.
  2. Transformation steps are applied sequentially, the output of each step being passed to the following step on the list.[note 6] The output of the last transformation step becomes the transformation output, which is the translation procedure's output.

The translation procedure's output is the transformation output, or the selection output in case no transformation steps have been defined.

The outputs from all translation procedures defined for a template field are concatenated in order into a single field output. If the template field corresponds to single-valued translation fields, the output values are joined with a , delimiter.

Finally, the translation field's validation pattern (see the Fields documentation) is used to decide whether the field output is valid or not. All output values must be valid according to this validation pattern for the field output to be valid. Empty outputs ([]) are always invalid.

Template applicability

The procedure described above is repeated for all template fields of a translation template. If all template fields marked as required return valid outputs, the translation template is deemed applicable for the target webpage, translation stops there and a citation is returned.

Citation

Translation templates that result applicable for a target webpage, can return a citation for it. These citations include metadata for the target webpage following the format used by Citoid/Zotero.

To generate a citation, template outputs are mapped to the corresponding Citoid/Zotero field. Mapping from Web2Cit to Citoid/Zotero fields is described in the Fields documentation.

Invalid outputs for template fields that have been marked as non-required are simply excluded from the citation.

Notes

  1. Citoid/Zotero 필드는 기본 필드 또는 파생 필드일 수 있습니다. 일부 항목 유형에는 기본 필드에 다시 매핑되는 일부 필드에 대한 파생 필드가 있습니다. Web2Cit에서는 기본 필드만 사용합니다. 여기에서 파생 및 기반 일반 및 작성자 필드 목록을 찾을 수 있습니다.
  2. 파이어폭스에 1달러 또는 크롬에 2달러를 줄 수 있습니다.
  3. The JMESPath website does not currently show when an error has been found either in the JSON input or in the JMESPath expression. This has been reported to the maintainers and is pending resolution here.
  4. 정규 표현식을 테스트하는 데 도움이 되는 도구(예: regex101)를 사용할 수 있습니다.
  5. a b See T308354 for discussion on whether transformation steps may be omitted from the fallback template.
  6. a b As per T305163, selection or transformation steps failing on the application stage (i.e., when they are applied to the given input) return an empty output ([]).

References