R/inpi.R

rm_accent <- function(x) gsub("`|\\'", "", iconv(x, to = "ASCII//TRANSLIT"))

#' Baixa a ultima revista RPI disponivel
#' 
#' @export
baixa_ultimo_inpi <- function(path) {
  link <- 'http://revistas.inpi.gov.br/rpi/'
  r <- httr::GET(link)
  h <- rvest::html(r)
  nodes <- rvest::html_nodes(h, xpath = '//a[contains(@href, "/txt/rm")]')
  values <- rvest::html_attr(nodes, 'href')
  last <- tail(sort(values), 1)
  name <- sprintf('%s/%s', gsub('[^/]+/', '', path), last)
  d <- download.file(last, destfile = name)
  if(d == 0) cat('Download OK!\n')
}

#' @export
carrega_xml <- function(path = NULL) {
  if(is.null(path)) {
    path <- system.file('extdata/', package = 'inpi')
  }
  arq <- list.files(path, full.names = TRUE)
  zip_arq <- arq[grep('\\.zip', arq)][1]
  unzip(zip_arq, exdir = path, )
  f <- TRUE
  while(f) {
    Sys.sleep(3)
    try({
      xml_arq <- arq[grep('\\.xml', arq)][1]
      xml_arq <- arq[grep('\\.xml', arq)][1]
      xml <- rvest::xml(xml_arq)
      f <- FALSE
    })
  }
  file.remove(xml_arq)
  cat('XML carregado com sucesso!\n')
  return(xml)
}

#' @export
pesquisa_inpi <- function(re, xml = NULL, mostrar_ncl = TRUE) {
  if(is.null(xml)) {
    xml <- carrega_xml()
  }
  nm <- rvest::xml_nodes(xml, xpath = '//processo//marca//nome')
  nm <- rvest::xml_text(nm)
  pesquisa <- nm[stringr::str_detect(rm_accent(nm), stringr::ignore.case(re))]
  
  cat('Termos encontrados:\n', pesquisa, sep = '\n')
  try({
    if(mostrar_ncl) {
      d <- dplyr::bind_rows(lapply(pesquisa, function(x) {
        xp <- sprintf('//processo//marca//nome[text()[contains(., "%s")]]', x)
        node <- rvest::xml_node(xml, xpath = xp)
        processo <- XML::xmlAncestors(node, count = 3)[[1]]
        node <- rvest::xml_node(processo, 'classe-nice')
        if(is.null(node)) {
          nc <- NA
        }
        nc <- rvest::xml_attr(node, 'codigo')
        proc <- rvest::xml_attr(processo, 'numero')
        d <- dplyr::data_frame(ncl = nc, processo = proc)
        return(d)
    }))
    d$nome <- pesquisa
    return(d)
    } else {
      return(pesquisa)
    }
  })
  return(data.frame())
}
jtrecenti/inpi documentation built on May 20, 2019, 3:17 a.m.