metanorma-iso 3.5.45 → 3.5.46

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 68d4d7985745cdc876ef1ab8da1d0bc2e3e391a4f9f77715addb58b62ecf2a5e
4
- data.tar.gz: 8cd58295fc5834b7a2c614c0a4b8503d65a215733b6d75de4c8c3ef28a76ceab
3
+ metadata.gz: cf78c30be6277e0ce4617f3c595d9f384ad6608791b6e932b6fdb8ca131f9eed
4
+ data.tar.gz: 37a36b75e451d11ed9979b8f65248e967628c3f2c96ca51e1bd116fe53645d60
5
5
  SHA512:
6
- metadata.gz: e007c1d7110b5d1fc609793d09dfaba60f769bed723f6ce8a5a78e37b87280a038567ba904ce0371f1fe98922f3b4c2ff70003d91394e7151025166b9ac9c1c0
7
- data.tar.gz: 2619cc1eafae85dd5d3149d90a46ffe6f0dff2ae37421cfce1cb720fdde62ca2f97b1b085248de48f701dd2c3f7840cc17717c5cf2dd730e19cd25322b071519
6
+ metadata.gz: '09f54138e874d23a49148a4094d0fd6f5fcfeec2fa41ff563d940ed3c5e8955e086b3583dbae4991ba717101e3fb54ad11f68e5b3bd9cedfe0e5092d8e4b7c48'
7
+ data.tar.gz: 81cd7a05bc855de03810b143f0d9ededd4f151bae0b4f9313beb02cdc26644f5a8aec8d9f8342c4120351cd10adef9bbafbb23a58c7c31fcf8d5c50ec95f35c0
@@ -0,0 +1,164 @@
1
+ # frozen_string_literal: true
2
+
3
+ module IsoDoc
4
+ module Iso
5
+ module Docx
6
+ class Importer
7
+ # Maps the OSD cover, titles and foreword onto the ISO document model.
8
+ class FrontMatter
9
+ Document = Metanorma::Iso::Document
10
+ Metadata = Document::Metadata
11
+ Relaton = Metanorma::Document::Relaton
12
+ Inline = Metanorma::Document::Components::Inline
13
+ Paragraph = Metanorma::Document::Components::Paragraphs::ParagraphBlock
14
+
15
+ TITLE_TYPES = [
16
+ ["intro", "title-intro", Metadata::TitleIntro, :title_intro],
17
+ ["main", "title-main", Metadata::TitleMain, :title_main],
18
+ ["compl", "title-part", Metadata::TitlePart, :title_part],
19
+ ["full", "main", Metadata::TitleFull, :title_full],
20
+ ].freeze
21
+
22
+ LANGUAGE_SUFFIX = /\(([a-z]{2,3}|[efr])\)\z/i
23
+ LEGACY_LANGUAGES = { "e" => "en", "f" => "fr", "r" => "ru" }.freeze
24
+ EDITION_ORDINALS = {
25
+ "en" => %w[first second third fourth fifth sixth seventh eighth ninth tenth],
26
+ "fr" => %w[première deuxième troisième quatrième cinquième sixième septième huitième neuvième dixième],
27
+ }.freeze
28
+
29
+ FRONT_STYLES = %i[
30
+ cover_large cover_meta cover_title cover_subtitle main_title1 main_title2
31
+ foreword foreword_text
32
+ ].freeze
33
+
34
+ def initialize(reader)
35
+ @reader = reader
36
+ @paragraphs = Hash.new { |styles, style| styles[style] = [] }
37
+ mapping = DocxStyleMapping.new(template: :dis)
38
+ styles = FRONT_STYLES.to_h { |key| [mapping.paragraph_style(key), key] }
39
+ reader.each_paragraph do |style, text|
40
+ key = styles[style]
41
+ @paragraphs[key] << text if key
42
+ end
43
+ end
44
+
45
+ def build
46
+ Document::Root.new(bibdata: bibliography, preface: preface)
47
+ end
48
+
49
+ private
50
+
51
+ def bibliography
52
+ Metadata::IsoBibliographicItem.new(
53
+ type: "standard", doc_identifier: identifiers,
54
+ language: [Metadata::LanguageElement.new(value: language)],
55
+ edition: editions, date: dates, version: version
56
+ ).tap { |bibdata| assign_titles(bibdata) }
57
+ end
58
+
59
+ def identifiers
60
+ reference = cover_reference&.sub(LANGUAGE_SUFFIX, "")&.rstrip
61
+ return [] if reference.to_s.empty?
62
+
63
+ [Metadata::DocIdentifier.new(type: "ISO", primary: true,
64
+ value: reference)]
65
+ end
66
+
67
+ def cover_reference
68
+ @paragraphs[:cover_large].first
69
+ end
70
+
71
+ def language
72
+ code = cover_reference.to_s[LANGUAGE_SUFFIX, 1]&.downcase || "en"
73
+ LEGACY_LANGUAGES.fetch(code, code)
74
+ end
75
+
76
+ def editions
77
+ text = @paragraphs[:cover_meta].find { |line| /\b[ée]dition\b/i.match?(line) }
78
+ return [] unless text
79
+
80
+ number = edition_number(text)
81
+ localized = Relaton::Edition.new(content: text, language: language)
82
+ return [localized] unless number
83
+
84
+ [Relaton::Edition.new(content: number.to_s), localized]
85
+ end
86
+
87
+ def edition_number(text)
88
+ digits = text[/\d+/]
89
+ return digits.to_i if digits
90
+
91
+ word = text.downcase[/\A[[:alpha:]]+/]
92
+ return 2 if language == "fr" && word == "seconde"
93
+
94
+ index = EDITION_ORDINALS.fetch(language, []).index(word)
95
+ index + 1 if index
96
+ end
97
+
98
+ def dates
99
+ published = @paragraphs[:cover_meta].find { |line| /\A\d{4}-\d{2}(?:-\d{2})?\z/.match?(line) }
100
+ core = @reader.core
101
+ [
102
+ date("published", published),
103
+ date("created", core&.created&.value),
104
+ date("updated", core&.modified&.value),
105
+ ].compact
106
+ end
107
+
108
+ def date(type, value)
109
+ return if value.to_s.empty?
110
+
111
+ Relaton::BibliographicDate.new(type: type, on: Relaton::DateTime.new(content: value.to_s))
112
+ end
113
+
114
+ def version
115
+ revision = @paragraphs[:cover_meta].filter_map { |line| line[/\ADate:\s*(\d{4}-\d{2}-\d{2})\z/i, 1] }.first
116
+ Relaton::VersionInfo.new(revision_date: revision) if revision
117
+ end
118
+
119
+ def assign_titles(bibdata)
120
+ localized = Metadata::IsoLocalizedTitle.new(language: language)
121
+ items = TITLE_TYPES.zip(cover_titles).filter_map do |(name, type, klass, slot), fallback|
122
+ title = build_title(name, type, klass, fallback)
123
+ localized.public_send("#{slot}=", title) if title
124
+ title
125
+ end
126
+ bibdata.titles = items
127
+ bibdata.titles.per_language = [localized] unless items.empty?
128
+ end
129
+
130
+ def build_title(name, type, klass, fallback)
131
+ text = @reader.custom_title(name)
132
+ text = fallback.to_s if text.empty?
133
+ klass.new(_type: type, language: language, value: text) unless text.empty?
134
+ end
135
+
136
+ def cover_titles
137
+ main = @paragraphs[:main_title1].first || @paragraphs[:cover_title].first
138
+ part = @paragraphs[:main_title2].first || @paragraphs[:cover_subtitle].first
139
+ intro, main, inline_part = split_main_title(main)
140
+ part = (part || inline_part)&.sub(/\APart(?:ie)?[[:space:]]+\S+?:[[:space:]]*/i, "")
141
+ full = [intro, main, part].compact.join(" — ")
142
+ full = @reader.core&.title.to_s.strip if full.empty?
143
+ [intro, main, part, full]
144
+ end
145
+
146
+ def split_main_title(text)
147
+ parts = text.to_s.split("—", 3).map(&:strip).reject(&:empty?)
148
+ parts.size > 1 ? parts : [nil, parts.first]
149
+ end
150
+
151
+ def preface
152
+ heading = @paragraphs[:foreword].first
153
+ paragraphs = @paragraphs[:foreword_text].map { |text| Paragraph.new(text: [text]) }
154
+ return if heading.nil? && paragraphs.empty?
155
+
156
+ title = Inline::TitleWithAnnotationElement.new(text: [heading]) if heading
157
+ foreword = Document::Sections::IsoForewordSection.new(title: title, paragraphs: paragraphs)
158
+ Document::Sections::IsoPreface.new(foreword: foreword)
159
+ end
160
+ end
161
+ end
162
+ end
163
+ end
164
+ end
@@ -0,0 +1,144 @@
1
+ # frozen_string_literal: true
2
+
3
+ module IsoDoc
4
+ module Iso
5
+ module Docx
6
+ class Importer
7
+ # Exposes typed properties and text from top-level styled paragraphs.
8
+ class Reader
9
+ IGNORED_FIELDS = %w[TOC PAGEREF REF].freeze
10
+
11
+ Word = Uniword::Wordprocessingml
12
+ Ooxml = Uniword::Ooxml
13
+ WordNamespace = Ooxml::Namespaces::WordProcessingML
14
+
15
+ # Teach Lutaml about inline smart tags without changing Uniword's
16
+ # shared paragraph mapping. Their contents use the same run mapping.
17
+ class Paragraph < Word::Paragraph
18
+ attribute :smart_tags, self, collection: true, initialize_empty: true
19
+
20
+ xml do
21
+ map_element "smartTag", to: :smart_tags
22
+ end
23
+ end
24
+
25
+ class Body < Lutaml::Model::Serializable
26
+ attribute :paragraphs, Paragraph, collection: true, initialize_empty: true
27
+
28
+ xml do
29
+ element "body"
30
+ namespace WordNamespace
31
+ map_element "p", to: :paragraphs
32
+ end
33
+ end
34
+
35
+ class DocumentPart < Lutaml::Model::Serializable
36
+ attribute :body, Body
37
+
38
+ xml do
39
+ element "document"
40
+ namespace WordNamespace
41
+ map_element "body", to: :body
42
+ end
43
+ end
44
+
45
+ attr_reader :core
46
+
47
+ def initialize(path)
48
+ parts = Uniword::Infrastructure::ZipExtractor.new.extract(path)
49
+ @core = read_part(parts, :core_properties)
50
+ @custom_properties = read_part(parts, :custom_properties)
51
+ @body = document_body(parts)
52
+ @fields = []
53
+ end
54
+
55
+ def custom_title(name)
56
+ property = @custom_properties&.properties&.find do |item|
57
+ item.name == name
58
+ end
59
+ property&.value.to_s.strip
60
+ end
61
+
62
+ def each_paragraph
63
+ # The body mapping only reads top-level paragraphs, so it skips
64
+ # TOC galleries while retaining content controls within paragraphs.
65
+ Array(@body&.paragraphs).each do |paragraph|
66
+ text = paragraph_text(paragraph).strip
67
+ yield paragraph.style&.value, text unless text.empty?
68
+ end
69
+ end
70
+
71
+ private
72
+
73
+ def read_part(parts, key)
74
+ definition = Ooxml::PartRegistry.find_by_key(key)
75
+ xml = parts[definition.path]
76
+ definition.loader_model.from_xml(xml) if xml
77
+ end
78
+
79
+ def document_body(parts)
80
+ definition = Ooxml::PartRegistry.find_by_key(:document)
81
+ relationships = read_part(parts, :package_rels)&.relationships
82
+ relationship = relationships&.find { |rel| rel.type.to_s.include?(definition.rel_type) }
83
+ xml = parts[relationship&.target&.delete_prefix("/")] || parts[definition.path]
84
+ DocumentPart.from_xml(xml).body if xml
85
+ end
86
+
87
+ def paragraph_text(paragraph)
88
+ ordered_text(paragraph, "fldSimple" => paragraph.simple_fields,
89
+ "smartTag" => paragraph.smart_tags)
90
+ end
91
+
92
+ def ordered_text(container, extra = {})
93
+ elements = {
94
+ "r" => container.runs, "hyperlink" => container.hyperlinks,
95
+ "sdt" => container.sdts
96
+ }.merge(extra).transform_values(&:dup)
97
+ container.element_order.filter_map do |entry|
98
+ element = elements[entry.name]&.shift
99
+ read_element(element) if element
100
+ end.join
101
+ end
102
+
103
+ def read_element(element)
104
+ case element
105
+ when Word::Run then read_run(element)
106
+ when Paragraph then paragraph_text(element)
107
+ when Word::StructuredDocumentTag then ordered_text(element.content) if element.content
108
+ when Word::SimpleField
109
+ read_runs(element.runs) unless ignored_field?(element.instr)
110
+ else read_runs(element.runs)
111
+ end
112
+ end
113
+
114
+ def read_runs(runs)
115
+ runs.map { |run| read_run(run) }.join
116
+ end
117
+
118
+ def read_run(run)
119
+ case run.field_char&.fldCharType
120
+ when "begin" then @fields.push(+"")
121
+ when "end" then @fields.pop
122
+ else
123
+ return run_content(run)
124
+ end
125
+ nil
126
+ end
127
+
128
+ def run_content(run)
129
+ if run.instr_text
130
+ @fields.last&.concat(run.instr_text.to_s)
131
+ return
132
+ end
133
+
134
+ run.text_string unless @fields.any? { |instruction| ignored_field?(instruction) }
135
+ end
136
+
137
+ def ignored_field?(instruction)
138
+ IGNORED_FIELDS.include?(instruction.to_s.split.first&.upcase)
139
+ end
140
+ end
141
+ end
142
+ end
143
+ end
144
+ end
@@ -0,0 +1,20 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "uniword"
4
+ require "metanorma/iso/document"
5
+
6
+ module IsoDoc
7
+ module Iso
8
+ module Docx
9
+ # Reads the front matter of a classic ISO OSD DOCX into the ISO model.
10
+ class Importer
11
+ autoload :Reader, "isodoc/iso/docx/importer/reader"
12
+ autoload :FrontMatter, "isodoc/iso/docx/importer/front_matter"
13
+
14
+ def import(path)
15
+ FrontMatter.new(Reader.new(path)).build
16
+ end
17
+ end
18
+ end
19
+ end
20
+ end
@@ -33,6 +33,7 @@ module IsoDoc
33
33
  autoload :DocumentProperties, "isodoc/iso/docx/document_properties"
34
34
  autoload :FormulaRenderer, "isodoc/iso/docx/formula_renderer"
35
35
  autoload :HeaderFooterRenderer, "isodoc/iso/docx/header_footer_renderer"
36
+ autoload :Importer, "isodoc/iso/docx/importer"
36
37
  autoload :IndexsectRenderer, "isodoc/iso/docx/indexsect_renderer"
37
38
  autoload :InlineRenderers, "isodoc/iso/docx/inline_renderers"
38
39
  autoload :InlineRenderer, "isodoc/iso/docx/inline"
@@ -11,9 +11,10 @@ module Metanorma
11
11
  #
12
12
  # Conservative by construction: "assure/assures/assured" is
13
13
  # flagged only when its object is a thing — a "that" clause, a
14
- # closed list of data/quality nouns, or an article plus a word
15
- # outside the person-word list. "Assure the user" and friends
16
- # pass.
14
+ # closed list of data/quality nouns, or an article plus a noun
15
+ # that is not a person reference (person reference is derived:
16
+ # agentive suffix or the closed irregular residue, see below).
17
+ # "Assure the user", "assure the investigator" and friends pass.
17
18
  class StyleAssureEnsureRule < StyleRule
18
19
  code "ISO_71"
19
20
 
@@ -25,22 +26,56 @@ module Metanorma
25
26
 
26
27
  ASSURE_THAT_REGEX = /\bassure[ds]?\s+that\b/i.freeze
27
28
 
28
- ASSURE_OBJECT_REGEX = /\bassure[ds]?\s+(?:the|a|an)\s+([a-z]+)\b/i.freeze
29
+ ASSURE_OBJECT_REGEX =
30
+ /\bassure[ds]?\s+(?:the|a|an)\s+([a-z]+)(?:\s+([a-z]+))?\b/i.freeze
29
31
 
30
32
  ASSURED_NOUN_REGEX =
31
33
  %r{\bassured\s+(?:data|quality|accuracy|results?|performance|values?|operation|compliance)\b}i.freeze
32
34
 
33
- # People: "assure" with a person as its object is correct.
34
- PERSON_WORDS = %w[
35
- user users reader readers customer customers client clients
36
- person persons people operator operators installer installers
37
- manufacturer manufacturers supplier suppliers purchaser
38
- purchasers buyer buyers owner owners everyone anyone somebody
39
- staff personnel team committees committee member members
40
- delegate delegates authority authorities regulator regulators
41
- public consumer consumers subscriber subscribers
35
+ # Person reference is derived, not enumerated (metanorma-iso#1963):
36
+ # a noun denotes a person when it carries a productive agentive
37
+ # suffix of English, or is in the closed residue of person nouns
38
+ # built without one. The suffix class covers every agent noun
39
+ # the hand list missed ("assure the investigator/engineer/
40
+ # technician/pilot", which the list flagged as things).
41
+ #
42
+ # -er/-or user, reader, owner, investigator, operator
43
+ # -ist scientist, specialist, cyclist
44
+ # -ian technician, librarian, physician
45
+ # -ant/-ent applicant, assistant, client, student, president
46
+ # (the -ment nominals are things, never persons)
47
+ # -ee employee, trainee, nominee, referee
48
+ # -eer engineer, volunteer, pioneer
49
+ # -eur amateur, entrepreneur, connoisseur
50
+ # -man/-woman/-person chairman, spokeswoman, contact person
51
+ AGENTIVE_SUFFIX_REGEX =
52
+ /\A(?:\w+(?:er|or|ist|ian|ant|(?<!m)ent|ee|eer|eur|man|woman|person))\z/i.freeze
53
+
54
+ # Suffixed nouns that are not persons.
55
+ NON_PERSON_SUFFIXED_NOUNS = %w[
56
+ guarantee settee rupee goatee tee fee tree spree melee jubilee
57
+ matinee liqueur grandeur
58
+ ].freeze
59
+
60
+ # Person nouns without an agentive suffix: pronouns, collective
61
+ # and irregular nouns. Closed residue; the agentive class above
62
+ # carries the productive part.
63
+ IRREGULAR_PERSON_NOUNS = %w[
64
+ people person public staff personnel team crew board panel party
65
+ audience readership membership workforce community population
66
+ family household victim witness pilot child children baby adult
67
+ human individual expert consumer colleague peer partner friend
68
+ member delegate candidate advocate graduate representative
69
+ executive authority government agency society association
70
+ everyone anyone somebody someone nobody everybody
42
71
  ].freeze
43
72
 
73
+ # The one noun-modifier position the object may carry: a
74
+ # participle or adjective ("the investigating officer", "the
75
+ # responsible authority"). Any other first word is the head.
76
+ MODIFIER_SUFFIX_REGEX =
77
+ /\A\w+(?:ing|ed|ive|al|ous|ic|able|ible|ful|less|ary)\z/i.freeze
78
+
44
79
  # Strip the duplicated json_* text copies so each paragraph
45
80
  # contributes its prose exactly once.
46
81
  def prose_exclusions
@@ -59,21 +94,41 @@ module Metanorma
59
94
 
60
95
  private
61
96
 
62
- # "assure(s|d) the|a|an X": flag unless X is a person word.
97
+ # "assure(s|d) the|a|an [modifier] X": flag unless the object is
98
+ # a person reference.
63
99
  def findings_for_inanimate_objects(node, text)
64
- text.scan(ASSURE_OBJECT_REGEX).filter_map do |(word)|
65
- next if PERSON_WORDS.include?(word.downcase)
100
+ text.to_enum(:scan, ASSURE_OBJECT_REGEX).filter_map do
101
+ match = Regexp.last_match
102
+ next if person_object?(match[1], match[2])
66
103
 
67
104
  build_warning(
68
105
  node,
69
106
  "style: 'assure' with a thing as its object " \
70
- "'#{match_text(text, word)}' (use 'ensure')"
107
+ "'#{match[0]}' (use 'ensure')"
71
108
  )
72
109
  end
73
110
  end
74
111
 
75
- def match_text(text, word)
76
- text.match(/assure[ds]?\s+(?:the|a|an)\s+#{word}\b/i).to_s
112
+ # The first word is the head noun unless it is a modifier
113
+ # shape and the second word is the person head.
114
+ def person_object?(first, second)
115
+ return true if person_noun?(first)
116
+ return false if second.nil?
117
+
118
+ first.match?(MODIFIER_SUFFIX_REGEX) && person_noun?(second)
119
+ end
120
+
121
+ # A plural object noun ("assure the users") is the same
122
+ # reference as its singular.
123
+ def person_noun?(word)
124
+ singular = word.downcase
125
+ candidates = [singular, singular.sub(/ies\z/, "y"),
126
+ singular.sub(/es\z/, ""), singular.sub(/s\z/, "")]
127
+ return false if (candidates & NON_PERSON_SUFFIXED_NOUNS).any?
128
+
129
+ candidates.any? do |candidate|
130
+ candidate.match?(AGENTIVE_SUFFIX_REGEX) || IRREGULAR_PERSON_NOUNS.include?(candidate)
131
+ end
77
132
  end
78
133
  end
79
134
  end
@@ -25,10 +25,10 @@ module Metanorma
25
25
  # list and bare digits (citation callouts) pass;
26
26
  # - "(see Table 3)": content that is not exactly value+unit.
27
27
  #
28
- # Units are detected against closed token lists, anchored to a
29
- # preceding number so that ordinary words never read as units
30
- # ("in the range", "A 5 m rope"). Symbol units match
31
- # case-sensitively ("5 KN" is kilonewtons, not knots); word
28
+ # Units are detected against the Unitsdb registry (UnitTokens),
29
+ # anchored to a preceding number so that ordinary words never
30
+ # read as units ("in the range", "A 5 m rope"). Symbol units
31
+ # match case-sensitively ("5 KN" is kilonewtons, not knots); word
32
32
  # units match case-insensitively.
33
33
  class StyleNonSiOrderRule < StyleRule
34
34
  code "ISO_146"
@@ -38,40 +38,41 @@ module Metanorma
38
38
  "value follows in parentheses: 5,6 km (3,5 miles)",
39
39
  source: :house_style, mn_category: :style
40
40
 
41
- # Common non-SI units: closed lists. Symbol entries are
42
- # case-sensitive, word entries case-insensitive.
43
- NON_SI_SYMBOL_UNITS = [
44
- "°F", "mph", "psi", "hp", "kcal", "cal", "knots", "knot",
45
- "kn", "lbs", "lb", "oz", "yd", "mi", "in", "ft", "bar",
46
- "miles", "mile",
47
- ].freeze
48
- NON_SI_WORD_UNITS = ["miles per hour", "mile per hour"].freeze
41
+ def self.alternation(tokens)
42
+ tokens.sort_by { |token| -token.length }
43
+ .map { |token| Regexp.escape(token) }.join("|")
44
+ end
49
45
 
50
- # SI (and SI-derived) units: a preceding value carrying one of
51
- # these means the statement already has its SI value. Closed
52
- # list; case-sensitive.
53
- SI_SYMBOL_UNITS = [
54
- "GPa", "MPa", "kPa", "Pa", "MN", "kN", "N", "MJ", "kJ", "J",
55
- "GW", "MW", "kW", "W", "MHz", "kHz", "Hz", "kV", "mV", "V",
56
- "km/h", "m/s", "km", "cm", "mm", "nm", "kg", "mg", "g",
57
- "mol", "ohm", "cd", "ms", "s", "m", "A", "K",
58
- ].freeze
46
+ # The flagged set is the Unitsdb registry's (metanorma-iso#1963):
47
+ # every unit the registry records as non-SI and not acceptable
48
+ # for use with the SI, plus the temporarily acceptable band
49
+ # (UnitTokens::SI_TWIN_EXPECTED). The hand lists this replaces
50
+ # misclassified "25 °C (77 °F)" because °C was absent from
51
+ # them. Symbol entries are case-sensitive, word entries
52
+ # (English names and their plurals) case-insensitive.
53
+ #
54
+ # Single ASCII-letter symbols are not flagged values: "(3 a)"
55
+ # reads as a reference far more often than as an are or a year.
56
+ NON_SI_SYMBOL_PATTERN = alternation(UnitTokens.non_si_symbols.grep_v(/\A[A-Za-z]\z/))
57
+ NON_SI_WORD_PATTERN = alternation(UnitTokens.non_si_words)
59
58
 
60
- NON_SI_SYMBOL_PATTERN = NON_SI_SYMBOL_UNITS
61
- .sort_by { |u| -u.length }.map { |u| Regexp.escape(u) }.join("|")
62
- .freeze
63
- NON_SI_WORD_PATTERN = NON_SI_WORD_UNITS
64
- .sort_by { |u| -u.length }.map { |u| Regexp.escape(u) }.join("|")
65
- .freeze
66
- SI_SYMBOL_PATTERN = SI_SYMBOL_UNITS
67
- .sort_by { |u| -u.length }.map { |u| Regexp.escape(u) }.join("|")
68
- .freeze
59
+ # A preceding value in an SI unit — the SI prefixes compose with
60
+ # the SI symbols exactly as the Brochure defines them ("336 kW",
61
+ # "300 kPa") — or in a unit accepted for use with the SI (min,
62
+ # L, dB, ...) means the statement already has its primary
63
+ # value.
64
+ SI_PREFIX_PATTERN = alternation(UnitTokens.si_prefix_symbols)
65
+ SI_SYMBOL_PATTERN = alternation(UnitTokens.si_symbols)
66
+ ACCEPTED_SYMBOL_PATTERN = alternation(UnitTokens.accepted_symbols)
67
+ SI_CARRIER_PATTERN =
68
+ /(?:#{SI_PREFIX_PATTERN})?(?:#{SI_SYMBOL_PATTERN})(?![A-Za-z])/.freeze
69
69
 
70
70
  # A parenthetical whose content is exactly a value and a
71
- # non-SI unit (word forms case-insensitive).
71
+ # non-SI unit (word forms case-insensitive; an abbreviation
72
+ # symbol may carry its "s" plural, "5 lbs").
72
73
  PAREN_REGEX = /\(([^()]{1,80})\)/.freeze
73
74
  VALUE_UNIT_REGEX =
74
- /\A\s*\d+(?:[.,]\d+)?\s+(?:#{NON_SI_SYMBOL_PATTERN})\s*\z/.freeze
75
+ /\A\s*\d+(?:[.,]\d+)?\s+(?:#{NON_SI_SYMBOL_PATTERN})s?\s*\z/.freeze
75
76
  VALUE_UNIT_WORD_REGEX =
76
77
  /\A\s*\d+(?:[.,]\d+)?\s+(?:#{NON_SI_WORD_PATTERN})\s*\z/i.freeze
77
78
 
@@ -100,12 +101,14 @@ module Metanorma
100
101
  content.match?(VALUE_UNIT_WORD_REGEX)
101
102
  end
102
103
 
103
- # SI and non-SI alike anchored to a preceding number: a bare
104
- # word never reads as a unit ("in the range"). Case-sensitive
105
- # on symbol units; word forms match case-insensitively.
104
+ # SI (optionally prefixed), accepted-with-SI and non-SI units
105
+ # alike anchored to a preceding number: a bare word never reads
106
+ # as a unit ("in the range"). Case-sensitive on symbol units;
107
+ # word forms match case-insensitively.
106
108
  def unit_carrier?(window)
107
109
  number = /\d(?:[\d.,]*\d)?\s*/
108
- window.match?(/#{number}(?:#{SI_SYMBOL_PATTERN})(?![A-Za-z])/) ||
110
+ window.match?(/#{number}#{SI_CARRIER_PATTERN}/) ||
111
+ window.match?(/#{number}(?:#{ACCEPTED_SYMBOL_PATTERN})(?![A-Za-z])/) ||
109
112
  window.match?(
110
113
  /#{number}(?:#{NON_SI_SYMBOL_PATTERN})(?![A-Za-z])/
111
114
  ) ||
@@ -45,19 +45,33 @@ module Metanorma
45
45
  "style: digit '%s' in prose (write the numbers one to " \
46
46
  "nine as words)".freeze
47
47
 
48
- # Unit tokens that license a digit, symbol-spaced or not.
49
- # "in" (inch) is deliberately absent: it reads as the English
50
- # word in prose ("3 in total") and its flag risk outweighs
51
- # the exemption value.
52
- UNIT_TOKENS = %w[
53
- % µm mm cm dm m km ft yd s ms µs ns min h d t kHz MHz
54
- GHz THz Hz kPa MPa GPa Pa mbar bar mol mL ml l L g kg mg
55
- µg °C N kN MN A mA V mV W mW kW J kJ
56
- ].freeze
57
-
58
- UNIT_GROUP = UNIT_TOKENS.map { |u| Regexp.escape(u) }.join("|").freeze
59
-
60
- UNIT_FOLLOW_REGEX = /\A\s?(?:#{UNIT_GROUP})(?![a-z])/i.freeze
48
+ # Unit tokens that license a digit, symbol-spaced or not: the
49
+ # Unitsdb-derived symbol set (every unit the registry knows,
50
+ # SI and non-SI alike), with the SI prefixes composing freely
51
+ # as the Brochure defines them ("3 kV", "3 MW", "3 µg"). The
52
+ # table is built once at autoload, like the currency rules'.
53
+ # UnitTokens (metanorma-iso#1963) replaces the hand list that
54
+ # flagged "3 MW" and "300 K" as style errors.
55
+ UNIT_GROUP = UnitTokens.all_symbols.map { |u| Regexp.escape(u) }
56
+ .sort_by(&:length).reverse.join("|").freeze
57
+
58
+ SI_PREFIX_GROUP = UnitTokens.si_prefix_symbols
59
+ .sort_by(&:length).reverse.join("|").freeze
60
+
61
+ # Registry symbols that read as English words in prose ("3 in
62
+ # total", "3 at a time", "divided into 3 as shown"): their
63
+ # flag risk outweighs the exemption value, so they never
64
+ # license a digit here. This holds for the prefixed grammar
65
+ # too (atto + tesla).
66
+ ENGLISH_HOMOGRAPH_UNITS = %w[in at as].freeze
67
+
68
+ # Only the bare homograph is excluded; a registry symbol that
69
+ # merely starts with it ("in/s", "in⁴") still licenses.
70
+ ENGLISH_HOMOGRAPH_GROUP = ENGLISH_HOMOGRAPH_UNITS
71
+ .map { |u| "#{u}(?:\\s|$)" }.join("|").freeze
72
+
73
+ UNIT_FOLLOW_REGEX =
74
+ /\A\s?(?!#{ENGLISH_HOMOGRAPH_GROUP})(?:#{SI_PREFIX_GROUP})?(?:#{UNIT_GROUP})(?![a-z])/i.freeze
61
75
 
62
76
  MONTHS = %w[
63
77
  january february march april may june july august september
@@ -0,0 +1,225 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "unitsdb"
4
+
5
+ module Metanorma
6
+ module Iso
7
+ module Validation
8
+ # Unitsdb-derived unit token tables, shared by the unit-aware style
9
+ # rules: ISO_121 (a digit licensed by a following unit), ISO_88
10
+ # (range units) and ISO_146 (SI/non-SI ordering). The registry is
11
+ # the Unitsdb database (NIST SP 811 / UnitsML). It loads once per
12
+ # process here, at autoload, never per scanned paragraph.
13
+ #
14
+ # The SI/non-SI split is the registry's own: a unit belongs to a
15
+ # unit system (SI base, SI derived, non-SI acceptable, non-SI not
16
+ # acceptable), and the SI prefixes combine with SI units exactly as
17
+ # the Brochure defines them (prefix symbol + unit symbol).
18
+ #
19
+ # Every presentation Unitsdb records for a symbol counts as a token
20
+ # (unicode "°C", ASCII "degC"). UnitsML product forms keep the two
21
+ # spellings ISO 80000 prints: the middle-dot form ("N·m", "m/s")
22
+ # and the compact form ("Nm", "kWh").
23
+ module UnitTokens
24
+ SI_SYSTEMS = %w[
25
+ si-base SI_compatible SI_derived_non-special SI_derived_special
26
+ ].freeze
27
+ ACCEPTED_NON_SI_SYSTEM = "non-SI_acceptable".freeze
28
+ NON_SI_SYSTEMS = %w[non-SI_nist_acceptable non-SI_not_acceptable].freeze
29
+
30
+ # Unitsdb folds NIST SP 811 Table 9 ("units temporarily
31
+ # acceptable": nautical mile, knot, ångström, bar, millimetre of
32
+ # mercury) into its single "non-SI but acceptable" tier. ISO
33
+ # House Style still expects the SI value ahead of these
34
+ # (15 m/s (30 kn), 300 kPa (3 bar)), so ISO_146 keeps them on
35
+ # the flagged side.
36
+ SI_TWIN_EXPECTED = %w[nautical_mile knot angstrom bar mm_Hg].freeze
37
+
38
+ # Quantities that carry no SI equivalent: information units (bit,
39
+ # byte, baud) are non-SI in the registry but are never "non-SI
40
+ # values" in the ISO_146 sense.
41
+ NO_SI_EQUIVALENT_QUANTITIES = %w[storage_capacity symbol_rate].freeze
42
+
43
+ # Registry gaps: Unitsdb records only the UnitsML form "mi*h^-1"
44
+ # for mile per hour (no "mph") and only the qualified forms
45
+ # "kcal_IT"/"kcal_th" for the kilogram-calorie (no "kcal"). Both
46
+ # are ISO prose symbols the registry cannot supply today.
47
+ REGISTRY_GAPS = %w[mph kcal].freeze
48
+
49
+ BINARY_PREFIXES = %w[kibi mebi gibi tebi pebi exbi zebi yobi].freeze
50
+ UNITY_PREFIX = "none".freeze
51
+
52
+ # Unitsdb prints the micro prefix as U+03BC (Greek mu); ISO 80000
53
+ # also prints U+00B5 (micro sign). Both forms apply.
54
+ MICRO_PREFIXES = ["μ", "µ"].freeze
55
+
56
+ SUPERSCRIPT_DIGITS = { "1" => "¹", "2" => "²", "3" => "³" }.freeze
57
+
58
+ # UnitsML slug internals and punctuation never read as a unit in
59
+ # prose ("ft_US_survey", "'_s").
60
+ SLUG_REGEX = /[_"',;<>=~|\\]/.freeze
61
+
62
+ module_function
63
+
64
+ def database
65
+ Unitsdb.database
66
+ end
67
+
68
+ # Units whose unit-system membership includes any of the systems.
69
+ def units_in_systems(*systems)
70
+ database.units.select do |unit|
71
+ system_slugs(unit).any? { |slug| systems.include?(slug) }
72
+ end
73
+ end
74
+
75
+ def system_slugs(unit)
76
+ unit.unit_system_reference.to_a.filter_map(&:id)
77
+ end
78
+
79
+ def english_names(unit)
80
+ unit.names.to_a.filter_map do |name|
81
+ value = name.value
82
+ value if value && name.lang.to_s.downcase.start_with?("en")
83
+ end
84
+ end
85
+
86
+ def quantity_slugs(unit)
87
+ unit.quantity_references.to_a.filter_map { |ref| quantity_slug_by_id[ref.id] }
88
+ end
89
+
90
+ def quantity_slug_by_id
91
+ @quantity_slug_by_id ||= database.quantities.flat_map do |quantity|
92
+ quantity.identifiers.to_a.map { |identifier| [identifier.id, quantity.short] }
93
+ end.to_h.freeze
94
+ end
95
+
96
+ # SI prefix symbols, binary prefixes and the unity prefix
97
+ # excluded; the micro prefix in both its printed forms.
98
+ def si_prefix_symbols
99
+ @si_prefix_symbols ||= begin
100
+ symbols = database.prefixes.reject do |prefix|
101
+ BINARY_PREFIXES.include?(prefix.short) || prefix.short == UNITY_PREFIX
102
+ end.flat_map do |prefix|
103
+ prefix.symbols.to_a.flat_map { |symbol| [symbol.unicode, symbol.ascii] }
104
+ end.compact.uniq
105
+ (symbols + MICRO_PREFIXES).uniq.freeze
106
+ end
107
+ end
108
+
109
+ # Every prose spelling of a unit's symbols. UnitsML expression
110
+ # forms ("m*s^-1", "N*m^2*kg^-2") contribute only their prose
111
+ # forms; the expressions themselves never occur in text.
112
+ def symbols(unit)
113
+ unit.symbols.to_a.flat_map do |symbol|
114
+ [symbol.unicode, symbol.ascii, decode_entities(symbol.html)]
115
+ end.compact.map(&:strip).reject(&:empty?)
116
+ .reject { |sym| sym.match?(SLUG_REGEX) || sym.match?(/\A\d+\z/) }
117
+ .flat_map { |sym| sym.match?(/[\^*]/) ? derived_forms(sym) : [sym, *derived_forms(sym)] }
118
+ .reject { |sym| sym.match?(/[\^*_]/) || sym.match?(/\A\d+\z/) }.uniq
119
+ end
120
+
121
+ # Regular English plurals of a unit's English names. The head noun
122
+ # of a compound name sits at either end ("mile per hour",
123
+ # "nautical mile"), so both pluralizations are emitted; the one
124
+ # English does not use never occurs in text. Qualified registry
125
+ # names ("horsepower, electric") are not word forms.
126
+ def word_forms(unit)
127
+ english_names(unit).reject { |name| name.match?(/[(),]/) }.flat_map do |name|
128
+ [name, pluralize(name, 0), pluralize(name, -1)]
129
+ end.uniq
130
+ end
131
+
132
+ # ---- Exported tables (frozen, built once) ----
133
+
134
+ # Symbols of the SI family units, as Unitsdb prints them; the SI
135
+ # prefixes compose with these by rule (see #si_prefixed_pattern).
136
+ def si_symbols
137
+ @si_symbols ||= units_in_systems(*SI_SYSTEMS).flat_map { |unit| symbols(unit) }.uniq.freeze
138
+ end
139
+
140
+ # Symbols of the units accepted for use with the SI (min, L, dB,
141
+ # °, ...): a primary value in one of these needs no SI twin.
142
+ def accepted_symbols
143
+ @accepted_symbols ||= units_in_systems(ACCEPTED_NON_SI_SYSTEM)
144
+ .flat_map { |unit| symbols(unit) }.uniq.freeze
145
+ end
146
+
147
+ # A symbol an SI unit or a non-band accepted unit also carries
148
+ # ("min" is both the minute and the sidereal minute) reads as its
149
+ # accepted sense and is never flagged. The band's own symbols are
150
+ # excluded from the subtraction: the band units are accepted-tier
151
+ # in the registry yet stay flagged.
152
+ def non_si_symbols
153
+ @non_si_symbols ||= ((non_si_units.flat_map { |unit| symbols(unit) } + REGISTRY_GAPS)
154
+ .uniq - si_symbols - accepted_symbols_outside_band).freeze
155
+ end
156
+
157
+ def accepted_symbols_outside_band
158
+ @accepted_symbols_outside_band ||= units_in_systems(ACCEPTED_NON_SI_SYSTEM)
159
+ .reject { |unit| SI_TWIN_EXPECTED.include?(unit.short) }
160
+ .flat_map { |unit| symbols(unit) }.uniq.freeze
161
+ end
162
+
163
+ def non_si_words
164
+ @non_si_words ||= non_si_units.flat_map { |unit| word_forms(unit) }
165
+ .reject { |word| word.match?(/[()]/) }.uniq.freeze
166
+ end
167
+
168
+ # Every unit symbol Unitsdb knows, whatever its class: the set
169
+ # that licenses a digit in ISO_121 and marks a range in ISO_88.
170
+ def all_symbols
171
+ @all_symbols ||= database.units.flat_map { |unit| symbols(unit) }.uniq.freeze
172
+ end
173
+
174
+ # The table ISO_146 flags: non-SI units that are not accepted for
175
+ # use with the SI, plus the temporarily acceptable band, minus the
176
+ # quantities that have no SI equivalent.
177
+ def non_si_units
178
+ units = units_in_systems(*NON_SI_SYSTEMS) + units_in_systems(ACCEPTED_NON_SI_SYSTEM).select do |unit|
179
+ SI_TWIN_EXPECTED.include?(unit.short)
180
+ end
181
+ units.reject { |unit| (quantity_slugs(unit) & NO_SI_EQUIVALENT_QUANTITIES).any? }
182
+ end
183
+
184
+ def decode_entities(html)
185
+ html&.gsub(/&#(\d+);/) { [$1.to_i].pack("U") }
186
+ end
187
+
188
+ # "N·m" -> "Nm", "m*s^-1" -> "m/s", "N*m^2*kg^-2" -> "N·m²/kg²",
189
+ # "m^2" -> "m²".
190
+ def derived_forms(sym)
191
+ forms = []
192
+ compact = sym.delete("·")
193
+ forms << compact if sym.include?("·") && !compact.empty?
194
+ if sym.match?(/\^-\d+\z/) && sym.include?("*")
195
+ numerator, denominator = sym.split("*").partition { |part| part !~ /\^-\d+\z/ }
196
+ quotient = "#{numerator.join('·')}/#{denominator.map { |part| part.sub(/\^-\d+\z/, '') }.join('·')}"
197
+ forms << quotient << quotient.delete("·")
198
+ end
199
+ forms.map! { |form| superscript(form) }
200
+ forms << superscript(sym) if sym.match?(/\^\d/)
201
+ forms.reject { |form| form.match?(/[\^*]/) }.uniq
202
+ end
203
+
204
+ def superscript(form)
205
+ form.gsub(/\^(\d)/) { SUPERSCRIPT_DIGITS[$1] || $1 }
206
+ end
207
+
208
+ def pluralize(name, head_index)
209
+ words = name.split(" ")
210
+ head = words[head_index]
211
+ words[head_index] = irregular_plural(head) || regular_plural(head)
212
+ words.join(" ")
213
+ end
214
+
215
+ def regular_plural(word)
216
+ word.match?(/(s|x|z|ch|sh)\z/i) ? "#{word}es" : "#{word}s"
217
+ end
218
+
219
+ def irregular_plural(word)
220
+ { "foot" => "feet" }[word.downcase]&.then { |plural| word =~ /\A[A-Z]/ ? plural.capitalize : plural }
221
+ end
222
+ end
223
+ end
224
+ end
225
+ end
@@ -27,6 +27,7 @@ module Metanorma
27
27
  autoload :RuleRegistry, "metanorma/iso/validation/rule_registry"
28
28
  autoload :ComposedRegistry, "metanorma/iso/validation/composed_registry"
29
29
  autoload :SentenceScan, "metanorma/iso/validation/sentence_scan"
30
+ autoload :UnitTokens, "metanorma/iso/validation/unit_tokens"
30
31
  autoload :Profile, "metanorma/iso/validation/profile"
31
32
  autoload :StateExtractor, "metanorma/iso/validation/state_extractor"
32
33
  autoload :Rules, "metanorma/iso/validation/rules"
@@ -1,5 +1,5 @@
1
1
  module Metanorma
2
2
  module Iso
3
- VERSION = "3.5.45".freeze
3
+ VERSION = "3.5.46".freeze
4
4
  end
5
5
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: metanorma-iso
3
3
  version: !ruby/object:Gem::Version
4
- version: 3.5.45
4
+ version: 3.5.46
5
5
  platform: ruby
6
6
  authors:
7
7
  - Ribose Inc.
@@ -539,6 +539,9 @@ files:
539
539
  - lib/isodoc/iso/docx/errors.rb
540
540
  - lib/isodoc/iso/docx/formula_renderer.rb
541
541
  - lib/isodoc/iso/docx/header_footer_renderer.rb
542
+ - lib/isodoc/iso/docx/importer.rb
543
+ - lib/isodoc/iso/docx/importer/front_matter.rb
544
+ - lib/isodoc/iso/docx/importer/reader.rb
542
545
  - lib/isodoc/iso/docx/indexsect_renderer.rb
543
546
  - lib/isodoc/iso/docx/inline.rb
544
547
  - lib/isodoc/iso/docx/inline_renderers.rb
@@ -984,6 +987,7 @@ files:
984
987
  - lib/metanorma/iso/validation/sentence_scan.rb
985
988
  - lib/metanorma/iso/validation/shared_state.rb
986
989
  - lib/metanorma/iso/validation/state_extractor.rb
990
+ - lib/metanorma/iso/validation/unit_tokens.rb
987
991
  - lib/metanorma/iso/validation/walk_cache.rb
988
992
  - lib/metanorma/iso/validation_policy/metanorma.yml
989
993
  - lib/metanorma/iso/version.rb