All files / app resources.tsx

96.98% Statements 161/166
89.01% Branches 81/91
97.36% Functions 37/38
100% Lines 160/160

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                                                                                                                                                            20x               20x   20x                           2580432x 735104x 735104x 735104x 756064x 756064x 756064x 588152x   167912x           20x   220x 220x 220x 220x 220x 220x 220x 220x 220x 220x 220x 220x 220x 220x   220x 220x 220x 220x 220x   220x 20x 20x 12x 12x 12x 12x 12x     8x   8x 8x 8x 8x 8x       8x   8x 4307600x 4307600x 4307600x 4307592x 4307296x   296x       8x 8x 8x   8x       220x 20x 20x 12x 12x 12x     8x   8x 8x 8x 8x   8x       220x 20x 20x 12x 12x 12x     8x   8x 8x 8x 8x   8x       220x 20x 20x 12x 12x 12x     8x   8x 8x 8x 8x 8x   8x       220x 20x 20x 12x 12x 12x     8x   8x 8x 8x 860144x 860144x 860144x 860144x 860144x   8x 8x   8x       220x 48x 20x 20x 10768980x 10732320x   10732320x     10732320x 1442300x 1442300x 1442300x 1442300x 404300x 29660x   374640x     1038000x   1442300x       20x     220x 56x 20x 20x 20x 2150360x 2150360x 2075680x 2075680x 2075680x   2075680x           2075680x 2075680x       20x 20x 20x 20x     220x 198x                                                               220x             220x   7x 7x 7x   7x 2x 2x         220x               720x                                        
import {Done, Error} from '@mui/icons-material'
import {CircularProgress, List, ListItem, ListItemIcon, Stack, Typography} from '@mui/material'
import {type ReactNode, createContext, useEffect, useState, useMemo, useCallback} from 'react'
import {newline} from './lib/utils'
import {loadResource, saveResource, setStorage} from './storage'
import type {NumberObject} from './building'
import {decompress} from './lib/compression'
 
type AssociatedIndices = [number | number[], (number | number[])?][]
type ConceptNet = {
  terms: {[index: string]: {[index: string]: number | number[]}}
  links: {[index: string]: string | string[]}
}
export type Synset = {
  id: string
  index: number
  count: number
  definition: string
  topic: string
  ili: string
  sense_index: number
  nltk_id: string
  babelnet: string
  source: string
  wikidata: string
  csi_labels: string | string[]
  members: number | number[]
  attribute: number | number[]
  domain_topic: number | number[]
  similar: number | number[]
  also: number | number[]
  domain_region: number | number[]
  exemplifies: number | number[]
  mero_part: number | number[]
  hypernym: number | number[]
  instance_hypernym: number | number[]
  mero_member: number | number[]
  mero_substance: number | number[]
  entails: number | number[]
  causes: number | number[]
  derivation: number | number[]
  pertainym: number | number[]
  agent: number | number[]
  antonym: number | number[]
  body_part: number | number[]
  by_means_of: number | number[]
  destination: number | number[]
  event: number | number[]
  instrument: number | number[]
  location: number | number[]
  material: number | number[]
  participle: number | number[]
  property: number | number[]
  result: number | number[]
  state: number | number[]
  undergoer: number | number[]
  uses: number | number[]
  vehicle: number | number[]
  hyponym: number[]
  instance_hyponym: number[]
  domain_topic_members: number[]
}
type Synsets = readonly Synset[]
export type CoarseSenseMap = {[index: string]: string[]}
export type RawSenseMap = {header: string[]; selectedCols: string[]; rows: readonly string[][]; NLTKLabels: boolean}
export type SenseMapSetterFun = (
  map: CoarseSenseMap,
  options: {rawMap?: RawSenseMap; store: boolean},
  password?: string,
) => void
export type TermResources = {
  terms?: readonly string[]
  lemmas?: {[index: string]: number | number[]}
  termLookup?: {[index: string]: number}
  collapsedTerms?: {[index: string]: string}
  termAssociations?: AssociatedIndices
  conceptNet?: ConceptNet
  sense_keys?: readonly string[]
  synsetInfo?: Synsets
  senseMap: CoarseSenseMap
  senseMapOptions: {rawMap?: RawSenseMap; store: boolean}
  SenseLookup: NumberObject
  NLTKLookup: NumberObject
  collapsedSenses: string
  collapsedNLTK: string
}
export const ResourceContext = createContext<TermResources>({
  senseMap: {},
  senseMapOptions: {store: true},
  SenseLookup: {},
  NLTKLookup: {},
  collapsedSenses: '',
  collapsedNLTK: '',
})
export const SenseMapSetter = createContext<SenseMapSetterFun>(() => {})
 
const resources = [
  {key: 'terms', label: 'Terms'},
  {key: 'termAssociations', label: 'Term Associations'},
  {key: 'conceptNet', label: 'ConceptNet'},
  {key: 'sense_keys', label: 'Sense Keys'},
  {key: 'synsetInfo', label: 'Synset Info'},
] as const
 
function backLink(
  entry: 'hypernym' | 'instance_hypernym' | 'domain_topic',
  targetEntry: 'hyponym' | 'instance_hyponym' | 'domain_topic_members',
  synset: Synset,
  synsets: Partial<Synset>[],
) {
  if (entry in synset) {
    const sourceEntry = synset[entry]
    const targets = 'number' === typeof sourceEntry ? [sourceEntry] : sourceEntry
    targets.forEach(ti => {
      const target = synsets[ti]
      const out = target[targetEntry]
      if (out) {
        out.push(synset.index + 1)
      } else {
        target[targetEntry] = [synset.index + 1]
      }
    })
  }
}
 
const wordSep = /[\s-]+/g
export function Resources({children}: {children: ReactNode}) {
  const [terms, setTerms] = useState<readonly string[]>()
  const [lemmas, setLemmas] = useState<{[index: string]: number | number[]}>()
  const [termLookup, setTermLookup] = useState<{[index: string]: number}>()
  const [collapsedTerms, setCollapsedTerms] = useState<{[index: string]: string}>()
  const [termAssociations, setTermAssociations] = useState<AssociatedIndices>()
  const [conceptNet, setConceptNet] = useState<ConceptNet>()
  const [sense_keys, setSenseKeys] = useState<readonly string[]>()
  const [synsetInfo, setSynsetInfo] = useState<Synsets>()
  const [senseMap, setSenseMap] = useState<CoarseSenseMap>({})
  const [senseMapOptions, setSenseMapOptions] = useState<{rawMap?: RawSenseMap; store: boolean}>({store: true})
  const [SenseLookup, setSenseLookup] = useState<NumberObject>({})
  const [NLTKLookup, setNLTKLookup] = useState<NumberObject>({})
  const [collapsedSenses, setCollapsedSenses] = useState('')
  const [collapsedNLTK, setCollapsedNLTK] = useState('')
 
  const [loadingTerms, setLoadingTerms] = useState(true)
  const [loadingTermAssociations, setLoadingTermAssociations] = useState(true)
  const [loadingConceptNet, setLoadingConceptNet] = useState(true)
  const [loadingSenseKeys, setLoadingSenseKeys] = useState(true)
  const [loadingSynsetInfo, setLoadingSynsetInfo] = useState(true)
 
  useEffect(() => {
    loadResource('terms').then(res => {
      if (res && res.content) {
        decompress(res.content).then(processedTerms => {
          setTerms(Object.freeze(processedTerms.arr))
          setTermLookup(Object.freeze(processedTerms.obj))
          setCollapsedTerms(Object.freeze(processedTerms.collapsed))
          setLoadingTerms(false)
        })
      } else {
        fetch('/dictionary_builder/data/terms.txt')
          .then(async res => {
            Iif (!res.ok) throw 'failed to fetch terms: ' + res.status + ' (' + res.statusText + ')'
            const data = await res.text()
            const arr = Object.freeze(data.split(newline))
            setTerms(arr)
            const collapsed: {[index: string]: string} = {
              all: ';;' + arr.join(';;') + ';;',
            }
 
            const obj: {[index: string]: number} = {}
 
            arr.forEach((term, index) => {
              obj[term] = index
              const initial = term[0]
              if (initial) {
                if (initial in collapsed) {
                  collapsed[initial] += term + ';;'
                } else {
                  collapsed[initial] = ';;' + term + ';;'
                }
              }
            })
            setTermLookup(Object.freeze(obj))
            setCollapsedTerms(Object.freeze(collapsed))
            saveResource('terms', {arr, obj, collapsed})
          })
          .finally(() => setLoadingTerms(false))
      }
    })
  }, [setLoadingTerms])
  useEffect(() => {
    loadResource('term_associations').then(res => {
      if (res && res.content) {
        decompress(res.content).then(data => {
          setTermAssociations(data)
          setLoadingTermAssociations(false)
        })
      } else {
        fetch('/dictionary_builder/data/term_associations.json')
          .then(async res => {
            Iif (!res.ok) throw 'failed to fetch term associations: ' + res.status + ' (' + res.statusText + ')'
            const data = await res.json()
            setTermAssociations(data)
            saveResource('term_associations', data)
          })
          .finally(() => setLoadingTermAssociations(false))
      }
    })
  }, [setLoadingTermAssociations])
  useEffect(() => {
    loadResource('conceptnet').then(res => {
      if (res && res.content) {
        decompress(res.content).then(data => {
          setConceptNet(data)
          setLoadingConceptNet(false)
        })
      } else {
        fetch('/dictionary_builder/data/conceptnet.json')
          .then(async res => {
            Iif (!res.ok) throw 'failed to fetch ConceptNet: ' + res.status + ' (' + res.statusText + ')'
            const data = await res.json()
            setConceptNet(data)
            saveResource('conceptnet', data)
          })
          .finally(() => setLoadingConceptNet(false))
      }
    })
  }, [setLoadingTermAssociations])
  useEffect(() => {
    loadResource('sense_keys').then(res => {
      if (res && res.content) {
        decompress(res.content).then(keys => {
          setSenseKeys(Object.freeze(keys))
          setLoadingSenseKeys(false)
        })
      } else {
        fetch('/dictionary_builder/data/sense_keys.txt')
          .then(async res => {
            Iif (!res.ok) throw 'failed to fetch sense keys: ' + res.status + ' (' + res.statusText + ')'
            const data = await res.text()
            const senseKeys = data.split(newline)
            setSenseKeys(Object.freeze(senseKeys))
            saveResource('sense_keys', senseKeys)
          })
          .finally(() => setLoadingSenseKeys(false))
      }
    })
  }, [setLoadingSenseKeys])
  useEffect(() => {
    loadResource('synset_info').then(res => {
      if (res && res.content) {
        decompress(res.content).then(info => {
          setSynsetInfo(info)
          setLoadingSynsetInfo(false)
        })
      } else {
        fetch('/dictionary_builder/data/synset_info.json')
          .then(async res => {
            Iif (!res.ok) throw 'failed to fetch synsets: ' + res.status + ' (' + res.statusText + ')'
            const data = await res.json()
            const synsetInfo = data.map((d: Synset, i: number) => {
              d.index = i
              backLink('hypernym', 'hyponym', d, data)
              backLink('instance_hypernym', 'instance_hyponym', d, data)
              backLink('domain_topic', 'domain_topic_members', d, data)
              return d
            })
            setSynsetInfo(synsetInfo)
            saveResource('synset_info', synsetInfo)
          })
          .finally(() => setLoadingSynsetInfo(false))
      }
    })
  }, [setLoadingSynsetInfo])
  useEffect(() => {
    if (terms && termAssociations) {
      const tempLemmas: {[index: string]: number | number[]} = {}
      termAssociations.forEach((termIndices, index) => {
        if (termIndices.length) {
          const associatedTerms = termIndices[0]
          const lemmaIndex =
            'number' === typeof associatedTerms ? associatedTerms
            : associatedTerms.length ? associatedTerms[0]
            : 0
          if (lemmaIndex) {
            const term = terms[index]
            const lemma = terms[lemmaIndex - 1]
            const existing = tempLemmas[lemma]
            if (existing && !('function' === typeof existing)) {
              if ('number' === typeof existing) {
                tempLemmas[lemma] = [lemmaIndex - 1, existing, index]
              } else {
                existing.push(index)
              }
            } else {
              tempLemmas[lemma] = [lemmaIndex - 1, index]
            }
            tempLemmas[term] = lemmaIndex - 1
          }
        }
      })
      setLemmas(tempLemmas)
    }
  }, [terms, termAssociations])
  useEffect(() => {
    if (terms && sense_keys && synsetInfo) {
      const sense_lookup: NumberObject = {}
      const nltk_lookup: NumberObject = {}
      synsetInfo.forEach((synset, index) => {
        sense_lookup[sense_keys[index]] = index
        if (synset.sense_index && synset.members) {
          const senseIndex = synset.sense_index + ''
          const firstMemberIndex = 'number' === typeof synset.members ? synset.members : synset.members[0]
          Eif (firstMemberIndex) {
            const nltkId =
              terms[firstMemberIndex - 1].replace(wordSep, '_') +
              '.' +
              synset.id.substring(synset.id.length - 1) +
              '.' +
              (senseIndex.length === 1 ? '0' : '') +
              senseIndex
            nltk_lookup[nltkId] = index
            synset.nltk_id = nltkId
          }
        }
      })
      setSenseLookup(sense_lookup)
      setNLTKLookup(nltk_lookup)
      setCollapsedSenses(';;' + sense_keys.join(';;') + ';;')
      setCollapsedNLTK(';;' + Object.keys(nltk_lookup).join(';;') + ';;')
    }
  }, [terms, sense_keys, synsetInfo])
  const Data = useMemo(() => {
    return {
      terms,
      lemmas,
      termLookup,
      collapsedTerms,
      termAssociations,
      conceptNet,
      sense_keys,
      synsetInfo,
      senseMap,
      senseMapOptions,
      NLTKLookup,
      SenseLookup,
      collapsedSenses,
      collapsedNLTK,
    } as TermResources
  }, [
    terms,
    lemmas,
    termLookup,
    collapsedTerms,
    termAssociations,
    conceptNet,
    sense_keys,
    synsetInfo,
    senseMap,
    senseMapOptions,
    NLTKLookup,
    SenseLookup,
    collapsedSenses,
    collapsedNLTK,
  ])
  const loading = {
    terms: loadingTerms,
    termAssociations: loadingTermAssociations,
    conceptNet: loadingConceptNet,
    sense_keys: loadingSenseKeys,
    synsetInfo: loadingSynsetInfo,
  }
  const editSenseMap = useCallback(
    (map: CoarseSenseMap, options: {rawMap?: RawSenseMap; store: boolean}, password?: string) => {
      setSenseMap(map)
      Eif (options.store) {
        setStorage('coarse_sense_map', '', map, true, password)
      }
      if (options.rawMap) {
        setSenseMapOptions(options)
        Eif (options.store) setStorage('coarse_sense_map', 'original_', options.rawMap, true, password)
      }
    },
    [setSenseMap, setSenseMapOptions],
  )
  return (
    <ResourceContext.Provider value={Data}>
      {lemmas && synsetInfo ?
        <SenseMapSetter.Provider value={editSenseMap}>{children}</SenseMapSetter.Provider>
      : <Stack sx={{margin: 'auto', marginTop: 10, maxWidth: 350}}>
          <Typography variant="h4">Loading Resources...</Typography>
          <List>
            {resources.map(({key, label}) => (
              <ListItem key={key} dense>
                <ListItemIcon sx={{minWidth: '35px', mb: 1}}>
                  {Data[key] ?
                    <Done color="success" />
                  : loading[key] ?
                    <CircularProgress size="1.5rem" />
                  : <Error color="error" sx={{marginBottom: -0.8}} />}
                </ListItemIcon>
                <Typography>
                  {!Data[key] && !loading[key] ? 'Failed to load ' : ''}
                  {label}
                </Typography>
              </ListItem>
            ))}
          </List>
        </Stack>
      }
    </ResourceContext.Provider>
  )
}