<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ivan Brasilico on Medium]]></title>
        <description><![CDATA[Stories by Ivan Brasilico on Medium]]></description>
        <link>https://medium.com/@brasilico-ivan?source=rss-642d583ec032------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*Dc1vDqzbzAx_Ajdd.</url>
            <title>Stories by Ivan Brasilico on Medium</title>
            <link>https://medium.com/@brasilico-ivan?source=rss-642d583ec032------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 01:00:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@brasilico-ivan/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Resenha de artigo: o impacto da inteligência artificial na inovação]]></title>
            <link>https://brasilico-ivan.medium.com/resenha-de-artigo-o-impacto-da-intelig%C3%AAncia-artificial-na-inova%C3%A7%C3%A3o-291c09535cf?source=rss-642d583ec032------2</link>
            <guid isPermaLink="false">https://medium.com/p/291c09535cf</guid>
            <category><![CDATA[transformação-digital]]></category>
            <category><![CDATA[inteligencia-artificial]]></category>
            <category><![CDATA[desenvolvimento]]></category>
            <category><![CDATA[inovaç]]></category>
            <category><![CDATA[economia]]></category>
            <dc:creator><![CDATA[Ivan Brasilico]]></dc:creator>
            <pubDate>Wed, 09 Jun 2021 17:53:50 GMT</pubDate>
            <atom:updated>2021-06-09T17:53:50.739Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/501/0*_5zFomtuUcQ8TSPm.jpeg" /><figcaption>‘Eternal Singularity’ by Mark Lloyd</figcaption></figure><h4>The Impact of Artificial Intelligence on Innovation<br>Iain M. Cockburn, Rebecca Henderson, Scott Stern<br>NBER Working Paper №24449 — March 2018<br>JEL No. L1</h4><h4>O provocante artigo exploratório publicado no norte-americano &quot;National Bureau of Economic Research&quot; traz várias discussões como pano de fundo, a principal, se o Deep Learning pode revolucionar a inovação, servindo como uma novo &quot;tecnologia de propósito geral&quot;, ou até como a &quot;invenção de um método de inventar&quot;.</h4><blockquote>&quot;A inteligência artificial deve aumentar significativamente a eficiência de nossa economia. Mas ela pode ter um impacto ainda maior se puder ser um novo &#39;método de invenção&#39; de propósito geral que possa reformar a natureza do processo de inovação e a organização da P&amp;D (…) as recompensas de dominar este modo de pesquisa podem inaugurar um período de corrida (…) por controle de dados e algoritmos (…) sugerimos que alguma política de transparência e compartilhamento de dados pode ser crítica para estimular competitividade, produtividade, pesquisa, inovação e progresso.&quot; — em uma tradução livre, assim começa o artigo.</blockquote><p>Abaixo apresento brevemente a estrutura do. Note-se que os autores propõe debater impactos/dinâmicos na economia, sociedade e na pesquisa como um todo. É um artigo que vai um pouco além da teoria ou aplicação em administração, e depois debatem se os últimos avanços em IA seriam, ou não, tecnologias de propósito geral (VI-<strong>GPT</strong>) ou mesmo uma invenção de método de invenção (VII-<strong>IMI</strong>)*.</p><p>*o leitor deve atentar para estes termos: <strong>GPT e IMI</strong>, serão, junto com a teoria de inovação arquitetural/disruptiva e a economia de inovação, o fio condutor do artigo.</p><p>I. Introduction</p><p>II. The Economics of New Research Tools</p><p>III. The Evolution of Artificial Intelligence</p><p>IV. How Might Different Fields within Artificial Intelligence Impact Innovation</p><p>V. Data</p><p>VI. Deep Learning as a GPT</p><p>VII. Deep Learning as a General-Purpose Invention</p><p>VIII. Concluding Thoughts</p><h3>I. Introdução</h3><p>Então os autores iniciam avisando que discutem &quot;sob a perspectiva econômica da informação&quot;, &quot;a <strong>importante distinção</strong> entre o problema de prover incentivos à <strong>inovações</strong> com <strong>domínio</strong> de aplicação relativamente <strong>estreito</strong>&quot; e &quot;<strong>tecnologias com largo domínio&quot;</strong>.</p><p>Portanto, cabe: 1 — analisar o grau em que avanços de IA podem ser <strong>GPT</strong> — general purpose technologies ou tecnologias de propósito geral — pois estas historicamente têm sido condutoras de desenvolvimento tecnológico de longo prazo e 2 — separar. Algumas irão constituir redução de custo ou aumento de qualidade em processos de produção existentes, outras possuem o potencial de criar não apenas incremento de produtividade, mas mudanças na própria natureza do processo de inovação.</p><p>Aqui, começam a conceitualizar também o <strong>IMI</strong>: a &quot;invenção de um método de invenção&quot; que teria muito mais impacto no desenvolvimento econômico que qualquer outro produto.</p><p>Avisam então que um dos produtos do artigo será um banco de dados sobre artigos científicos e registros de patentes no campo de IA, que dividirão a IA em 3 campos escolhidos: robótica, sistemas simbólicos e aprendizado profundo, e que encontraram flagrantes evidências de rápido e significante incremento do campo de aprendizado.</p><p>Coletaram também evidências suplementares analisando o padrão de citações de autores seminais do campo, como Geoffrey Hinton.</p><h4>II. The Economics of New Research Tools: The Interplay between New Methods of Invention and the Generality of Innovation</h4><p>As novas aplicações de IA trazem os potenciais de novos problemas de contratos associados ao desenvolvimento de uma nova ferramenta de pesquisa de largo alcance, bem como problemas de coordenação surgindo da adoção e difusão. Surgirão desafios sérios, para Governos, instituições e organizações, em ambas dimensões.</p><p>O estudo de David’s (1990) sobre o motor elétrico demonstrou que esta invenção trouxe mudança tecnológica e organizacional, em setores tão diversos como manufatura, agricultura, varejo e construção. Estas &quot;<strong>GPTs</strong>&quot; possuem características que distinguem de outras inovações: aplicação em vários setores, fazem surgir e avançar inovações em setores de aplicação, e elas mesmas evoluem rapidamente, trazendo externalidades tanto verticais quanto horizontais ao processo de inovação.</p><p>N.A.: interessante que Rodgers (2017) ao falar sobre transformação digital em seu livro, cita também os motores elétricos. Fala sobre a despeito das possibilidades trazidas pelas tecnologias, muitas fábricas ficam presas no processo do passado: <em>&quot;A energia elétrica eliminou todas as limitações que até então haviam definido as características das fábricas. Agora as máquinas podiam ser arrumadas na ordem do fluxo de trabalho ótimo. (…) Os donos das fábricas, no entanto, ignoravam em grande parte essas oportunidades&quot;</em></p><p>Uma segunda forma conceitual de pensar sobre IA é a economia de ferramentas de pesquisa, caso a IA seja utilizada como uma forma de criar novos produtos, com aplicações ainda mais abrangentes. Aqui os autores exemplificam <strong>IMI </strong>através da descoberta da hibridização cruzada dupla. Ao invés de criar apenas uma nova variedade de milho, a tecnologia permitiu o nascimento de toda uma nova categoria de pesquisa na agricultura, permitindo o surgimento de inúmeros novos produtos.</p><p>Os avanços em aprendizado de máquina e aprendizado profundo posseum grande potencial como ferramenta de pesquisa e classificação automáticas. e podem expandir horizontes alterando radicalmente a ciência e a comunidade técnica, do modo que a invenção de lentes óticas e sua aplicação em microscópios e telescópios mudou a maneira de vermos o mundo.</p><p>Um alerta trazido pelos autores: distorções competitivas podem ser trazidas nesta revolução, na forma de controle físico ou de propriedade intelectual de ativos de IA, sendo primordial o papel das instituições neste processo de garantir os benefícios da IA para a sociedade.</p><h4>III. The Evolution of Artificial Intelligence: Robotics, Symbolic Systems, and Neural Networks</h4><p>Aqui os autores traçam um panorama bem particular das subdivisões de IA e da história de IA. Começam falando do nascimento dos sistemas simbólicos, tentando modelar inteligência inspirada na humana, passam a falar de aplicações robóticas, e fazem considerações sobre haver um ramo &quot;robótico&quot; de IA que seria de aplicação muito especializada, e que não seriam com certeza <strong>IMIs</strong>, e que o terceiro ramo de IA seria os baseados em aprendizado. Citam Hinton e Salakhutdinov (N.A: talvez um dos principais responsáveis pelo ressurgimento da IA seja realmente Hinton, que insistiu em pesquisas com <em>Hopfield Networks, Simulated Annealing </em>e principalmente foi um dos primeiros a formalizar a aplicação dos algoritmos de <em>Gradient Descent </em>no treinamento de redes neurais, permitindo o surgimento das redes neurais profundas e com isso superando as limitações de redes neurais descritas no trabalho de Marvin Minsky and Seymour Papert — Perceptrons(1969). Além disso, orientou o trabalho que originou grande parte do <em>hype</em> de IA, a rede vencedora do ImageNet em 2012).</p><h4>IV. How Might Different Fields within Artificial Intelligence Impact Innovation?</h4><p>Os autores citam que a IA simbólica tinha como um dos objetivos fornecer um &quot;resolvedor de problemas gerais&quot; que mesmo os avanços atuais não atingiram. E que avanços em robótica têm vindo de forma muito especializada, mas em que os avanços de melhoria de performance e maior difusão terão maior impacto em substituição de pessoas (job displacement) do que em melhoria de trabalhos (job enhancement). Citam que o &quot;progresso em veículos autônomos apontam para a possibilidade da robótica escapar do campo estrito da manufatura e laboratórios. Aqui eu gostaria de fazer a observação, que, na definição de &quot;robótica&quot; utilizada pelos autores, menos de 10% da tecnologia dos atuais carros autônomos se encaixa, sendo que a maior parte são tecnologias classificadas pelos autores no grupo de aprendizado.</p><p>Em seguida os autores citam que os últimos avanços em aprendizado profundo possuem o potencial de ser tanto <strong>IMI</strong> quanto <strong>GPT</strong>, reforçando a expectativa de impactos significantes de longo prazo desta tecnologia.</p><p>Novamente, os autores reforçam a necessidade políticas públicas para conduzir esta inovação, de forma a promover competição e ganho social. &quot;<em>Enquanto os algoritmos estão em domínio público, os dados, que são essenciais, podem ser públicos ou privados, e o acesso a eles dependerá de políticas, limites organizacionais e instituições&quot;.</em></p><h4>V. Data</h4><p>Conforme citado anteriormente, o artigo utilizou um conjunto de publicações em IA pesquisados no “Thompson Reuters Web of Science&quot;, assim como o registro de patentes do &quot;U.S. Patent and Trademark Office”.</p><h4>VI. Deep Learning as a GPT: An Exploratory Empirical Analysis</h4><p>De posse das definições anteriores, os autores se voltam para o primeiro exercício de análise exploratória, determinar se os recentes avanços no campo &quot;aprendizado&quot; da IA são mais orientadas para aplicações do que os demais, concluindo terem encontrado evidência empírica que o aprendizado profundo carrega características de uma <strong>GPT</strong>, e que os indicadores bibliométricos provam que está evoluindo rapidamente além de ser aplicado em cada vez mais setores diversos.</p><h4>VII. Deep Learning as a General-Purpose Invention in the Method of Invention: Considerations for Organizations, Institutions and Policy</h4><p>A seguir, inicia-se a análise exploratória da configuração de aprendizado profundo como uma <strong>IMI</strong>.</p><p>Em <strong>&quot;The Management and Organization of Innovation&quot;</strong>, por exemplo, analisam que a IA tende a aumentar performance em projetos de pesquisa intensivos em busca e organização de conhecimento e abrir oportunidade de estudos de fenômenos anteriormente tidos como intratáveis.</p><p>Permitindo a manipulação de dados e descoberta de padrões de forma nunca antes vista, o aprendizado profundo tem a priori realmente todas as características de uma revolução do tipo &quot;<strong>IMI</strong>&quot;.</p><p><strong>Em &quot;Innovation and Competition Policy and Institutions&quot;</strong>, alertam novamente para problemas em propriedade de dados, propriedade de invenções, e cuidados necessários relativos a privacidade, viés e proteção do consumidor. Alertam que empresas que adquirirem uma posição privilegiada prévia em IA tendem a consolidar esta posição gerando mais dados, e levantar uma barreira de entrada.</p><h4>VIII. Concluding Thoughts</h4><p>Aqui os autores repetem alguns destaques presentes no artigo: que o artigo exploratório demonstra que o campo de pesquisa de IA se move em direção ao aprendizado profundo, que estas descobertas são uma GPT e estão se tornando IMI, e que nos campos político, social, econômico e gerencial haverão implicações a serem levadas em conta, da necessidade de políticas visando estabelecer equilíbrio e competição, e que tanto este campo quanto as possíveis respostas gerenciais e institucionais constituem um campo fértil para pesquisa.</p><p>Por fim, gostaria de destacar ao final o quadro apresentado na parte IV, que sumariza bem as classificações adotadas no artigo e as dimensão <strong>GPT e IMI</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*GSC-dsxIQRH76lr9YUBSKA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=291c09535cf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Resenha de artigo - Inteligência Artificial: blocos construtivos e uma tipologia de inovação]]></title>
            <link>https://brasilico-ivan.medium.com/resenha-de-artigo-intelig%C3%AAncia-artificial-blocos-construtivos-e-uma-tipologia-de-inova%C3%A7%C3%A3o-2c8ef18df9ac?source=rss-642d583ec032------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c8ef18df9ac</guid>
            <category><![CDATA[tipología]]></category>
            <category><![CDATA[inteligencia-artificial]]></category>
            <category><![CDATA[inovação]]></category>
            <category><![CDATA[transformação-digital]]></category>
            <dc:creator><![CDATA[Ivan Brasilico]]></dc:creator>
            <pubDate>Sun, 06 Jun 2021 18:36:18 GMT</pubDate>
            <atom:updated>2021-06-09T02:10:10.005Z</atom:updated>
            <content:encoded><![CDATA[<h3>Artificial intelligence: Building blocks and<br>an innovation typology</h3><p><a href="https://doi.org/10.1016/j.bushor.2019.10.004">Ulrich Paschen (a), Christine Pitt (b), Jan Kietzmann</a> (c)</p><p>(a) Luleå University of Technology, 971 87 Luleå, Sweden<br>(b) Royal Institute of Technology (KTH), 114 28 Stockholm, Sweden<br>(c) University of Victoria, Victoria, BC V8P 5C2, Canada</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/1*UfdIf7sIPPe1hP5qVo6czA.png" /><figcaption>w w w. j o u r n a l s . e l s e v i e r. c o m / b u s i n e s s — h o r i z o n s</figcaption></figure><p>O artigo começa propondo fechar o escopo e definir os princípios do que seria a IA para fins deste, e a partir daí as oportunidades e desafios. Então apresenta seis blocos construtivos: dados estruturados e não-estruturados, pré-processamento, processamento, base de conhecimento e saída de informação com adição de valor. Propõe também uma tipologia de duas dimensões para gerentes analisarem o impacto da IA em seus negócios: a primeira dimensão identifica se é uma inovação de produto ou inovação de processos, a segunda se ele é habilitadora ou destruidora das competências atuais das empresas.</p><p>Vale a pena começar visualizando a estrutura do artigo:</p><ol><li>AI: Optimism, pessimism, and a middle road for managers</li><li>AI building blocks</li></ol><ul><li>2.1 Inputs</li><li>2.1.1 Structured data</li><li>2.1.2. Unstructured data</li><li>2.2. Processes</li><li>2.2.1. Preprocesses</li><li>2.2.2. Main processes</li><li>2.3. Data storage: Knowledge base</li><li>2.4. Outputs: Information</li></ul><p>3. A typology of AI-enabled innovations and their effects on competencies</p><p>4. Applications of the AI typology</p><p>5. Limitations of AI</p><p>Como se vê, são analisadas duas formas diferentes de tentar mapear IA para gerentes: em (2.) por etapas/produtos dos sistemas de IA, em (3 e 4) a tipologia baseada em competências expandidas ou destruídas x inovação de produto ou processo.</p><p>Em (1) os autores expõem rapidamente o <em>hype </em>em AI e principalmente existirem definições e expectativas (otimistas ou pessimistas) muito extremas. Então propõem uma definição mínima consensual, um meio termo de expectativas, e também postura pragmática, como &quot;gerentes considerarem se IA representa mais uma oportunidade ou uma ameaça para sua organização&quot;. Reforçam que o artigo é direcionado mais a executivos e gerentes do que especialistas em IA, com a meta de fazer o fenômeno IA ser melhor digerido pelos tomadores de decisão.</p><p>Passando a parte 2, que seriam os blocos componentes da IA, começa-se definindo IA como agentes computacionais que agem de forma inteligente, percebendo seus ambientes a fim de tomar ações que maximizam a chance de sucesso. Redes neurais artificiais também podem agir como bases de conhecimento implícitas, gravando em seus pesos o conhecimento adquirido no treinamento.</p><p>Estes agentes seriam compostos de partes, conforme o quadro abaixo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*QtzIvCVg7UvTIHlaEIVMow.png" /><figcaption>Blocos de construção de sistemas de inteligência artificial</figcaption></figure><p>E a tipologia que estuda as dimensões tipo de inovação e tipo de efeito em competências é resumida no quadro abaixo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/505/1*1j5HEXwVEjx2dRgQfs_fYQ.png" /><figcaption>Tipologia de inovações habilitadas por IA e seus efeitos nas competências</figcaption></figure><p>A tipologia então poderia ser utilizada para ajudar a entender a IA e:</p><ul><li>Antecipar como inovações de IA podem afetar as competências da organização;</li><li>Como a IA afeta as competências dos parceiros (trocar para fornecedores que reconheçam melhor como a IA pode guiar melhorias em competências para a sua cadeia de valor);</li><li>Entender a variedade de inovações de IA e as diversas formas de obter vantagem competitiva através destas;</li><li>Discutir o portfólio de inovações da organização, com vistas a decidir quais inovações de AI se encaixam melhor em sua situação.</li><li>Monitorar como inovações de IA podem destruir ou expandir valor em produtos ou processos relacionados ao seu Setor. Neste caso, especialmente, líderes em Setores/produtos precisam avaliar se não estão em iminência de uma descontinuidade/disrupção em seu fluxo de criação de valor.</li></ul><p>O artigo foca na chamada IA &quot;estreita&quot; ou &quot;fraca&quot;, especialista em tarefas bem específicas, em oposição à uma IA geral ou generalista, dado que é a que atualmente está avançada e sendo aplicada. De qualquer forma, mesmo a IA &quot;fraca&quot; possui potencial para mudar completamente o mundo de trabalho e ocupações, expandir a desigualdade entre pessoas e organizações e ameaçar direitos e liberdades.</p><p>Destaca por fim, algumas limitações atuais: há considerável custo e tempo para implantação de sistemas de IA, pode ser necessário contornar problemas de interoperabilidade, de qualidade dos dados e de privacidade.</p><p>Reforça mais uma vez que executivos e empreendedores dispostos a se beneficiar do potencial da IA precisam entender os blocos componentes de sistemas de IA e seus impactos nas competências organizacionais.</p><p>Por fim, os autores afirmam que<em> &quot;ao descrever os seis blocos construtivos de IA e apresentarem uma tipologia para ajudar a antecipar os efeitos da IA, esperam motivar pesquisas com mais nuances em um contexto de teoria de organizações&quot;.</em> Opinam que as <em>&quot;aplicações atuais de IA seriam mais tendentes a ser habilitadoras de competências, entretanto com os avanços devem surgir mais IAs destruidoras de competências, fundamentalmente reinventando como negócios agem, competem e prosperam&quot;</em>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c8ef18df9ac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A "Receita Certa" de Transformação Digital]]></title>
            <link>https://brasilico-ivan.medium.com/e-transforma%C3%A7%C3%A3o-ou-d-transforma%C3%A7%C3%A3o-informatizar-e-digitalizar-7e917694e929?source=rss-642d583ec032------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e917694e929</guid>
            <category><![CDATA[transformação-digital]]></category>
            <category><![CDATA[inovação]]></category>
            <dc:creator><![CDATA[Ivan Brasilico]]></dc:creator>
            <pubDate>Sat, 05 Jun 2021 14:42:34 GMT</pubDate>
            <atom:updated>2021-06-11T15:37:30.414Z</atom:updated>
            <cc:license>http://creativecommons.org/publicdomain/zero/1.0/</cc:license>
            <content:encoded><![CDATA[<h4>E-transformação ou D-transformação — informatizar e digitalizar — com tempero ou sem tempero</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JFCu6KkqeTDk3O6EMQedTQ.png" /><figcaption>m</figcaption></figure><blockquote><em>&quot;o velho está morrendo, e o novo não pode nascer&quot; *</em></blockquote><p>Tem sido gasta (com razão) muita tinta, muita energia ativando LEDs e muitos gigabytes de tráfego de rede e espaço de armazenamento com o tema &quot;Transformação Digital&quot;. Pesquisas, artigos, cursos para todos os bolsos, muitos títulos nos Currículos e nos <em>blogs</em>. Mas não teria certeza se tantos a estão praticando. Esta semana me deparei com um artigo aqui na <em>Medium</em> que consegue resumir, com uma brincadeira de palavras, o que a meu ver é — talvez — o erro mais comum em processos de informatização (aproveitando e recuperando uma palavra fora de moda) / transformação digital.</p><p>Falando em palavras, a língua tem um poder muito grande. Noam Chomsky, um dos mais influentes linguistas e pensadores do século XX chegou a teorizar que os humanos possuiriam estruturas inatas para a linguagem, tal a importância desta no desenvolvimento do pensamento. No campo da pedagogia, Piaget e Stern, e mais tarde Vigotsky, ao estudarem o pensamento infantil, também teorizavam habilidades inatas do ser humano para o pensamento e a linguagem, tal o poder que observa-se da linguagem para resumir entendimentos, pensamentos e conceitos muitas vezes complexos e abstratos.</p><p>Esta teoria de gramática gerativa foi tão influente que algumas décadas depois foi preciso um movimento de linguistas para refutá-la/afastá-la e permitir outras linhas de investigação (e isto tem tudo a ver com este artigo e com inovação — é preciso alternar pensamento concentrado e difuso, linear e lateral- não é porque a ideia é boa ou &quot;sempre funcionou assim&quot; que podemos ficar sempre parados no mesmo lugar).</p><p>Talvez nunca saibamos como o pensamento realmente funciona, talvez as pesquisas de ICM e as teorias sobre cérebro do neurocientista <a href="https://www.amazon.com.br/verdadeiro-criador-tudo-esculpiu-conhecemos/dp/6555350288">Miguel Nicolelis</a>, ou as investidas comerciais do neuralink de Elon Musk acabem revelando ao menos parte do mistério. Mas não há dúvida do poder e influência da linguagem e das palavas na significação e no aprendizado.</p><p>Neste sentido do &quot;poder da linguagem&quot;, foi deveras impactante a provocação central de &quot;tali&quot; apresentada no artigo de John Maeda.<em> Digitalização x &quot;Digitização&quot;</em><strong><em>. </em>Na visão de Maeda, falta um tempero chamado &quot;tali&quot; na maioria das receitas executadas de Transformação Digital. </strong>O que faz com que não sejam Transformação, apenas &quot;Digitização&quot;. Muda-se a mídia, mas não se aproveita a oportunidade de melhorar os processos.</p><p>Voltando a analisar palavras, penso que naqueles que possuem mais ou menos a formação e bagagem que eu, a palavra &quot;digitalização&quot; acabe sendo muito negativa para o entendimento de processos de digitalização e de transformação digital. Afinal, na minha formação cultural &quot;digitalização&quot; é sinônimo de &quot;Tirar Xerox&quot;, que nada mais é do que tirar uma foto de um papel (e no caso das &quot;máquinas de Xerox&quot; ainda imprimir novamente). Até, se eu tiver sorte de ter leitores mais jovens, ou de outras regiões do país, ou de outra língua nativa, peço contribuírem respondendo se ao ouvir a palavra &quot;digitalização&quot; já pensam logo em fotocopiadoras também (talvez os mais novos vão perguntar: que raio é esse de Xerox??).</p><p>Cansei de ver empresas e órgãos públicos implementarem sistemas de processo e comunicação eletrônica exatamente assim. Dos mais simples aos mais sofisticados. Vi estes sistemas serem utilizados como se fossem fábricas de salsichas: vamos enfiar tudo dentro de qualquer jeito e embrulhar. Assim, procedimentos que eram em papel continuaram sendo feitos em papel. <strong>Apenas estavam sendo transportados em meio digital</strong>. O antigo memorando continua sendo impresso (em várias vias), assinado manualmente, e depois tira-se a foto deste, enfia-se na salsicha do sistema de e-processo (seja um sistema específico, um site, ou um simples e-mail) e manda-se embora.</p><p>Trabalhei bastante tempo em órgãos públicos, cheguei a conhecer as &quot;RMs&quot;. Funciona assim: tenho que enviar um pedido/memorando/outro a outro Setor. Então imprimo o pedido/memorando (no mínimo duas vias para receber uma de volta e guardar na gaveta). Além disso, mando também uma &quot;RM&quot; (em duas ou mais vias) declarando que mandei outro papel. Servirá de recibo, para mim e para o destinatário. O estagiário só entrega o documento ao destinatário se este primeiro assinar o &quot;RM&quot;.</p><p>Talvez para os mais novos o descrito acima pareça piada. Mas olhe-se os sistemas, em organizações públicas ou privadas. Quantos não são exatamente ou parcialmente como o procedimento descrito? Mesmo com dezenas de opções <em>Open Source </em>de<em> </em>assinaturas digitais, blockchain, Bancos de Dados, <em>frameworks</em> rápidos de desenvolvimento web, bibliotecas de PDFs, tudo disponível e gratuito, a informatização em geral é baixa, o investimento em Sistemas é baixo.</p><p>Quanto da informação corre hoje em documentos nato-digitais, digitalmente assinados e certificados, ou mesmo em tabelas, sistemas e processos estruturados já &quot;habilitados para informação&quot; nas organizações? E por outro lado quanto de &quot;Xerox&quot; corre por aí embrulhada em salsichas disfarçada de digital?</p><p>Um dos grandes &quot;movimentos&quot; de desenvolvimento de software hoje é o &quot;<em>RPA</em>&quot;. Tem ganhado até congressos, certificações específicas, consultorias e ferramentas lucrativas das &quot;<em>Big Tech</em>&quot;. Basicamente consiste em programar &quot;robôs&quot; que entram em vários sistemas para automatizar tarefas repetitivas de escritórios. Um verdadeiro robô carimbador. Ora, no mundo <em>cyberfísico </em>é necessário continuar apertando os parafusos e encaixando as peças. Mas se estamos falando de algo 100% digital, muito provavelmente a maior parte dos (às vezes caros, sofisticados e de difícil manutenção) projetos de RPA são a solução errada para um problema que não deveria existir. Em tese, no processo transformado digitalmente não deveria existir a tal tarefa repetitiva. Mas é preciso desmontar a salsicha e pegar &quot;o Xerox&quot; lá dentro…</p><p>Podemos tentar explicar estes aparentes paradoxos pelas teorias administrativas da visão baseada em recursos e das capacidades dinâmicas. Nos desafios da inovação arquitetural/disruptiva estudados por Abernathy, Utterback e Christensen, vemos a ocorrência destes fenômenos. Uma organização desenvolve capacidades, habilidades, conhecimentos, ao longo do tempo. O novo precisa nascer, mas está obnubilado em um <em>chiaroscuro </em>de capacidades e comportamentos obsoletos.</p><blockquote>Fala-se muito que transformação digital é sobre negócio e estratégia, mais que tecnologia, na literatura. Eu gostaria de aproveitar a deixa do &quot;tali&quot; para ir além. <strong>Transformação digital é sobre pessoas</strong>. É preciso investir em Sistemas, feito por pessoas, em melhoria de processos, feito por pessoas, e é preciso principalmente investir em implantar os novos Sistemas e processos, engajando e treinando pessoas.</blockquote><p>Há uma receita certa para a Transformação Digital? Certamente não, embora haja guias, caminhos e práticas. As organizações precisam criar a sua própria receita enquanto praticam. Há a necessidade de estratégia, mas como muitas dessas serão emergentes, não basta o líder visionário, é necessário flexibilidade, comunicação, inteligência competitiva, desenvolvimento de recursos e capacidades, reformulação de processos, informatizar de verdade, desenvolver pessoas. Qualquer que seja a receita, é necessário tempero.</p><p>E você e sua organização? Falta ou não falta &quot;tali&quot; nos seus processos de Transformação Digital?</p><p>Os artigos originais de John Maeda que inspiraram este <em>post</em> estão <a href="https://johnmaeda.medium.com/digital-transformations-fail-because-they-miss-the-difference-that-just-four-letters-can-make-fb5ea5305520">aqui</a> e <a href="https://johnmaeda.medium.com/how-i-learned-what-digital-transformation-truly-means-after-waving-to-a-couple-gs-3be62c4cef7a">aqui</a>.</p><p>Aqui um ótimo resumo da <a href="https://www.blogs.unicamp.br/linguistica/2020/01/10/noam-chomsky-e-o-funcionamento-da-linguagem-menos-e-mais/">Teoria Linguística de Noam Chomsky</a> e tradução do trabalho de pensamento e linguagem de <a href="https://edisciplinas.usp.br/pluginfile.php/2477794/mod_resource/content/1/A%20construcao%20do%20pensamento%20e%20da%20linguagem.pdf">Zigotsky</a></p><p>*<em>citação inspirada em &quot;Il vecchio mondo sta morendo. Quello nuovo tarda a comparire. E in questo chiaroscuro nascono i mostri. — Antonio Gramsci&quot;</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e917694e929" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Resenha de artigo: Potenciais aplicações de Inteligência Artificial no desenho dos processos de…]]></title>
            <link>https://brasilico-ivan.medium.com/resenha-de-artigos-potenciais-aplica%C3%A7%C3%B5es-de-intelig%C3%AAncia-artificial-no-desenho-dos-processos-de-f567c4389d1c?source=rss-642d583ec032------2</link>
            <guid isPermaLink="false">https://medium.com/p/f567c4389d1c</guid>
            <category><![CDATA[inovação]]></category>
            <category><![CDATA[inteligencia-artificial]]></category>
            <dc:creator><![CDATA[Ivan Brasilico]]></dc:creator>
            <pubDate>Tue, 25 May 2021 23:22:29 GMT</pubDate>
            <atom:updated>2021-06-09T21:21:21.745Z</atom:updated>
            <content:encoded><![CDATA[<h3>Resenha de artigo: Potenciais aplicações de Inteligência Artificial no desenho dos processos de inovação</h3><h3>Application potentials of artificial intelligence for the design of innovation processes</h3><p><a href="https://www.sciencedirect.com/science/article/pii/S2212827119308741#!">ChristianVocke</a>, <a href="https://www.sciencedirect.com/science/article/pii/S2212827119308741#!">CarmenConstantinescu</a>, <a href="https://www.sciencedirect.com/science/article/pii/S2212827119308741#!">DanielaPopescu</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/141/0*c1PYcIv6v8M5GEyS.gif" /></figure><p>O artigo foi produzido por um instituto de pesquisa aplicada: Fraunhofer IAO — especializado em estudo de tecnologias digitais, modelos de negócio e transformação digital, em conjunto com a Technical University of Cluj-Napoca, e apresentado no 29th CIRP Design Conference 2019.</p><p>Este artigo analisa o estado da arte atual das técnicas de inteligência artificial e as aplicações em inovação de interação homem-máquina, aplicadas à inovação de processos.</p><p>Ele se divide em 4 partes: introdução, casos de uso, efeitos no futuro do trabalho e dos negócios, conclusões e trabalhos futuros.</p><p>Na introdução em que faz um breve história da pesquisa de IA, destacando que cada fase é seguida por um período de desilusão, destaca que a convergência atual dos fatores de abundância de dados e capacidade computacional geram atualmente novos avanços significativos.</p><p>Segundo o artigo, AI tem que ser encarada mais como uma disciplina com impactos significativos na sociedade e na economia global do que uma simples tecnologia.</p><p>Em seguida, apresenta a transcrição da definição da Comissão Européia de IA. Resumidamente, sistemas que, dada uma meta complexa, “percebem” o ambiente (coletam dados), interpretam estes dados com base no conhecimento acumulado e decidem a melhor ação. Resume a conceituação da introdução com o gráfico a seguir.</p><p>Em “Casos de Uso e funções de Sistema de IA”, os autores se debruçam sobre aplicações e taxonomias. Exemplificam que a IA já está sendo utilizada em setores tão diversos como automotivo, energia, serviços financeiros, saúde, manufatura, varejo, tecnologia, entretenimento e transporte.</p><p>Em seguida citam a “tabela periódica da IA”, publicada por Kristian Hammond no desafio xprize — Hammond K.: The Periodic Table of AI, 2016 (https://ai.xprize.org/).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/0*LbSDIRA-OBouLQa-.jpg" /></figure><p>A tabela acima é importante para compreender este artigo, e ajuda a pensar no desenho de Sistemas de IA, pois divide em áreas de entrada, processamento e saída diversas funções hoje existentes que podem ser classificadas como ou são laterais à IA. Um sistema completo de IA pode conter peças de diversas áreas, e especialmente, combinar peças dos grupos “Acessar”, “Inferir” e “Responder”.</p><p>O artigo a seguir cita uma pesquisa recente com 130 executivos de grandes companhias, com os usos mais comuns dos projetos atuais de IA. Assistentes de linguagem, como chatbots ou dispositivos “smart” são os mais comuns, com 68% dos casos. Automação de processos de negócio e TI, vêm em seguida com 62%. Em seguida, a aplicação de análise preditiva e inteligência de negócios, em áreas como detecção de fraudes ou segmentação de clientes, com 58%. Embora já haja tentativas de “prever” o futuro com base em ferramentas analíticas, o uso corrente de IA atinge hoje os maiores benefícios ao ser usado para encontrar padrões e anomalias em grandes bases de dados.</p><p>Atores introduzem a próxima parte do Artigo citando que: “no futuro, sistemas de IA serão capazes de combinar múltiplas habilidades e fazer algumas tarefas de forma 100% autônoma, hoje, precisam da interação com um decisor humano.”</p><p>Na parte 3 — Efeitos no trabalho e nos negócios — começam citando estudo que afirma esperar impacto positivo de 1,2% ao ano no PIB, enquanto para fins de comparação máquina a vapor, robôs industriais e as modernas TICs exerceram respectivamente impacto de 0,3%, 0,4% e 0,6% a.a. Note-se que aqui este agrupamento cita indiretamente os conceitos de revolução industrial 1.0, 2.0, 3.0 e 4.0, prevendo que esta terá impacto muito maior que as anteriores, ou pelo menos impacto mais acelerado.</p><p>São esperados impactos tanto em fatores estratégicos (por exemplo melhora de eficiência e custos) quanto operacionais (automação de interação com clientes e canais de vendas via chatbots), e impacto extremo no trabalho, seja através da substituição, aumento da eficiência do trabalhador por prover melhor informação, e até criação de novas funções de trabalho devido à execução automática de tarefas padronizadas. Em resumo, se preveem 3 ondas de automação por AI, conforme gráfico abaixo: inteligência assistida, inteligência aumentada, e autonomia. A análise atual do instituto para uma janela de 5 anos é que análises de dados simples serão cada vez mais automatizadas, mas atividades empáticas ainda continuarão de predominância humana.</p><p>Com as mudanças anunciadas no mundo do trabalho, empresas precisam rever suas competências e desenvolver competências digitais para implementar e compreender as novas tecnologias, assim como competências clássicas como criatividade, solução de problemas, empreendedorismo. As organizações devem desenvolver ambidestria, agilidade, experimentação, foco no cliente. Ambidestria entendida como a habilidade de identificar mudanças e desafios rapidamente e responder com mudanças em estratégias e processos. No final, são pessoas que estarão desenhando este futuro do mundo do trabalho enriquecido por IA.</p><p>Vamos para o item 4, conclusões e trabalhos futuros:</p><p>IA promoverá profundas mudanças no mundo do trabalho. Embora ofereça imensas possibilidades, adequar a tecnologia e função ao caso de uso concreto e novas formas de interação homem-máquina ainda é um grande desafio.</p><p>Sistemas de IA requerem combinação de diversos componentes para oferecer soluções sob medida e com propósito específico.</p><p>O uso de IA cria novos padrões de atividade que requerem novas competências.</p><p>É necessário o desenho integrado dos processos e atividades com as tecnologias — promovendo competências em um desenho centrado em humanos.</p><p>A IA tem o potencial de libertar empregados de mais atividades rotineiras e de oferecer novo nível de suporte a atividades intensivas em conhecimento. Mas estas oportunidades de eficiência, produtividade e inovação devem ser identificadas.</p><p>Em conclusão, acoplar as capacidades humanas e de sistemas de IA habilitam a competitividade em um mundo híbrido. Incorporar IA nos sistemas e processos do negócio é uma jornada nova, mas é sobre o suporte a humanos e não o domínio de tecnologia sobre as pessoas. Pesquisa adicional precisa ser realizada sobre uma metodologia para identificação de aplicações potenciais de IA e estabelecimento de novas formas de interação homem-máquina para melhoria de processos de inovação.</p><p>O artigo é um apanhado de referências, tentando, a partir da definição de IA, enumeração de Casos de Uso, descrição de componentes ou funções de um Sistema, analisar os impactos em processos de negócios e necessidades das empresas para se adequarem. Por já ser um resumo de diversas referências, o artigo é curto e objetivo e até difícil de resumir.</p><p>Um dos axiomas constantes do artigo: atividades &quot;empáticas&quot;, que exigem contato com pessoas, seriam menos ameaçadas por IA, e análises de dados mais ameaçadas. Entendo que não é tão simples assim, e os próprios dados do artigo contradizem em parte esta afirmação, afinal o artigo cita chatbots como uma das aplicações mais difundidas de IA. Então dependo muito do canal e do tipo de contato &quot;humano&quot;. Certamente profissões de saúde e cuidados pessoais, especialmente as que envolvem o mundo físico, estão por ora longe do alcance das aplicações de IA, mas por outro lado contatos via canais de atendimento virtuais, telemarketing, entre outros, têm apresentado grande aumento na automação, com ou sem utilização de IA.</p><p>Sobre as taxonomias apresentadas, os autores as colocam como guia para gestores avaliarem e compararem soluções de IA, citando que a combinação dos grupos &quot;Acessar&quot;, &quot;Inferir&quot; e &quot;Responder&quot; seriam um ciclo completo. Isto pode ser verdade, se utilizada simplificação, para sistemas de direção autônoma, por exemplo. Mas pode perfeitamente existir aplicação de IA mais simples, utilizando somente inferência, por exemplo. A esmagadora maioria das aplicações de segurança e detecção de fraude, prospecção do solo, previsões climáticas, por exemplo, utiliza alimentação manual de dados, ou mesmo se automática, a parte &quot;Acessar&quot; não necessariamente utiliza IA, e a parte &quot;Responder&quot;, a decisão final, fica a cargo de seres humanos, sendo a inferência apenas mais uma entrada de dados para estes. De qualquer forma, precisam estar inseridas em um processo de negócio e recebendo de outros módulos da aplicação entradas de dados, e fornecendo a outros módulos, neste exemplo interfaces de Usuário, os resultados. Seria o exemplo de &quot;inteligência assistida&quot; do próprio artigo.</p><p>O destaque que os autores dão à necessidade de acoplar/combinar a tecnologia aos processos de negócio, e, principalmente, colocar o ser humano no centro, desenvolver capacidades e utilizar estratégias ágeis, vão de encontro à teoria atual de disrupção e de inovação, sendo uma parte bastante interessante.</p><p>Sobre taxonomia, vale a pena indicar como leitura complementar curta o artigo da revista &quot;Computer World&quot; de Kris Hammond, citado neste artigo como elaborador da &quot;tabela periódica&quot; da IA. Neste artigo, ele desenvolve um pouco mais através de exemplos algumas funções &quot;Sensing, reasoning e communicating&quot;. Ele exemplifica que os assistentes &quot;Siri&quot;, &quot;Cortana&quot; e &quot;Google Now&quot; &quot;acessam&quot; através de um primeiro modelo — reconhecimento de voz — que converte a voz em texto. Então um segundo modelo utilizando técnicas de processamento de linguagem natural traduz aquele texto em um conjunto de intenções- que vira entrada para outro modelo que oferece um menu de saídas, outro modelo converte este menu de saídas em texto, e outro em voz para retorno ao usuário. O que para o humano que interage com a máquina parece um único sistema, na verdade é um conjunto de subsistemas especializados — um utiliza deep learning, outro machine learning, outro é simplesmente simbólico ou apenas um algoritmo ou uma lista cadastrada. A combinação destes sistemas cria a ilusão de um assistente &quot;inteligente&quot;.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/647/1*BZQ79GNHq4d_VDSrK1W86Q.png" /><figcaption>Exemplo de componentes de um assistente — Kris Hammond</figcaption></figure><p>Quis citar este artigo, porque no artigo resenhado não é dada ênfase que a IA hoje existente é a chamada IA restrita, em oposição à IA ampla, ou inteligência de propósito geral. Assim, para cada tarefa do processo de negócio será preciso um ou mais modelos especializados.</p><p>Uma outra informação que vale incluir é a extrema dependência dos sistemas de IA, especialmente os baseados em aprendizado profundo, de um grande conjunto de dados. Assim, conforme citado pelo artigo, sistemas de IA são compostos de múltiplas partes, devem ser acoplados aos processos de negócio, sua implantação deve incluir o estudo e inovação dos processos e o investimento no ser humano, com desenvolvimento de capacidades e competências empresarias — em aderência ao que já está prescrito na teoria de inovação — e acrescento, os componentes de IA são estreitos e extremamente ávidos por dados para aprender.</p><p>Em conclusão, sistemas de IA terão um impacto imenso em todas as áreas, e qualquer organização pública ou privada precisa estudar e implementar seus potenciais de aplicação e os impactos que está sujeito. E definitivamente, capacidade de IA não se comprará em prateleira, é uma competência a ser desenvolvida.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f567c4389d1c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Líderes Digitais — Westerman, Bonnet, Mc Afee — Resenha e reflexões pessoais]]></title>
            <link>https://brasilico-ivan.medium.com/l%C3%ADderes-digitais-westerman-bonnet-mc-afee-resenha-e-reflex%C3%B5es-pessoais-bdc9259675e8?source=rss-642d583ec032------2</link>
            <guid isPermaLink="false">https://medium.com/p/bdc9259675e8</guid>
            <category><![CDATA[transformação-digital]]></category>
            <category><![CDATA[inovação]]></category>
            <dc:creator><![CDATA[Ivan Brasilico]]></dc:creator>
            <pubDate>Tue, 25 May 2021 13:55:42 GMT</pubDate>
            <atom:updated>2021-05-25T13:55:42.969Z</atom:updated>
            <content:encoded><![CDATA[<h3>Líderes Digitais — Westerman, Bonnet, Mc Afee — Resenha e reflexões pessoais</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/160/0*-HSZMVfHyYixbHdK" /><figcaption>Leading Digital: Turning Technology Into Business …</figcaption></figure><p>Livro por Andrew McAfee e Didier Bonet</p><p>A Obra &quot;<em>Leading Digital</em>&quot;, em português &quot;Liderando na Era Digital&quot;, se propõe a dissecar as vantagens competitivas dos líderes da era digital, e a seguir em tentar destacar entre estes líderes o que foi realizado e como foi realizado.</p><p>Logo no início do Livro (Cap. 1) é apresentado um interessante quadrante bidimensional. Em um eixo, a capacidade digital instalada, em outro, a capacidade ativada de liderança em mudança. Então os autores dividem 391 empresas pesquisadas igualmente entre os quatro quadrantes, calculam as médias, e chegam à impressionantes diferenças no lucro líquido, e significativas diferenças no faturamento.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fdNx7CIS8PTaaV6d.png" /></figure><figure><img alt="Elaborado por purpose brands: https://purpose-brands.com/wp-content/uploads/2016/12/2016-12-11-Digital-Leaders-Model.png" src="https://cdn-images-1.medium.com/max/913/1*98tThZpnqGKzs8tEYnUsIg.png" /><figcaption>Gráfico elaborado por purpose brands</figcaption></figure><p>O quadrante com os melhores desempenhos é então chamado de “Mestres Digitais”. Primeiro o leitor é convencido que os “Mestres Digitais” são realmente muito melhores que os concorrentes, em seguida os autores se dedicarão a enumerar modelos de ação para uma transformação digital de sucesso, em uma série extensa de exemplos práticos nas Empresas.</p><p>Os capítulos 2, 3, e 4 passam então a enumerar modelos com áreas de atenção para incrementar a capacidade digital instalada, o primeiro eixo, e os 5, 6, 7, 8 focam no desenvolvimento da capacidade de liderança.</p><p>O capítulo 2 foca especialmente no encantamento do cliente, o 3 na construção de excelência operacional, de certa forma focando a necessidade do “cliente interno”, e o 4 na criação e exploração de novos modelos de negócio.</p><p>Destes capítulos, me chamaram a atenção especialmente os seguintes pontos:</p><p>Permeando o capítulo 2, muitas vezes o foco no cliente acaba sendo o foco nos dados. Ou seja, as novas tecnologias permitem entender o cliente, de verdade. São superadas as pesquisas, são superadas também as impressões. Em alguns casos, com os dados corretos, podemos dizer que as Empresas podem conhecer o cliente mais até do que ele mesmo. Assim, sistemas de agrupamento e sistemas de recomendação podem melhorar as vendas para os clientes, e até mesmo ser parte da própria experiência/excelência de atendimento. Em um mar de opções e informações, oferecer/entregar o produto com uma experiência suave aos clientes. A inteligência sobre o cliente passa a ser parte do produto e parte da estratégia de encantamento.</p><p>É importante também o reforço da necessidade de coerência da experiência entre diversas plataformas, dispositivos e até entre a experiência física e a virtual e o alerta que a inovação deve ser constante.</p><p>O Capítulo 3 achei o mais interessante, talvez por trabalhar em organização pública em um setor no qual a excelência operacional é o que encanta também o cliente externo e otimiza a produtividade e satisfação do cliente interno. Afinal, trabalhamos com a dicotomia facilitação e segurança: facilidade para o “correto”, e eficiência e agilidade na detecção e punição do “errado”, para garantir segurança legal a todos os envolvidos e segurança econômica a toda a sociedade.</p><p>Falando em dicotomia, o livro tenta quebrar paradigmas mentais ao enumerar algumas e defender que a excelência operacional e tecnológica pode permitir a melhoria de duas capacidades aparentemente conflitantes, como padronizar e empoderar, controlar e inovar, orquestrar e liberalizar. Termina recomendando, se houver dificuldade, começar por um lado do par, depois pelo outro, e alternando. Reforça a importância de ter uma plataforma digital central também para as operações e para estar atento aos bons exemplos de dentro e de fora da organização.</p><p>Há uma breve discussão também, como a simples disponibilização de dados de Sistema legados em uma plataforma analítica única pode ser o início de uma transformação da operação.</p><p>Do Exemplo da UPS, achei especialmente interessante como uma empresa eminentemente operacional e com um ramo de negócio “estável” e uniforme montou uma Equipe extremamente numerosa de analistas de dados, reforçando como, dentre as novas especialidades trazidas pela transformação digital, as diversas áreas de dados são centrais, são a matéria prima da inteligência, seja humana ou a de modelos de inteligência artificial.</p><p>O Capítulo 4 foca em quando há necessidade de reinvenção do modelo de negócio.</p><p>Ao separar estas possibilidades em grupos e enumerar exemplos, apresenta um modelo de raciocínio e didática prático e facilitado. Assim, a Empresa pode focar em serviços a terem regras modificadas ou até serem totalmente substituídos, em explorar serviços ou ramos totalmente novos, ou a reconfigurar entrega de valor dos serviços existentes.</p><p>Por último, aqui vão algumas críticas ao Livro:</p><p>Em primeiro lugar, me pareceu muito mais uma obra com certo teor comercial do que com extremo rigor acadêmico.</p><p>Isto começa pela apresentação dos quadrantes: como os fatores vêm de uma pesquisa, não se sabe da precisão dos julgamentos efetuados sobre as Empresas, não se sabe se há na verdade variáveis latentes sendo medidas (setor ou país de atuação, tempo da Empresa, momentos de mercado). Aparentemente também só foi analisado um ano. Novamente, não se sabe se câmbio, mercado de commodities, fatores políticos, climáticos, entre outros, desequilibraram a medição. Há mais um problema, a utilização da média dentro de grupos heterogêneos, o que sujeita a amostra a influência forte de outliers, até mesmo casos de impairment ou fraude contaminando a amostra.</p><p>Também não encontrei demonstração da relevância estatística dos achados. Ou seja, em resumo, pela exposição não dá para ter certeza se a correlação encontrada é estatisticamente significante nem se é devido às variáveis medidas ou a variáveis latentes. Talvez haja estas informações em algum anexo.</p><p>Partindo da correlação simples para a causalidade, o ideal seria um modelo teórico robusto e um caminho de comprovação estatística e/ou o estabelecimento de um contrafactual para avaliação, com avaliação da evolução das empresas no tempo. Por exemplo, as diferenças demonstradas se devem às capacidades medidas, ou a empresa que já possuía melhor organização, posicionamento de mercado e faturamento teve mais capital disponível para investir nestas dimensões?</p><p>Um caminho mais rigoroso seria comparar agrupando empresas de Setor, área geográfica e porte semelhantes, até por vários anos se possível, antes e depois de suas transformações digitais(ou não), e comparar estatisticamente intra grupos os efeitos efetivos, tentando isolar ao máximo os fatores exógenos.</p><p>Claro que acabo exagerando na narrativa anterior, por isso repeti várias vezes a palavra “ideal”, sabendo que na prática, isolar completamente os fatores exógenos e evitar variáveis latentes, ainda mais durante vários anos, seria impossível. E uma pesquisa com esta abrangência e rigor teria provavelmente custos proibitivos. Coloco como contraponto, somente pelo modo central como o quadrante foi apresentado no primeiro capítulo. Certamente o investimento em capacidade digital, liderança, capital humano tem sido empiricamente e factualmente demonstrado como essencial, mas neste quadrante podem estar sendo confundidas as causas e os efeitos.</p><p>Em seguida, gostaria de pontuar três características que permeiam grande parte do Livro que me incomodaram: uma enumeração talvez excessiva de empresas famosas, um excessivo foco na alta administração(talvez influência de uma cultura “self made man”), e alguns exemplos que me pareceram fracos e poderiam ter ficado de fora ou colocados com mais rigor.</p><p>A enumeração de nomes de empresas famosas empresta status aos achados. Como o “Mestres Digitais” e o quadrante, está presente muito mais como um argumento de autoridade. Soma-se que às vezes com base nisso inicia um desfilar de trivialidades sobre as empresas que afeta a fluidez do assunto principal.</p><p>Não tenho dúvida, e é comum a vários artigos sobre transformação digital e inovação de modelos de negócio, da importância da liderança forte, da estratégia central liderando a organização. Mas embora implicitamente o livro cite repetidamente como a vantagem digital foi construída pelo capital humano, pelo envolvimento do corpo funcional, muitas vezes o texto me causou impressão de depositar apenas na alta administração as glórias pelo processo. Sou mais partidário, e tenho visto na prática, que grandes estratégias e grandes executivos se constróem pela capacidade de ouvir diversas vozes dentro (e muitas vezes fora) da Organização. Hoje inclusive temos a predominância cada vez maior de metodologias ágeis, design sprints, estruturas matriciais, horizontalização, kanban, todos métodos voltados a construir inteligência coletiva, melhorar a comunicação e participação, inovar, e se for preciso inclusive falhar, mas falhar rápido e aprender no processo. O mito do executivo autocrata infalível e onipotente é a meu ver contraproducente para a administração e as organizações. Coincidentemente, uma das Empresas citadas é a Volvo, citada há muitos anos na teoria de administração, existindo até termos como “Toyotismo” e “Volvismo”, que são caracterizados justamente pela flexibilidade, empowerment, envolvimento dos funcionários, e outros modelos conflitantes com a visão do “Grande Líder”.</p><p>Igualmente, alguns exemplos, como a Nike. Foi citado um aplicativo da Nike como “grande diferencial”. Pode ser que estar no mercado de aplicativos, especialmente para as novas gerações, passe a ser cada vez mais importante, mas como o próprio livro coloca, a Nike, mais que uma empresa de produtos, é uma empresa de marketing. Portanto acredito que o “fator Michael Jordan” ainda é o grande diferencial de marcas como a Nike. É importante se atualizar e estar presente nas novas mídias digitais, se aproximar do cliente através do analytics e presença digital, mas seria interessante medir efetivamente os fatores de decisão de compra da Nike, e posso apostar que o status, a força do “swoosh”, o “fator Michael Jordan” ainda seja o determinante, e um deslise na presença digital pode comprometer anos desta aura. Assim, uma estratégia levemente conservadora em presença digital pode ser benéfica, um app imperfeito pode ser desastroso, e talvez o investimento em games (um Fortnite pode ser um novo Michael Jordan) case mais com a imagem da marca do que em redes sociais bobas/casuais. Ou seja, tudo demanda estudo e método, não é só “lançar um app”. Em tempos de redes sociais, o tempo é mais relativo do que nunca, sucessos geralmente levam tempo para construir mas desastres são produzidos em instantes.</p><p>Por último, o livro não cita algumas das principais tecnologias transformadoras, entre elas a inteligência artificial. Novamente falando da Volvo, é impressionante e um dos pontos altos do livro a transformação de B2B para BCB2C. É impressionamento como a Empresa encurta a distância entre ela e o Cliente e ao mesmo tempo melhora a relação com o parceiro através da fluidez da informação. Mas, em minha opinião, o verdadeiro desafio para empresas como a Volvo ainda está a espreita. Por melhor que seja seu processo de produção, que seus carros sejam indestrutíveis, que o seu casamento com o cliente e concessionários seja de conto de fadas, quando (se) carros inteligentes e autônomos chegarem e se tornarem tendência, e talvez a tendência seja apenas alugar, não mais possuir, carros, se esta não estiver par a par com inovadores (Tesla, Google, Uber?) será descartada tão facilmente quanto o foram as listas telefônicas.</p><p>Nos capítulos 5 a 8, os Autores engajam uma discussão sobre a criação da capacidade de liderança, ou como fazer a transformação digital, separando em criação, difusão, governança e a integração entre áreas chave</p><p>O Capítulo 5 foca na criação desta visão compartilhada, inicia com uma discussão sobre a importância da visão estratégica compartilhada (fazendo todos irem na mesma direção), que a visão explicita, bem definida, impede perda de tempo dos funcionários em discussões sobre quão rápido e em quanto tempo a empresa deve mudar. Resumindo, os autores defendem que os “Mestres Digitais” possuem uma visão digital compartilhada, que os distingue dos demais.</p><p>De novo, aqui, para fins didáticos, há uma pequena simplificação da realidade. Entendo que os autores tenham por visão digital uma leitura prévia e geral, embora explícita da necessidade de atualização e posicionamento frente a novas tecnologias, mas que não pode ser muito detalhada nem fechada, pela própria natureza da inovação e das tecnologias. Em primeiro lugar, a Inovação é um processo complexo, normalmente iterativo e incremental, em que muitas vezes é preciso falhar para aprender. Há respostas específicas para esta necessidade: MVPs, processos ágeis, ensaios, sondagens, etc. Muitas vezes a inovação se comporta mais como uma seleção natural de várias tentativas do que com uma teoria de design inteligente. Portanto, embora a visão geral e a liderança permaneçam essenciais — é necessário saber onde se quer chegar — o reforço na inovação como um processo iterativo, sujeito a falhas e idas e vindas pode evitar decepções prematuras. Em segundo lugar, o próprio ciclo de novas tecnologias é sujeito a oscilações. A Gartner, consultoria referência em tecnologia, publica periodicamente um ciclo de vida de tecnologias, tentando encaixar estas em uma curva sinoidal que depois tende a se estabilizar no platô. As fases da tecnologia seriam o surgimento, um crescimento rápido até a “hype”, um choque de realidade com rápido declínio, e depois nova subida até a exploração do potencial pleno desta. Nem todas cumprem <em>todo esse ciclo, cada tecnologia tem um tempo próprio em cada fase, e pode haver tecnologia com mais ou menos impacto em setores e culturas diferentes.</em></p><p>Os autores em seguida reforçam conceitos dos capítulos anteriores, citando que a visão digital normalmente engloba três perspectivas:</p><p>Melhorar a experiência do Consumidor<br>Melhorar a excelência operacional<br>Combinar os anteriores para reinventar os modelos de negócio</p><p>Um exemplo que resume diversos conceitos apresentados é o caso da Procter &amp; Gamble: “digitalizar a P&amp;G irá habilitar a gerência em tempo real e com base em demandas reais. Poderemos colaborar mais efetivamente e eficientemente, dentro e fora da companhia”. A visão privilegia a excelência operacional, colocando o negócio e a relação com consumidores e parceiros no centro da preocupação e do motivo da transformação. É bem específica no objetivo, sem detalhar a forma.</p><p>Outro ponto reforçado diversas vezes é a necessidade de identificar quais são os ativos estratégicos. Vejo como uma necessidade de ter claras as prioridades, visando otimizar os recursos.</p><p>Uma metáfora interessante utilizada para despertar a necessidade de que a visão seja ambiciosa, transformadora, é a de lagartas &amp; borboletas. Os autores falam de formas de transformação: substituição, extensão e transformação, reforçando que a última é normalmente a desejada. Ou seja, digitalizar é uma oportunidade. Não adianta substituir os formulários atuais por novos, ou estender os sistemas existentes. Deve-se entender que informatização exige simultânea revisão dos processos existentes, com eliminação de etapas redundantes ou desnecessárias para liberar todo seu potencial. Por exemplo, muitas empresas criam um Sistema para alimentar um formulário existente, mas continuam imprimindo e circulando este formulário. Se a informação já está no Sistema pode e deve circular diretamente neste.</p><p>Duas outras citações que merecem destaque: uma visão deve ter clara a intenção, os resultados e deve evoluir com o tempo.</p><p>O Capítulo 6 debate a importância do engajamento do corpo funcional, sem o qual a visão não se realiza. Começa propondo que as próprias ferramentas tecnológicas podem facilitar a cooperação e comunicação, que é importante acompanhar (dar voz) os funcionários, que engajamento passa também por distribuir papéis e responsabilidades.</p><p>O livro faz pensar em alguns questionamentos para esta era digital: Inovação é uma competência a ser desenvolvida/aprendida?? Devemos desenvolver pessoas e processos para inovação?? Inovação e Transformação digital viram processos (contínuos) dentro das Empresas? Como acostumar com a cultura de mudança?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bdc9259675e8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A dinâmica da Inovação — James M. Utterback]]></title>
            <link>https://brasilico-ivan.medium.com/a-din%C3%A2mica-da-inova%C3%A7%C3%A3o-james-m-utterback-636a131b5808?source=rss-642d583ec032------2</link>
            <guid isPermaLink="false">https://medium.com/p/636a131b5808</guid>
            <category><![CDATA[project-management]]></category>
            <category><![CDATA[disruption]]></category>
            <category><![CDATA[inovação]]></category>
            <dc:creator><![CDATA[Ivan Brasilico]]></dc:creator>
            <pubDate>Sun, 23 May 2021 11:34:28 GMT</pubDate>
            <atom:updated>2021-05-23T11:34:28.600Z</atom:updated>
            <content:encoded><![CDATA[<h3>A dinâmica da Inovação — James M. Utterback</h3><p><a href="https://g.co/kgs/NF5UFw">Dominando a dinamica da inovaçao James M. Utterback - Pesquisa Google</a></p><p>O livro &quot;Dominando a dinâmica da Inovação&quot;, de James M. Utterback, pesquisador de gestão e inovação do MIT, editado em 1994, debate os conceitos de design dominante de produto e habilitação tecnológica de processos. Este autor analisa a temática inovação desde a década de 70, em Harvard, e depois passou a desenvolver seus trabalhos no MIT. Participou de estudos e publicou artigos que cunharam diversos termos e frameworks de estudo e taxonomia da inovação. Em seus estudos, &quot;conversou&quot; e colaborou com outros autores célebres do estudo da Inovação, como William J. Abernathy e Clayton Christensen.</p><p>A ideia central do livro é descrever o ciclo da dinâmica de inovação de produto e processo, em torno do conceito de “design dominante” e das mudanças organizacionais nas diversas fases deste ciclo, seja para produtos complexos — compostos de várias partes — ou para produtos simples, sua relação com ondas de inovação tecnológica e com o aprendizado e capacidades das organizações, extraindo deste modelo lições para administradores e pesquisadores de administração.</p><p>No livro, o autor analisa, por décadas, diversas indústrias e o processo de inovação nelas. Acompanhando indústrias como a de máquinas de escrever (incluindo a substituição por computadores pessoais e processadores de texto), a de lâmpadas (a gás e óleo, posteriormente substituídas pelas elétricas), a indústria de fotografia, vidro plano, gelo, o autor identifica padrões comuns da dinâmica da inovação de produto e de processo, e a interação entre eles.</p><p>Logo na Introdução, cunha que &quot;Examinando a lista das maiores empresas dos EUA, por uma janela de tempo suficientemente grande, grande parte das outrora maiores e mais ricas saíram do topo ou simplesmente desapareceram por completo. Muitos negócios novos nasceram de tecnologias não imaginadas uma geração antes, e mesmo aquelas empresas que permaneceram mudaram tanto em produtos e tecnologias que seriam irreconhecíveis se comparadas às mesmas empresas 30 anos atrás&quot; (tradução livre e resumida).</p><p>A seguir, o autor apresenta o modelo básico retirado do artigo &quot;A Model of Product and Process Innovation&quot;, artigo de 1975 em conjunto com Abernathy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*6a0TsbW_v2eWwj0Xn0ZbWg.png" /><figcaption>Figura retirada do artigo <a href="https://doi.org/10.1016/0305-0483(75)90068-7">https://doi.org/10.1016/0305-0483(75)90068-7</a></figcaption></figure><p>Este modelo, que permeia todo o livro, mapeia a intensidade da inovação de produto e de processos ao longo do ciclo de vida de um produto ou tecnologia em indústrias. <strong>O livro tenta conectar o estudo da inovação tecnológica, o aprendizado organizacional e as competências centrais para que companhias estabelecidas transpassem as descontinuidades causadas pela mudança tecnológica.</strong></p><p>O Capítulo 1 é o primeiro de cinco estudos de caso longitudinais. Ele acompanha o desenvolvimento das primeiras máquinas de escrever até a chegada dos processadores de texto, tangenciando a maior parte dos conceitos do livro. Mostra como um design de produto nasce de um período inicial de criatividade e exploração(fase fluida), representado pelo grande ritmo da inovação de produto no gráfico abaixo, que muitas vezes se dá pela recombinação e reconfiguração de elementos constantes em outros produtos ou em protótipos. Quando finalmente um mercado é estabelecido para aquele produto, emerge um &quot;design dominante&quot;, e, cada vez mais, os antigos &quot;inovadores&quot;/experimentadores vão se focando mais em pequenos ganhos incrementais e vão desenvolvendo cada vez mais capacidades inerentes àquele produto específico(fase de transição). As habilidades empreendedoras ficam menos importantes e é dada ênfase cada vez maior às habilidades gerenciais. No final do ciclo, apenas pequenos ganhos no processo ou no produto são obtidos, através exclusivamente de inovações ou mudanças incrementais (fase específica).</p><p>Um exemplo inicial de design dominante foi o teclado &quot;QWERTY&quot;. Embora hoje todos utilizemos, e muitos não dêem conta disso, nos primórdios das máquinas de escrever foram tentados os mais diversos teclados, com as mais diversas disposições de teclas, talvez sendo o mais famoso o teclado Dvorak. Quando as máquinas de escrever se tornaram um sucesso de mercado, o teclado &quot;QWERTY&quot; já tinha dominado o mercado de tal forma que já era o design aceito e dominante. Mudar envolveria custos para os fabricantes, para os usuários que já tinham desenvolvido habilidade no teclado &quot;QWERTY&quot;, etc. Então nem se discute mais qual modelo é superior tecnicamente (em teoria o Dvorak), dados os custos de migração, o teclado &quot;QWERTY&quot; virou um padrão tão persistente que as máquinas deixaram de existir mas ele continuou como padrão nos teclados de computadores e notebooks. Caso parecido acontece, mais tarde, na guerra dos padrões Betamax e VHS. Embora teoricamente melhor, o Betamax lança fitas de 1h para gravar programas de TV e fica preso à Sony, e o VHS abre para qualquer fabricante e possui fitas de maior duração, permitindo o surgimento do mercado de <em>home video</em>. Não importa só a melhor técnica, mas também o melhor posicionamento de mercado, e uma vez estabelecido o design dominante, este tende a dominar o mercado até surgir uma disrupção tecnológica.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/0*wUwHvC1_Jj0ymGLa.jpg" /></figure><p>O Capítulo 2 detalha mais o conceito de design dominante, estendendo a explicação de como o design dominante cria uma padronização e acaba encorajando a competição por custo e escala. Para comprovar, apresenta diversos gráficos mostrando que, antes do aparecimento de um design dominante, o número de competidores em um mercado é grande, e após começa a decair rapidamente, com poucos competidores dominando os processos com perfeição e menores custos para produzir aquele design, competindo por quem tem melhor posicionamento de mercado e melhores processos, caindo cada vez mais a inovação de produto e processos, apenas na forma incremental.</p><p>E como identificar o design dominante quando surge? Olhando para trás, fica fácil perceber. Mas olhando para o presente, há muito mais dificuldade. O importante para os estrategistas empresariais, segundo o autor, é assim que identificado o surgimento de um design dominante, entender as restrições em mercados, aprendizado e hábitos de usuários, e outros efeitos colaterais, para saber posicionar seu próprio produto. Monitorar também, movimentos de mercado , especialmente pequenas empresas inovadoras ou grandes empresas explorando novas ideias, que são as que costumam fazer inovações arquiteturais — aqui ele usa a nomenclatura &quot;architetural product innovation&quot; criada por Abernathy no artigo &quot;Mapping the winds of creative destruction&quot;, com grande paralelo com o que Clayton Christensen chama de inovação disruptiva em seu livro &quot;Dilema do Inovador&quot;.</p><p>Capítulo 3 estuda o desenvolvimento da lâmpada incandescente e suas sucessoras, como esta desbancou a indústria de gás criando uma nova indústria, e também como se amoldou para aproveitar a infraestrutura e padrões deixada pronta pela antiga titular.</p><p>O livro frisa neste capítulo a essencialidade de entender as ligações entre produto, processo tecnológico, estratégia corporativa e a estrutura e dinâmica dos competidores. Uma empresa desbalanceada pode ter seu produto facilmente copiado e lançado com mais sucesso por um concorrente.</p><p>O quarto capítulo recorda o modelo de dinâmica da inovação, descrevendo-o, assim como os estudos que o mapeiam e as diversas fases do modelo, em mais detalhes. Neste, o autor reforça e confirma as fases do ciclo e destaca as mudanças organizacionais, com o poder se movendo dos indivíduos empreendedores para os indivíduos gerenciais (a demissão de Steve Jobs da Apple seria, em parte, um exemplo disso?)</p><p>Neste capítulo o autor apresenta diversas tabelas, separando diversas áreas, e seu estado em cada fase. Por exemplo, o mercado do produto vai de largo e instável a comoditizado, a competição vai de várias firmas pequenas a um oligopólio organizado em torno do design dominante, a R&amp;D inicia com foco aberto, passa a focar em poucas características do produto, até passar a focar no processo. Como o processo, o conhecimento, as cadeias de suprimentos, os equipamentos, se tornam todos bem específicos e especializados, enquanto o custo de produzir o produto baixa, o custo de mudar de produto, que era baixo, se torna altíssimo. Esta é uma das origens do &quot;Dilema do Inovador&quot; de Christensen e também do &quot;Dilema da Produtividade&quot; formulado por Abernathy. Face a uma mudança disruptiva no mercado/tecnologia, estes titulares de oligopólios/líderes de mercado têm muito a perder e muita dificuldade de adaptação.</p><p>O capítulo 5 começa a descrever a aplicação do modelo a produtos &quot;simples&quot; ou &quot;não montados&quot;, iniciando pelo vidro plano, e o sexto discorre sobre as diferenças entre produtos &quot;montados&quot; e &quot;não montados&quot;, exemplificando também com a indústria de polietileno e viscose. Destaco o alto custo de desenvolver processos inovadores e revolucionários nesta área, ainda com alto grau de risco e de incerteza, e a necessidade de perseverança e liderança visionária. A companhia Pilkington, que transformou o processo de produção de vidro em um processo manual, complicado e caro de mais de 8 etapas em um processo automatizado e barato de etapa única, demorou 12 anos para conseguir por em prática este projeto e começar a lucrar com ele. Hoje, com a mentalidade de acionistas e bolsas de valores, um CEO de uma S.A. que banca um projeto gerando fluxo de caixa negativo em no máximo dois anos seria demitido.</p><p>O capítulo 6 discorre sobre as diferenças entre produtos montados e não montados. Nos produtos não montados, a diferenciação se dá mais no processo, então a inovação de processos é maior desde o início, e se dá em formato de degraus (ou saltos) largos, momentos em que uma série de pequenas inovações combinadas toma corpo e passa a fazer uma grande diferença no processo.</p><p>Aqui há uma passagem interessante, citando estudos na indústria de petróleo e na indústria de viscose: a inovação é, também, um trabalho de &quot;formiguinha&quot;, ou de colocar tijolinhos em uma parede. 77% de reduções de custo baseadas em tecnologia na planta de viscose da Du Pont, eram devidas a pequenas mudanças técnicas, melhorias graduais de processo <strong>que não puderam ser atribuídas a projetos ou mudanças formais. </strong>Assim, não se deve desprezar o impacto das pequenas mudanças incrementais, como no estereótipo de que empresas americanas são grande inventoras, e empresas japonesas imitadoras que fazem &quot;apenas&quot; pequenas melhorias no processo. Segundo o autor, nenhuma estratégia, por si só, leva à dominação do mercado. As empresas precisam investir constantemente em inovações, de forma balanceada, tanto em produto como em processo, tanto nas radicais quanto nas incrementais.</p><p>O capítulo 7 fala sobre o que ocorre comumente quando uma indústria é invadida por uma inovação radical, o oitavo sobre o poder da inovação para criar novos e lucrativos mercados — focando principalmente no caso da Kodak — e o nono, &quot;Innovation as a game of chutters and ladders&quot; promove um debate entre as ideias apresentadas e diversas pesquisas acadêmicas com vistas a estabelecer a relação entre estratégias e comportamento das empresas diante da inovação tecnológica e a sobrevivência destas a longo prazo. O décimo e último capítulo debate como organizar a empresa para os desafios dados pelo modelo de dinâmica da inovação estudado. O autor, por fim, defende que para manter seu sucesso e renovar os seus produtos, a empresa precisa focar mais no pessoal envolvido do que nos produtos.</p><p>Sobre os capítulos citados no parágrafo, cabe alguns destaques/citações:</p><p>A inovação tecnológica se dá em sucessivas ondas, quase sempre aproveitando e combinando formas, ideias e estruturas anteriormente existentes, tendo como <em>milestones</em> a emergência de um design dominante, exemplos:</p><ul><li>Máquina de escrever: manual, elétrica, processadores de textos</li><li>Luzes: velas, lampiões de óleo, lampiões a gás, lâmpada incandescente, lâmpada fluorescente, (atualmente LEDs)</li></ul><p>Frequência grande de <em>outsiders </em>como inovadores (Sony na fotografia), relutância de empresas estabelecidas na adoção de novas tecnologias, e uma ligação muito forte entre a inovação em processos e a inovação de produtos, com foco também em conquista de mercado. Por exemplo, o design de produtos pode influenciar enormemente o custo do processo de produção (o livro cita 70%). A Kodak foi mestra durante anos em aproveitar designs e tecnologias anteriores, reaproveitando componentes, fazendo transições suaves, projetando produtos que equilibrassem qualidade, funcionalidade e custo de produção (baixo). Produzir produto adequado a preço baixo garantiu a dominância da Ford e da Kodak por mais de meio século.</p><p>Importância de sistemas: Edison precisou desenvolver simultaneamente à lâmpada todo um sistema de cabos, soquetes, geradores, … (aproveitando parte da estrutura e formas da indústria de gás). Novos produtos geram sistemas que não podem ser desprezados.</p><p>Importância da competência: A inovação deve ser considerada em termos das capacidades possuídas pela empresa. Em maior ou menor grau, inovações amplificam ou destroem a utilidade das competências que a empresa já possui. Quando a GE precisou passar da competência de produzir válvulas para a competência de produzir transistores, só conseguiu a transição quando montou uma planta inteiramente nova, com pessoal todo novo.</p><p>Como regra geral, inovações que envolvem competências existentes vem igualmente de titulares estabelecidos e <em>outsiders </em>mas inovações que envolvem a destruição de competências quase sempre vêm de <em>outsiders.</em></p><p>Como dito, no capítulo 9 o autor discute diversas visões de como lidar as inovações, especialmente as disruptivas que destroem competências, debatendo com Schumpter, Myers &amp; Marquis, Cooper &amp; Schendel, e outros que fizeram estudos seminais da área de inovação ou que trabalharam com o autor. Ao final, após afirmar que nenhum dos estudos resolve a questão de como as firmas estabelecidas podem renovar suas tecnologias quando estas se tornam obsoletas, apresenta um modelo (<em>framework) </em>de fatores para avaliar o grau de ameaça da inovação, a partir de 46 casos estudados.</p><p>Este <em>framework</em> cria 3 fatores:</p><p>A descontinuidade é de produto não-montado ou montado?</p><p>É uma substituição ou cria um novo mercado?</p><p>É habilitadora ou destruidora das competências estabelecidas da Empresa?</p><p>Por exemplo, enquanto 27 do total de 46 foram com inovadores entrantes como vencedores, se olhados por fatores: três fatores &quot;negativos&quot; — não montado, substituição e habilitadora, 7 de 7 foram dominadas por firmas estabelecidas. Já com três fatores &quot;positivos&quot; — montado, novo mercado e destruidora, 5 de 6 (com 1 inconclusivo) foram protagonizadas por novos entrantes. Placares com dois e um fator: 16 a 1 e 6 a 6, respectivamente. Ou seja, há uma clara correlação entre a quantidade de fatores presentes e a dificuldade de empresas estabelecidas transporem a descontinuidade tecnológica da inovação.</p><p>O Capítulo 10 é o mais prescritivo. O autor se preocupa em informar aos gestores diversas ações: monitoramento tecnológico, valorizar capacidades, pessoal e habilidade de aprendizado, investimento em inovação que &quot;não se justifica&quot; — a inovação radical. Discutirei este capítulo em conjunto com o livro &quot;Dilema do Inovador&quot; e alguns artigos selecionados.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=636a131b5808" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Use of Text Retrieval and Search Engines technology for tax classification]]></title>
            <link>https://medium.com/data-science/use-of-text-retrieval-and-search-engines-technology-for-tax-classification-d903fa3cf948?source=rss-642d583ec032------2</link>
            <guid isPermaLink="false">https://medium.com/p/d903fa3cf948</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Ivan Brasilico]]></dc:creator>
            <pubDate>Thu, 21 Sep 2017 02:45:04 GMT</pubDate>
            <atom:updated>2017-09-21T17:07:05.571Z</atom:updated>
            <content:encoded><![CDATA[<h3>The use of the techniques of Information Retrieval and AI (Artificial Intelligence) to aid the fiscal classification (Text Retrieval, Information Retrieval, Ranking and Search applied on product tax HS)</h3><p>Abstract: The use of the word2vec, BagofWords, unigram, bigram, tokenization, text similarity, OkapiBM25 + techniques, among others, to process sub-items that can be used for tax classification suggestion as described in the TEC¹ Mercosul (South American HS (Harmonized System²) local customization) text and ranking with respect to a list of searched words</p><p>The correct tax classification is always a challenge. The Brazilian editions of the text of the Common External Tariff have tens of thousands of words, a hundred chapters, more than 10,000 sub-items that can be used for classification, a complex and not always uniform hierarchy, besides Section Notes, Chapter Notes, general rules, etc. In this work it is proposed to use computers to raise these exact numbers for us, because in this the computers already outnumber human beings (and with the latest advances in AI and Machine Learning — AI Machine Learning and Deep Learning are beginning to reach us in processing statistical analysis of texts and in the vision and recognition of objects, in some cases surpassing).</p><p>This article is structured in four parts, relatively independent. This way, the reader can jump directly to what interests him the most. Part 1 deals with the conceptual part and does an analysis of the problem. Parts 2 and 4 will be more technical. If you just want to download and test the software that demonstrates the concepts in this article, you can go straight to Part 3.</p><p><strong>Part 1</strong> — Analysis of the text of the TEC¹ and considerations on the challenge of the Fiscal Classification. First word processing and choosing a path.</p><p><strong>Part 2</strong> — Tests and statistics in the Python programming language (with code). Application of vectorization techniques, bigram, stemization, Query similarity and OkapiBM25 +.</p><p><strong>Part 3</strong> — A user-friendly and fully functional application developed in the Java programming language — with codes on the GitHub website to download and “fork”.</p><p><strong>Part 4</strong> -Discussion of possible improvements using Machine Learning and other techniques.</p><p><strong>References</strong> — Bibliography and online resources</p><p>¹ TEC / NCM — Mercosur Common External Tariff, subject to be developed in part 1.</p><p>² Harmonized system is the international version of TEC, also explained in part 1.</p><h3>Part 1</h3><p><strong>In order to</strong> analyze the TEC text, the first step is to obtain its latest version. The TEC is a legal norm, published in Brazil by MDIC — <a href="http://www.mdic.gov.br/">Ministry of Industry, Foreign Trade and Services</a> . MDIC publishes in the link below the most recent version of TEC in “formats” Word and Excel.</p><p><a href="http://www.mdic.gov.br/index.php/comercio-exterior/estatisticas-de-comercio-exterior-9/arquivos-atuais">Current Archives</a> <a href="http://www.mdic.gov.br/index.php/comercio-exterior/estatisticas-de-comercio-exterior-9/arquivos-atuais"><br></a> <a href="http://www.mdic.gov.br/index.php/comercio-exterior/estatisticas-de-comercio-exterior-9/arquivos-atuais">MDIC www.mdic.gov.br</a></p><p>Opening TEC in Word, we can begin to analyze its structure. Basically, it has six parts:</p><blockquote>Sections and Chapters Titles <br> Abbreviations and Symbols <br> General Rules for Interpretation of the Harmonized System <br> Complementary General Rules <br> Taxation Rule for Products of the Aeronautical Sector <br> MERCOSUR Common Nomenclature (NCM) and Common Tariff Rate</blockquote><p>For our work, the important part is the sixth part, which in turn is divided as follows:</p><blockquote>Section (Description) <br> Section Notes <br> Chapter (Description) <br> Chapter Notes <br> Table NCM, Description, TEC</blockquote><p>Here is an addendum and an important observation: the task of tax classification is a technical work, which may depend on other information and specific knowledge, which will not be written in the text of the TEC, such as knowledge on metallurgy, chemistry or textiles. In addition to knowledge about the tax classification rules (described in TEC), grammatical and legal interpretation, product decomposition mixed case, among others. Therefore, the legislation determined the tax authority (Fiscal Auditor in the Federal Revenue) in terms of the tax classification of goods (article 15, section XIX, of Decree 7.482 / 11 and RFB REGULATION Nº 1464, DE MAY 2014, among others) <strong>.</strong></p><p>It should also be remembered that what we now call “TEC” is a compilation of international treaties, traditions, technical studies and standards first compiled in the international harmonized system (HS) in the so-called Brussels International Convention, signed by the World Customs Organization and then expanded to the experience and needs of Mercosur NCM — Mercosur Common Market Common Nomenclature of Goods. In addition, in Brazil, there are also additional federal rules of RIPI — Industrialized Products Tax Regulations as well as ICMS — State regulations.</p><p>As the overall focus of this article is not Fiscal Classification or legislation, we will not delve deeper into the subject. The general classification issue was exposed only to find that, before we even study the text of the TEC, at least at this stage, the 100% automatic tax classification is an utopia. The best solution that this author envisions is a suggestion system, very similar to the suggestions we receive from <em>web</em> pages when we do a search on “Google” or another <em>Internet</em> search engine <em>.</em></p><p>In this work, it is established that the proposed system will “score” TEC sub-items and display the results in descending order. After all, there are more than 10,000 possibilities. Then we’ll make the computer go through what we might call a “thick sieve,” and we’ll just look at a few better-ranked positions. We may need to look at only the top three or four of the list if we are lucky.</p><p>By “luck” we can define the “right” question as well. In this case, the question would be the description of the merchandise to be classified. Thus, the authority (Fiscal Auditor), Importer, Manufacturer, Technical Assistant, Customs Broker, agent, or other person who has the responsibility to describe the merchandise must do so in order to correctly identify the product and define its correct tax classification (IN RFB 680/2006 and Customs Regulation Art. 711, among others).</p><p>In summary, we can didactically then “slice” the tax classification task in two steps: 1. Describe the product; 2. Insert the description into the correct classification. Because TEC / NCM is hierarchical, we can make an analogy with a tree. Normally, we go through the branches of this tree in search of the correct positioning. But there is a possibility that we are looking at one branch and the correct item is in another, and we do not see it because we are in the wrong branch using a very similar sub item. <strong>Overcoming this hierarchical search is the goal of this system.</strong></p><p>Taking another analogy, let us think of an Egyptologist: in step 1 he defines exactly the artifact that the expedition will seek, and describes, through previous research, the way: How is the artifact, what archaeological site would it be, and so on. The second step is the expedition itself. In this, the team is entangled by galleries, tunnels, etc. And you can find a VERY similar artifact in a chamber, but do not look in the neighboring chamber, where the artifact is actually searched. To avoid this situation, our robot will go through all the chambers and score the artifacts found according to the similarity with the artifact described in the first step.</p><p>This score will be based on a similarity relation between a sentence describing what is sought and each of the TEC sub-items.</p><p>In the case of tax classification there is a third step still because a position or chapter or another may be <strong>excluded</strong> or there may be a conditional imposed by a section or chapter note or other type of exception as one of the general rules. This task could be amenable to automation also through NLP techniques, but it is not <em>yet</em> the scope of this work.</p><p>Now, what we can understand by “subitems of TEC”.</p><p>Analyzing the “NCM Table, Description, TEC” part, we can see that not all lines have a value in the “TEC” column:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*wY_GP3rJhjCzkWLGdUPPyA.png" /><figcaption>First page of TEC, Word version. Note the third column of the table</figcaption></figure><p>On the screen, we can easily notice the structure described above (Chapter XX (Description), Chapter Notes, NCM Table. We also noticed that only a few rows in the table have values ​​in the third column (TEC%).</p><p>It follows that the NCM structure is hierarchical, following the HS: Chapter (2 digits), Position (4 digits), Subposition 1 and 2 (5 and 6 digits). Mercosur adds two more digits: Item and Subitem (7th and 8th digits respectively). Only the full line, higher order, containing a TEC rate (as well as in the own tax rates of IPI and ICMS) can be used for tax classification.</p><p>But looking back at the table, we see that the description field in these lines is usually Spartan. For example, sub-item NCM 0102.21.10 speaks only in “pregnant or with footprints” and, worse, the following, 0102.21.90, only “Other”.</p><blockquote>So let’s create a concept called “TEC List with full description”. In this way, each sub-item, item or subitem must be described with the concatenation of its hierarchical tree. Thus, we know that subheading 0102.21.10 refers to “Live bovine animals — Domestic bovine animals — Purebred breeding animals with foot-breeding” and subheading 0102.31.90 refers to “Live bovine animals — Buffalos — Purebred Other “ . Certainly much more informative than before. We can still think of adding the descriptions of Chapters in this hierarchy.</blockquote><p>Although each line is more informative, the total number of words to be searched will be much larger, since many will repeat themselves. Also, the amount of words in some table descriptions is already large by itself, and concatenating with more descriptions will make everything bigger. But we can not lose focus: the goal is to produce lines so that the computer, not human beings, seeks and contains occurrences of words. And in that, computers are vastly better than us humans. This line being proposed will be “digested” and (pre) processed by digital machines, which will return to the human being only the “filet” that it seeks from among the more than 10,000 options.</p><h3>Part 2</h3><p>A script with all the codes of this text is available in GitHub.</p><p><a href="https://github.com/IvanBrasilico/ClassificadorFiscal">IvanBrasilico/ClassificadorFiscal</a></p><p>The general idea was put in Part 1 (“Create TEC list with concatenated description of the hierarchical tree, only for table rows with non-zero value TEC column.”), We need to start getiing our hands-on. To deal with text, characters, vectors, in the middle of the year 2017, certainly there is no faster and fun way than a good and friendly Python script.</p><pre>Beautiful is better than ugly. <br>  Explicit is better than implicit. <br>  Simple is better than complex. <br>  Complex is better than complicated.</pre><pre>In The Zen of Python</pre><p>In addition, to deal with the data we get the Python ecosystem has numerous libraries such as scikit-learn, NLTK, Theano, Tensor Flow, which implement in state-of-the-art form numerous algorithms that we may need. So without reinventing the wheel and <strong><em>K</em></strong> <em>eeping</em> <strong><em>I</em></strong> <em>t</em> <strong><em>S</em></strong> <em>imple</em> <em>,</em> <strong><em>S</em></strong> <em>tupid</em> (if we can), let’s get to work!</p><p>The first task is to analyze the lines of the file and think about the processing that will assemble the list of words. This will be a simple, line-by-line processing of a text file. We will try to determine criteria for assembly of the list and we will make “fingers” to hope that there are no exceptions, that the structure of the file is as uniform as possible. We will call this our list of TEC lists. We will then process the first one by creating the list with the complete descriptions. We’ll call it TECResumo.</p><blockquote>Given a collection of documents, the second step will be to extract your “vocabulary”. This is the most important part for applying the techniques called “Word Vectorization” and “BagofWords”. We go through the entire collection by creating a vector of unique words and call them vocab. Then, for each line in the TEC list, we will assemble a vector of the same size as the vocabulary. It will be a list of vectors called TEC vectors, with the occurrence count of each word. Using technical terms in “Text Retrieval,” each line in the SUM list is a document, and all lines form a collection. TTC vectors is the word count per document and vectorVocab the word count of the collection. This will be the heart of our work.</blockquote><pre>## Format of generated variables: <br>  ## <br>  ## TEC list: string list with each line of the text file <br>  ## listCapitulos: list of list containing title, description, and notes of each chapter <br>  ##NCM list: list list with each line containing the line code and after the description <br>  ##TECResumo list: string list containing the complete code and &quot;complete&quot; description of non-null TEC lines <br>  ## vocab: dict with key word and value occurrence count <br>  ##TEC vectors, vectorVocab: count of occurrences of the word per line and total count of occurrences of the word in the Collection <br>  ## In technical terms, each line of the list will be a collection document, vocab is the collection vocabulary</pre><p>First step, a function to process the TEC and create our first list, the “TEC list”. This first list will be assembled with the raw data of the TEC (raw data), to show the user the list exactly as it was in the original file. Using Word itself or LibreOffice that has the file ** <a href="http://www.mdic.gov.br/images/REPOSITORIO/secex/deint/cgam/tec/TEC_2017/mar-tec2017-word-completa.docx">tec ** — word-complete.docx</a> , we export the content to text file. The file will look something like the image below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1003/1*uWEeWr1BaBxIvPysR4CI1g.png" /><figcaption>TEC file in plain text format</figcaption></figure><p>What we need to do is find the lines with the following structure: line 1 with at least two numbers and a point, where the point is in column 2 or greater, followed by a line with only text. We will try to pick up the Chapters and Notes as well, looking for lines that begin with the letters “Cap” and then taking the next line until the “Note.” Line to set the titles and Note to “______” to capture the notes.</p><p>First we assemble a list with all the lines of the file</p><pre>def montaTEC (): <br>  arq = open (&quot;src / org / sort / resources / tec.txt&quot;) <br>  TACfileset = arq.readlines () <br>  return TACWatchlist</pre><p>Then a list of chapters</p><pre>def montaCapitulos (plistaTEC): <br>  listCapitulos = [] <br>  r = 0 <br>  while (r &lt;len (plistaTEC)): <br>  line = plistaTEC [r] <br>  if (line [0: 3] == &quot;Cap&quot;): #Search chapters <br>  chapter = line <br>  description = &quot;&quot; <br>  r = r + 1 <br>  line = TEC list [r] <br>  while (line [0: 4]! = &quot;Note&quot;): <br>  description = description + line + &quot;&quot; <br>  r = r + 1 <br>  line = TEC list [r] <br>  notes = &quot;&quot; <br>  r = r + 1 <br>  line = TEC list [r] <br>  while (line [0: 4]! = &quot;____&quot;): <br>  notes = notes + line + &quot;\ n&quot; <br>  r = r + 1 <br>  line = TEC list [r] <br>  list.append.append ([chapter, description, notes]) <br>  r = r + 1 <br>  return listCapitulos</pre><p>The following is the NCM hierarchical list:</p><pre>def montaNCM (plistaTEC): <br>  listNCM = [] <br>  r = 0 <br>  while (r &lt;len (plistaTEC)): <br>  line = plistaTEC [r] <br>  if (len (line) &lt;12): <br>  i = line.find (&quot;.&quot;) <br>  if ((i&gt; = 2) and (line [0] .isnumeric ())): <br>  r = r + 1 <br>  line2 = plistaTEC [r] <br>  if (not line2 == &quot;\ n&quot;): # Eliminates number sequences (in part 5 TEC Taxation Rule for Products of the Aeronautical Sector) <br>  if (not line2 [0] .isnumeric ()): # First test if line is not empty <br>  ncm = line <br>  description = line2 <br>  line3 = plistaTEC [r + 1] <br>  tec = &quot;&quot; <br>  if ((not line3) or (line3 [0] .isnumeric ())): <br>  r = r + 1 <br>  tec = row3 <br>  listNC.append ([ncm.strip (), description.strip (), tec.strip ()]) <br>  r = r + 1 <br>  return listNCM</pre><p>Finally, the most important part. Assemble our “documents”, a list of words and letters (strings) containing the code of the “usable” position for classification (column II non-zero) and the descriptions of the whole hierarchy</p><pre>def montaTECResumo (plistaNCM): # Mounts TEC lines containing II with description containing concatenation of line description and &quot;parents&quot; - positions, subheadings, etc. <br>  listTECResumo = [] <br>  r = 0 <br>  while (r &lt;len (plistaNCM)): <br>  line = plistaNCM [r] <br>  II = line [2] <br>  if (not II == &#39;&#39;): # Is a valid / &quot;selectable&quot; Classification, search for &quot;parents&quot; <br>  code = line [0] <br>  description = line [1] <br>  s = r-1 <br>  while (True): #Loop DNA.  Browse the &quot;up&quot; list by looking for the family tree ... <br>  line = plistaNCM [s] <br>  code2 = line [0] <br>  description = line [1] <br>  lcodigo = code [0: 2] + &quot;.&quot; + code [2: 4] <br>  if (lcode == code2): <br>  description = description + &quot;&quot; + descricao2 <br>  listTECResumo.append (code + &quot;&quot; + description) <br>  break <br>  lcodigo = code [0: 6] <br>  if (lcode == code2): <br>  description = description + &quot;&quot; + descricao2 <br>  lcodigo = code [0: 7] <br>  if (lcode == code2): <br>  description = description + &quot;&quot; + descricao2 <br>  lcodigo = code [0: 8] <br>  if (lcode == code2): <br>  description = description + &quot;&quot; + descricao2 <br>  lcodigo = code [0: 9] <br>  if (lcode == code2): <br>  description = description + &quot;&quot; + descricao2 <br>  s = s - 1 <br>  if ((s == - 1) or ((rs)&gt; 100)): # Exception found, abort! <br>  listTECResumo.append (code + &quot;&quot; + description) <br>  break <br>  r = r + 1 <br>  return listTECResumo</pre><p>We have codified enough here. So, say good programming practice is already out of time to write some automated test, or at least view our results. Let’s make a small preview:</p><pre>def Display (): <br>  listTEC = montaTEC () <br>  print (&quot;RAW File&quot;) <br>  print (TEC list [0:19]) <br>  print (TEC list [5001: 5020])</pre><pre>listCapitulos = montaCapitulos (listTEC) <br>  print (&quot;Chapterlist&quot;) <br>  print (ListCapitulos [1]) <br>  print (ListCapitulos [50])</pre><pre>listNCM = montaNCM (listTEC) <br>  print (&quot;listNCM&quot;) <br>  for line in listNCM [0: 9]: <br>  print (line) <br>  for line in listNCM [1001: 1010]: <br>  print (line)</pre><pre>print (&quot;Assembling documents ...&quot;) <br>  listTECResumo = montaTECResumo (listNCM) <br>  print (&quot;Total documents in collection:&quot;) <br>  print (len (listTECResumo)) <br>  print (&quot;First lines:&quot;) <br>  for line in listTECResumo [0: 9]: <br>  print (line) <br>  print (&quot;Some random lines:&quot;) <br>  from random import randint <br>  for i in range (1.10): <br>  print (listTECResumo [randint (0, len (listTECResumo))])</pre><pre>View ()</pre><pre>(I.e. <br>  ======= RESTART: D: \ Users \ Brazil \ Downloads \ Sorts \ ncmutils.py ======= <br>  RAW file <br>  \ n &#39;,&#39; \ n &#39;,&#39; \ n &#39;,&#39; \ n &#39;,&#39; \ n &#39;,&#39; \ n &#39; COMMON FOREIGN TARIFF (TEC) \ n &#39;,&#39; \ n &#39;,&#39; \ n &#39;,&#39; \ n &#39;,&#39; \ n &#39;,&#39; &#39;BRASIL \ n&#39;, &#39;2 0 1 7 \ n&#39;] <br>  \ N &#39;, &#39;10 \ n&#39;, &#39;1003.90.80 \ n&#39;, &#39;1003.90.10 \ n&#39;, &#39;Other \ n&#39;, \ n &#39;,&#39; , in grain \ n &#39;, &#39;10 \ n&#39;, &#39;1003.90.90 \ n&#39;, &#39;Other \ n&#39;, &#39;10 \ n &#39;,&#39; \ n &#39;,&#39; \ n &#39;,&#39; \ n &#39;, &#39;10 .04 \ n &#39;,&#39; \ n &#39;,&#39; 1004.10.00 \ n &#39;] <br>  listCapitulos <br>  (&#39;Chapter 2&#39;, &#39;Meat and edible meat offal&#39;, &#39;1 This chapter does not cover: \ n \ na) \ tFor items 02.01 to 02.08 and 02.10, products unfit for human consumption; \ n \ nb) \ tThe animal fats, bladders and stomachs (heading 05.04) or animal blood (headings 05.11 or 30.02); \ n \ nc) \ t Animal fat, excluding products of heading 02.09 (Chapter 15 ). \ n \ n &#39;] <br>  &#39;For the purposes of subheadings 5209.42 and 5211.42, the expression &quot;Denim fabrics&quot; means woven fabrics of yarns of different colors, with a twill not exceeding 4, comprising broken twill (sometimes referred to as satin 4), with warp on the right side, the warp yarns having the same single color and those of the weft, whitened or dyed gray or a lighter shade than of the warp threads. \ n \ n &#39;] <br>  CNM list <br>  [&#39;01 .01 &#39;,&#39; Live horses, crabs and mules&#39;] <br>  [&#39;0101.2&#39;, &#39;- \ tHawks:&#39;, &#39;&#39;] <br>  [&#39;0101.21.00&#39;, - &#39;Pure-bred breeding animals&#39;, &#39;0&#39;] <br>  [&#39;0101.29.00&#39;, &#39;- \ tOutros&#39;, &#39;2&#39;] <br>  [&#39;0101.30.00&#39;, &#39;- \&#39; Asinos&#39;, &#39;4&#39;] <br>  [&#39;0101.90.00&#39;, &#39;- \ tOutros&#39;, &#39;4&#39;] <br>  [&#39;01 .02 &#39;,&#39; Live bovine animals&#39;, &#39;&#39;] <br>  [&#39;0102.2&#39;, - &#39;Domestic animals:&#39;, &#39;&#39;] <br>  [&#39;0102.21&#39;, - &#39;Pure-bred breeding animals&#39;, &#39;&#39;] <br>  [&#39;0903.00.10&#39;, &#39;Simply shackled&#39;, &#39;10&#39;] <br>  [&#39;0903.00.90&#39;, &#39;Other&#39;, &#39;10&#39;] <br>  [&#39;09 .04 &#39;,&#39; Pepper of the genus Piper;  chilies and peppers of the genus Capsicum or of the genus Pimenta, dried or crushed or ground.], <br>  [&#39;0904.1&#39;, &#39;- \ Pepper of the genus Piper:&#39;, &#39;&#39;] <br>  [&#39;0904.11.00&#39;, &#39;- \ tNot crushed or powdered&#39;, &#39;10&#39;] <br>  [&#39;0904.12.00&#39;, &#39;-&#39; or powdered &#39;,&#39; 10 &#39;] <br>  [&#39;0904.2&#39;, - - Peppers and peppers (Capsicums of the genus Capsicum or of the genus Pimenta: &#39;,&#39; &#39;] <br>  [&#39;0904.21.00&#39;, - - - - - - - - - - - - - - - - - - - - - - - <br>  [&#39;0904.22.00&#39;, &#39;-&#39; or &#39;powdered&#39;, &#39;10&#39;] <br>  Assembling documents ... <br>  Total documents in collection: <br>  10147 <br>  First lines: <br>  0101.21.00 - Pure-bred breeding animals - Horses: Live horses and cousins. <br>  0101.29.00 - Other - Horses: Live horses and asses, mules and hinnies. <br>  0101.30.00 - Asinines Horses, sharks and mules, live. <br>  0101.90.00 - Other Live horses and asses, mules and hinnies. <br>  0102.21.10 Pregnant or bred breeding animals - Pure-bred breeding animals - Domestic bovine animals: Live bovine animals. <br>  0102.21.90 Other - Pure-bred breeding animals - Domestic bovine animals: Live bovine animals. <br>  0102.29.11 Breeding or breeding on foot For breeding - Other - Domestic bovine animals: Live bovine animals. <br>  0102.29.19 Other For breeding - Other - Domestic bovine animals: Live bovine animals. <br>  0102.29.90 Other - Other - Domestic bovine animals: Live bovine animals. <br>  Some Random Rows: <br>  5112.19.20 Of fine hairs - Other - Containing 85% or more by weight of wool or fine animal hair: Woven fabrics of combed wool or of fine animal hair. <br>  5403.41.00 - Of viscose rayon - Other multiple or cabled yarn: Artificial filament yarn (other than sewing thread), not put up for retail sale, including artificial monofilament of less than 67 decitex. <br>  5102.11.00 - Of Kashmir goat - Fine hair: fine or coarse animal hair, not carded or combed. <br>  4107.92.10 Of bovine animals (including buffaloes) - Divided with the blossom side - Other, including strips: Leather further prepared after tanning or crusting and parchment-dressed leather, of bovine (including buffalo) or of equine, without hair on, whether or not split, other than leather of heading 41.14. <br>  2916.20.90 Cyclanic, cyclenic or cycloterpenic monocarboxylic acids, their anhydrides, halides, peroxides, peroxyacids and their derivatives, unsaturated acyclic monocarboxylic acids and cyclic monocarboxylic acids, their anhydrides, halides, peroxides and peroxyacids;  their halogenated, sulphonated, nitrated or nitrosated derivatives. <br>  5204.11.31 Of two ropes Of bleached or colored cotton yarn of a size not exceeding 5,000 decitex per single yarn - Containing 85% or more by weight of cotton - Not put up for retail sale: whether or not put up for retail sale: <br>  8704.32.90 Other - Of a maximum permissible gross weight exceeding 5 tonnes - Other, with spark-ignition internal combustion piston engine (spark) *: Motor vehicles for the transport of goods. <br>  5206.24.00 - Of a denomination less than 192,31 decitex but not less than 125 decitex (metric number exceeding 52 but not exceeding 80) - Single yarn of combed fibers: Cotton yarn (other than sewing thread) containing less than 85% by weight of cotton, not put up for retail sale. <br>  8467.99.00 - Other - Parts: Tools, pneumatic, hydraulic or with self-contained electric or nonelectric motor,</pre><p>So far it seems like everything is running as expected. The ideal would be to further refine this test by creating an object or function with automated tests, comparing a human-generated “Ground Truth” result in some sample lines with that generated by our scripts. Or at least browse in more random positions and compare them to the original file.</p><p>Now let’s assemble the vectors. So far we have not dealt with the words of the text, we have kept the same as the original, for viewing a human user. Now that the “user” will be the computer (in totalizing and ranking), we must remember that “Chapter”, “Chapter”, “chapter”, “CHAPTER” and “Chapter” for the computer are different words. So first, before we start looking for and comparing words, we need to create functions to “clean” special characters, punctuation, etc. and encode our text in the simplest possible way, to increase performance and avoid surprises.</p><pre>import re <br>  from unicodedata import normalize</pre><pre>def remove_action (txt): <br>  return normalize (&#39;NFKD&#39;, txt) .encode (&#39;ASCII&#39;, &#39;ignore&#39;). decode (&#39;ASCII&#39;)</pre><pre>def only_read_and_numbers (raw): <br>  raw = remove_acentos (raw) <br>  clean = re.sub (&quot;[^ a-zA-Z0-9]&quot;, &quot;&quot;, raw) <br>  return clean</pre><p>Next step, we assemble our vocabulary, that is, search for words and add only once to our list. In this step, we go beyond standardizing the words using the above functions, putting all the characters in uppercase, eliminating <em>Stop words</em> * and all words that have up to two characters. We will take advantage of <em>Stop words</em> from the NLTK library.</p><blockquote>* Stop words <br> (Stop Word) are simple everyday words that have no relevance in the Search Engines indexing process. The use of these words in meta tags can have a negative effect, reducing the density of keywords. <br> <a href="http://www.seopedia.com.br/dicionario-seo/letra-s/">htp://www.seopedia.com.br/dicionario-seo/letra-s/</a></blockquote><p>To start using NLTK, in addition to installing the library you need to download the Databases by typing at the Python prompt. Then, in the interface, select the “Forest” and “Stopwords” packages. If you do not have the NLTK library installed, you usually just type pip install nltk at the command prompt.</p><pre><strong>&gt;&gt;&gt; import</strong> <strong>nltk</strong> <br>  <strong>&gt;&gt;&gt;</strong> nltk.download ()</pre><p>Let’s now use the Python dict to build our vocabulary:</p><pre>import nltk <br>  stopwords = nltk.corpus.stopwords.words (&#39;portuguese&#39;)</pre><pre>def montaDictVocabulario (plistaTEC): <br>  vocab = {} # Traverses all NCM COM subitems with full description.  Create vocabulary through this full description <br>  index = 0 <br>  for line in (plistaTEC): <br>  code = line [: 10] <br>  description = line [11:] <br>  list of words = description.split () <br>  for word in lists of words: <br>  if ((len (word)&gt; 2) and (stopwords.count (word) == 0)): <br>  word = only_letras_e_numeros (word) # Take anything other than AB and 0-9 <br>  word = word.upper () <br>  if word not in vocab: <br>  vocab [word] = index <br>  index + = 1 <br>  return vocab</pre><p>Next, the assembly of word counting vectors. Let’s use the numPy library that provides high performance, flexibility and ease in assembly and manipulation of arrays:</p><pre>import numpy as np <br>  # Scroll through all NCM COM subitems with full description.  Create a vector dict for each TEC item.  Create a vocabulary vector first <br>  def montaVetores (plistaTEC, pvocab): <br>  vectorVocab = np.zeros (len (pvocab), dtype = np.int16) <br>  vectorsTEC = {} <br>  for line in (plistaTEC): <br>  code = line [: 10] <br>  description = line [11:] <br>  list of words = description.split () <br>  tecvector = np.zeros (len (pvocab), dtype = np.int16) <br>  for word in lists of words: <br>  word = only_letras_e_numeros (word) # Take anything other than AB and 0-9 <br>  word = word.upper () <br>  if word in pvocab: <br>  index = pvocab [word] <br>  tecvector [index] + = 1 <br>  vectorVocab [index] + = 1 <br>  vectorsTEC [code] = tecvector <br>  return vectorsTEC, vectorVocab</pre><p>Ready! Our Vectors are assembled (it was easier than it first seemed), we have a vocabulary, and now we can practice a bit of “Know your data”. So let’s extract some statistics. How about adding some rows in the function view ()?</p><pre>print (&quot;Mounting vectors ...&quot;) <br>  vectorsTEC, vectorVocab = montaVetores (listTECResumo, vocab) <br>  print (&quot;Vocabulary Vector:&quot;) <br>  print (vectorVocab.shape) <br>  print (&quot;Document Vector:&quot;) <br>  print (len (TECs)) <br>  &gt;&gt;&gt; <br>  Assembling vocabulary ... <br>  Total TEC Vocabulary words: <br>  12787 <br>  Riding vectors ... <br>  Vocabulary vector: <br>  (12787) <br>  Vector of documents: <br>  10147</pre><p>So we have a total of 12,787 words (unique) in the vocabulary, divided into 10,147 lines that can be used for tax classification. This is because we eliminate stop words, punctuation, two-character words, box, etc. It is certainly a lot of information for a human being.</p><p>Let’s get some more interesting statistics:</p><pre>allwordsTEC = str (listTEC) <br>  list of allTEC.split () <br>  print (&quot;TEC word totals&quot;) <br>  print (len (allTextText)) </pre><pre>  allwordsTECResum = str (listTECResumo) <br>  list of all wordsTECResumo = allwordsTECResumo.split () <br>  print (&quot;Total words from TEC&#39;s NCM lines with complete description (Collection of documents):&quot;) <br>  print (len (allTextRecords)) </pre><pre>  print (&quot;Mean of words per line (Collection of documents):&quot;) <br>  print (len (listofTextRecords) / len (listTECResumo))</pre><pre>print (&quot;Number of documents in the collection:&quot;) <br>  print (len (TECs))</pre><pre>print (&quot;Statistics of occurrences of words in vocabulary:&quot;) <br>  format (vectorVocab.mean (), vectorVocab.min (), vectorVocab.max ()) <br>  &gt;&gt;&gt; <br>  Total TEC words: <br>  170019 <br>  Total words from TEC&#39;s NCM lines with complete description (Collection of documents): <br>  353167 <br>  Average words per line (Collection of documents): <br>  34.80506553661181 <br>  Number of documents in the collection: <br>  10147 <br>  Statistics of occurrences of words in vocabulary: <br>  Average 18.51848900223143, min 1, max 8124</pre><p>Well, now it’s time to create your browser to rank these lines in a word search:</p><pre>def pointerVector (ptexto, pvocab, pvetoresTEC, vectorVocab, weighted = False): <br>  ### For efficiency, select only the columns with words that occur in the search <br>  ## Therefore, first convert the TEC vectors list into a Dimension Matrix <br>  ## number ofTECs x size of the Vocabulary <br>After ## create an array of summing values query vocabulary columns <br>matrizVetores = np.asarray (list (pvetoresTEC.values ()), DTYPE = np.int16) <br>matrizCodigos = np.asarray (list (pvetoresTEC.keys ()) ) <br>matrizSoma np.zeros = (len (pvetoresTEC)) <br>wordlist = ptexto.split () <br>explanation = &quot;&quot; <br>for word in wordlist: <br>word = somente_letras_e_numeros (word) # Strip everything is not AB and 0-9 <br>word = palavra.upper () <br>if the word in pvocab: <br>index = pvocab [word] <br>vector matrizVetores = [index :,] <br>explanation = explanation word + + &#39;&#39; + str (vetorVocab [index]) + &#39; <br>matrizSoma = np.add (matrizSoma, vector)<br>indicesnaozero = np.nonzero (matrizSoma) <br>matrizTemp np.vstack = ((matrizCodigos [indicesnaozero] matrizSoma [indicesnaozero])) <br>. indices matrizTemp = [1:] argsort () <br>indices indices = [:: - 1] <br>matrizCodigoePontuacao = matrizTemp [:, indices] <br>return matrizCodigoePontuacao, explanation</pre><p>Finally, create a routine to test the search engine:</p><pre>test = &quot;T&quot; <br>while (test = &quot;&quot;): <br>test = input ( &quot;Enter a product-description words Enter simply Enter to end:.&quot;) <br>matrizPontos explains = pontuaVetores (test, vocab, vetoresTEC, vetorVocab) <br>print (explains) <br>ind = 5 <br>if (ind&gt; matrizPontos.shape [1]): <br>ind = matrizPontos.shape [1] <br>print ( &quot;plus 5&quot;) <br>is in code (matrizPontos [0: ind]): it <br>is in line (listaTECResumo): <br>codigo2 = line [10] <br>if (code == codigo2): <br>print (line)</pre><pre>&gt;&gt;&gt;&gt;&gt; <br>Enter a product-describing words. Type simply enter to terminate: other tissues <br>OTHER TISSUES 8124 569 <br>5 plus:<br>8517.62.79 Other Other emitting devices with embedded Digital Receiver - Machines for the reception, conversion, emission and transmission or regeneration of voice, images or other data, including switching and routing (forwarding *) - Other apparatus for transmission, transmission or reception of voice, images or other data, including apparatus for communication in networks wired or wireless network (such as a local area network (LAN) or wide area network (extended *) (WAN)): telephone sets including telephones for cellular networks or for other wireless networks; other devices for emission, transmission or reception of voice, images or other data, including apparatus for communication networks by wired or wireless network (such as a local area network (LAN) or wide area network (extended *) (WAN ))except devices<br>8517.62.93 Other personal receivers radio message Other - Machines for the reception, conversion, emission and transmission or regeneration of voice, images or other data, including switching and routing (forwarding *) - Other apparatus for transmission, transmission or reception voice, images or other data, including apparatus for communication in networks wired or wireless network (such as a local area network (LAN) or wide area network (extended *) (WAN)): telephone sets, including telephones for cellular networks or for other wireless networks; other devices for emission, transmission or reception of voice, images or other data, including apparatus for communication networks by wired or wireless network (such as a local area network (LAN) or wide area network (extended *) (WAN )), excluding devices<br>8517.62.59 Other apparatus for transmission or reception of voice, images or other data in wired network - Machines for the reception, conversion, emission and transmission or regeneration of voice, images or other data, including switching and routing (forwarding *) - other apparatus for transmission, transmission or reception of voice, images or other data, including apparatus for communication in networks wired or wireless network (such as a local area network (LAN) or wide area network (extended * ) (WAN)): telephone sets, including telephones for cellular networks or for other wireless networks; other devices for emission, transmission or reception of voice, images or other data,including apparatus for communication networks in a wired or wireless network (such as a local area network (LAN) or wide area network (extended *) (WAN)), excluding devices<br>8517.62.99 Other Other - Machines for the reception, conversion, emission and transmission or regeneration of voice, images or other data, including switching and routing (forwarding *) - Other apparatus for transmission, transmission or reception of voice, images or other data, including apparatus for communication networks by wired or wireless network (such as a local area network (LAN) or wide area network (extended *) (WAN)): telephone sets, including telephones for cellular networks and for other wireless networks; other devices for emission, transmission or reception of voice, images or other data, including apparatus for communication networks by wired or wireless network (such as a local area network (LAN) or wide area network (extended *) (WAN )), excluding devices<br>Other 8517.62.39 Other apparatus for switching - Machines for the reception, conversion, emission and transmission or regeneration of voice, images or other data, including switching and routing (forwarding *) - Other apparatus for transmission, transmission or reception of voice, images or other data, including apparatus for communication networks by wired or wireless network (such as a local area network (LAN) or wide area network (extended *) (WAN)): telephone sets, including telephones for cellular networks or for other wireless networks; other devices for emission, transmission or reception of voice, images or other data, including apparatus for communication networks by wired or wireless network (such as a local area network (LAN) or wide area network (extended *) (WAN )), excluding devices<br>Enter a product-describing words. Type simply enter to terminate: patterned knitted fabrics <br>WOVEN FABRIC 569 54 31 STAMPING <br>5 plus: <br>5407.10.19 Other rubber thread No - fabrics woven from high tenacity yarn of nylon or other polyamides or polyester yarn fabrics of synthetic filaments, including tissues obtained from the products of heading 5404. <br>6001.21.00 - Cotton - rings fabrics: Pile fabrics (including woven fabrics called &quot;long pile&quot; or &quot;the long&quot;) and tissue rings mesh. <br>5407.20.00 - Woven fabrics obtained from strip or the like Woven fabrics of synthetic filament yarn, including woven fabrics obtained from the products of heading 5404.<br>5407.30.00 - &quot;Fabrics&quot; mentioned in Note 9 Section XI Woven fabrics of synthetic filament yarn, including woven fabrics obtained from the products of heading 5404. <br>5407.74.00 - Printed - Other fabrics containing at least 85% by weight of synthetic filament fabrics of synthetic filament yarn, including woven fabrics obtained from the products of heading 5404. <br>Enter a product-describing words. Type simply enter to terminate: knitted polyester synthetic fiber fabrics printed <br>WOVEN FABRIC 569 839 SYNTHETIC FIBERS 54 281 74 polyester STAMPING 31 <br>5 plus:<br>9001.10.20 beams and optical fiber cables - Optical fibers, bundles of cables and optical fibers Optical fibers and optical fiber bundles; optical fiber cables other than those of heading 85.44; polarizing material in sheets and plates; lenses (including contact lenses), prisms, mirrors and other optical elements, of any material, unmounted, other than glass not optically worked. <br>Other optical fibers 9001.10.19 - optical fibers, bundles of cables and optical fibers Optical fibers and optical fiber bundles; optical fiber cables other than those of heading 85.44; polarizing material in sheets and plates; lenses (including contact lenses), prisms, mirrors and other optical elements, of any material, unmounted, other than glass not optically worked.<br>9001.10.11 core diameter less than 11 micrometers (microns) Fiber Optics - Optical fibers, bundles of cables and optical fibers Optical fibers and optical fiber bundles; optical fiber cables other than those of heading 85.44; polarizing material in sheets and plates; lenses (including contact lenses), prisms, mirrors and other optical elements, of any material, unmounted, other than glass not optically worked. <br>5511.10.00 - synthetic staple fibers, containing at least 85% by weight of such fibers yarns of synthetic or artificial staple fibers (excluding sewing thread), packaged for retail sale.<br>6001.22.00 - Of man-made fibers - rings fabrics: Pile fabrics (including woven fabrics called &quot;long pile&quot; or &quot;the long&quot;) and tissue rings mesh. <br>Enter a product-describing words. Enter simply Enter to end:</pre><p>Well, above you can see that we already have a search engine. The first search was far from what we wanted. The second got better, the third a little better, and so on. When we use search engines we always have to &quot;refine&quot; the search, and, iteratively, we get closer to what we want. The key to understanding the refinement is in the line OTHER 8124 FABRICS 569. It means that the word &quot;OTHERS&quot; appears 8,124 times in our collection and fabrics 569. In the last survey we performed the following counts: FABRICS 569 MALHA 54 FIBERS 839 SYNTHETICS 281 POLYESTERS 74 STAMPING 31</p><p>As we can see, there are &quot;very common&quot; words, &quot;common&quot; words, &quot;unusual&quot; words and &quot;rare&quot; words. Paracetamol, for example, appears only 3 times. Therefore, the occurrence of the word &quot;STAMPED&quot; in a line should count more points in the ranking than the word &quot;FIBERS&quot;. Thus, we would not display optical fibers between the first results if we look for clothes or fabrics.</p><p>Now, to better situate the problem, let&#39;s adapt the line of interaction with the user to search only the word count and make some queries:</p><pre>teste = &quot;T&quot; <br> while (teste!=&quot;&quot;): <br> teste = input(&quot;Digite umas palavras-descrição de produto para ver suas ocorrências. Digite simplemente Enter para encerrar:&quot;) <br> matrizPontos, explica = pontuaVetores(teste, vocab, vetoresTEC, vetorVocab) <br> print(explica) <br> &gt;&gt;&gt;&gt;&gt; <br> Digite umas palavras-descrição de produto para ver suas ocorrências. Digite simplemente Enter para encerrar:outros outras outro estampado estampados tintos tinto poliester poliesteres <br> OUTROS 8124 OUTRAS 3266 OUTRO 468 ESTAMPADOS 31 TINTOS 35 POLIESTER 33 POLIESTERES 74</pre><pre>From the above results, we see that &quot;OTHERS&quot; is a super-frequent word, followed by &quot;OTHERS&quot;. Already &quot;STAMPED&quot; occurs only 31 times, and &quot;STAMPED&quot; none. Already &quot;POLYESTER&quot; 33 AND &quot;POLYESTERS&quot; 74 times. To treat different versions of the same word as one, we will discuss the techniques below.<br>The solution to better score rankings is in a concept called TF-IDF. In a very short explanation, TF-IDF proposes to punctuate repetition in a document, and penalize repetition in the collection (most common word is worth less, rare is worth more).<br>Thus, we need to modify our score vector, which today contains only the word count, in a vector with the TF-IDF values. For this, in Python, we have the IDFTransformer package from the sklearn library:</pre><p>From the above results, we see that &quot;OTHERS&quot; is a super-frequent word, followed by &quot;OTHERS&quot;. Already &quot;STAMPED&quot; occurs only 31 times, and &quot;STAMPED&quot; none. Already &quot;POLYESTER&quot; 33 AND &quot;POLYESTERS&quot; 74 times. To treat different versions of the same word as one, we will discuss the techniques below.</p><p>The solution to better score rankings is in a concept called TF-IDF. In a very short explanation, TF-IDF proposes to punctuate repetition in a document, and penalize repetition in the collection (most common word is worth less, rare is worth more).</p><p>Thus, we need to modify our score vector, which today contains only the word count, in a vector with the TF-IDF values. For this, in Python, we have the IDFTransformer package from the sklearn library:</p><p><a href="http://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.TfidfTransformer.html">sklearn.feature_extraction.text.TfidfTransformer - scikit-learn 0.19.1 documentation</a></p><p>Let’s see the TfidfTransfomer effect on our vectors:</p><pre>from sklearn.feature_extraction.text import TfidfTransformer <br> transformer = TfidfTransformer() <br> matrizVetores = np.asarray(list(vetoresTEC.values()), dtype=np.int16) <br> tfidf = transformer.fit_transform(matrizVetores) <br> matriz_tfidf = tfidf.toarray()</pre><pre>print (matrizVetores [1:10]) <br>print (matriz_tfidf [1:10]) <br>&gt;&gt;&gt;&gt; <br>[[0 0 0 ... 0 0 0] <br>[0 0 0 ... 0 0 0] <br>[0 0 0 ... 0 0 0] <br>..., <br>[0 0 0 ... 0 0 0] <br>[0 0 0 ... 0 0 0] <br>[1 1 1 ... 0 0 0]] <br>[[... 0. 0. 0. 0. 0. 0.] <br>[... 0. 0. 0. 0. 0. 0] <br>[0 ... 0 0., 0. 0. 0] <br>..., <br>[... 0. 0. 0. 0. 0. 0.] <br>[... 0. 0. 0. 0. 0. 0.] <br>[0.3453688 0.3453688 0.33742073. .. 0. 0. 0.]]</pre><p>To compare the results, we will create a slightly modified scoring function (changes in bold):</p><pre>def pontuaVetores_tfidf (ptexto, pvocab, pvetoresTEC, vetorVocab = False weighted): <br>### For efficiency, select only the columns with words that occur in the search <br>## Therefore, first convert the TEC vectors list in a dimension Matrix <br>## númerodeTECs tamanhodoVocabulario x <br>## then create an array by adding the values of the query vocabulary columns <br>matrizVetores = np.asarray (list (pvetoresTEC.values ()), DTYPE = np.int16) <br> <strong>from sklearn.feature_extraction.text import TfidfTransformer <br>transformer TfidfTransformer = () <br>tfidf = transformer.fit_transform (matrizVetores) <br>matriz_tfidf = tfidf.toarray ()</strong> <br> matrizCodigos = np.asarray (list (pvetoresTEC.keys ()))<br>matrizSoma np.zeros = (len (pvetoresTEC)) <br>wordlist = ptexto.split () <br>explanation = &quot;&quot; <br>for word in wordlist: <br>word = somente_letras_e_numeros (word) # Strip everything is not AB and 0-9 <br>word palavra.upper = ( ) <br>if the word in pvocab: <br>index = pvocab [word] <br>vector = <strong>matriz_tfidf</strong> [:, index] <br>explanation = explanation word + + &#39;&#39; + str (vetorVocab [index]) + &#39; <br>matrizSoma = np.add (matrizSoma, vector) <br>indicesnaozero = np.nonzero (matrizSoma) <br>matrizTemp np.vstack = ((matrizCodigos [indicesnaozero] matrizSoma [indicesnaozero])) <br>. indices matrizTemp = [1:] argsort () <br>indices indices = [:: - 1]<br>matrizCodigoePontuacao = matrizTemp [:, indices] <br>return matrizCodigoePontuacao, explanation</pre><p>Finally, we view the results by repeating our last test, and listing beyond the TEC line score. Looking at the list below gives notice that the results greatly improved. “Optical fibers” are gone of the first list of positions and came only sub consistent with what we seek. In addition, we note that “optical fibers” and the following items had tied the score, so the ranking was actually random among the highest scoring.</p><pre>teste=&quot;tecidos de malha fibras sinteticas poliesteres estampados&quot; <br> matrizPontos, explica = pontuaVetores(teste, vocab, vetoresTEC, vetorVocab) <br> print(explica) <br> ind = 5 <br> if (ind &gt; matrizPontos.shape[1]): <br> ind = matrizPontos.shape[1] <br> print(&quot;5 mais:&quot;) <br> for codigo in (matrizPontos[0, :ind]): <br> for linha in (listaTECResumo): <br> codigo2 = linha[:10] <br> if(codigo2==codigo): <br> print(matrizPontos[1, :ind]) <br> print(linha) <br> &gt;&gt;&gt; <br> TECIDOS 569 MALHA 54 FIBRAS 839 SINTETICAS 281 POLIESTERES 74 ESTAMPADOS 31 <br> 5 mais: <br> <strong>[&#39;6.0&#39; &#39;6.0&#39; &#39;6.0&#39; &#39;5.0&#39; &#39;5.0&#39;]</strong> <br> 9001.10.20 Feixes e cabos de fibras ópticas - Fibras ópticas, feixes e cabos de fibras ópticas Fibras ópticas e feixes de fibras ópticas; cabos de fibras ópticas, exceto os da posição 85.44; matérias polarizantes em folhas ou em placas; lentes (incluindo as de contato), prismas, espelhos e outros elementos de óptica, de qualquer matéria, não montados, exceto os de vidro não trabalhado opticamente. <br> <strong>[&#39;6.0&#39; &#39;6.0&#39; &#39;6.0&#39; &#39;5.0&#39; &#39;5.0&#39;]</strong> <br> 9001.10.19 Outras Fibras ópticas - Fibras ópticas, feixes e cabos de fibras ópticas Fibras ópticas e feixes de fibras ópticas; cabos de fibras ópticas, exceto os da posição 85.44; matérias polarizantes em folhas ou em placas; lentes (incluindo as de contato), prismas, espelhos e outros elementos de óptica, de qualquer matéria, não montados, exceto os de vidro não trabalhado opticamente. <br> <strong>[&#39;6.0&#39; &#39;6.0&#39; &#39;6.0&#39; &#39;5.0&#39; &#39;5.0&#39;]</strong> <br> 9001.10.11 De diâmetro de núcleo inferior a 11 micrômetros (mícrons) Fibras ópticas - Fibras ópticas, feixes e cabos de fibras ópticas Fibras ópticas e feixes de fibras ópticas; cabos de fibras ópticas, exceto os da posição 85.44; matérias polarizantes em folhas ou em placas; lentes (incluindo as de contato), prismas, espelhos e outros elementos de óptica, de qualquer matéria, não montados, exceto os de vidro não trabalhado opticamente. <br> <strong>[&#39;6.0&#39; &#39;6.0&#39; &#39;6.0&#39; &#39;5.0&#39; &#39;5.0&#39;]</strong> <br> 5511.10.00 - De fibras sintéticas descontínuas, que contenham pelo menos 85 %, em peso, destas fibras Fios de fibras sintéticas ou artificiais, descontínuas (exceto linhas para costurar), acondicionados para venda a retalho. <br> <strong>[&#39;6.0&#39; &#39;6.0&#39; &#39;6.0&#39; &#39;5.0&#39; &#39;5.0&#39;]</strong> <br> 6001.22.00 -- De fibras sintéticas ou artificiais - Tecidos de anéis: Veludos e pelúcias (incluindo os tecidos denominados de “felpa longa” ou “pelo comprido”) e tecidos de anéis, de malha.</pre><pre>test = &quot;synthetic fiber fabrics knitted polyester patterned&quot; <br>matrizPontos explains = pontuaVetores <strong>_tfidf</strong> (test vocab, vetoresTEC, vetorVocab) <br>print (explains) <br>ind = 5 <br>if (ind&gt; matrizPontos.shape [1]): <br>ind = matrizPontos.shape [1] <br>print ( &quot;plus 5&quot;) <br>is in code (matrizPontos [0: ind]): <br>for line in (listaTECResumo): <br>codigo2 = line [10] <br>if (code == codigo2): <br>print (matrizPontos [ 1: ind]) <br>print (line) <br>&gt;&gt;&gt;&gt; <br>WOVEN FABRIC 569 839 sYNTHETIC FIBERS 54 281 74 polyester STAMPING 31 <br>5 plus: <br> <strong>[ &#39;1.5540693500933536&#39; 1.2670506868422255 &#39;1.2275553770539624&#39;<br>&quot;1.2042355691237416 &#39;1.1558503446987298&#39;]</strong> <br> 6006.34.20 Of polyesters - Printed - Of synthetic fibers: Other knitted fabrics. <br> <strong>[ &#39;1.5540693500933536&#39; 1.2670506868422255 &#39;1.2275553770539624&#39; <br>&#39;1.2042355691237416&#39; 1.1558503446987298 &#39;]</strong> <br> 6006.44.00 - Printed - of artificial fibers: Other knitted fabrics. <br> <strong>[ &#39;1.5540693500933536&#39; 1.2670506868422255 &#39;1.2275553770539624&#39; <br>&#39;1.2042355691237416&#39; 1.1558503446987298 &#39;]</strong> <br> 5516.94.00 - Printed - Other: Woven fabrics of staple fibers. <br> <strong>[ &#39;1.5540693500933536&#39; &#39;1.2670506868422255&#39; &#39;1.2275553770539624&#39; <br>&#39;1.2042355691237416&#39; &#39;1.1558503446987298&#39;</strong> <br>] 6006.34.90 Other - Printed - Of synthetic fibers: Other knitted fabrics.<br> <strong>[ &#39;1.5540693500933536&#39; 1.2670506868422255 &#39;1.2275553770539624&#39; <br>&#39;1.2042355691237416&#39; 1.1558503446987298 &#39;]</strong> <br> 6003.30.00 - of synthetic fiber mesh fabrics width not exceeding 30 cm, excluding the positions 6001 and 6002.</pre><p>Was implemented in the Java version a version of this algorithm showed better performance in our tests, Okapi BM25 + (the [+] more important is due to the high variance between the number of words in our collection documents). It is an interpolation parameter to reduce the penalty of short documents. Furthermore, let the ‘b’ parameter default BM25 in 60% instead of the standard 75%. ‘B’ is a linear interpolation parameter and also helps mitigate the penalty of short documents. The formula implemented using various parameters and hyper and minimized / eliminated draws the ranking.</p><p>To learn more about TF-IDF and BM25, there are great articles in Wikipedia:</p><ul><li><a href="https://pt.wikipedia.org/wiki/Tf%E2%80%93idf">Tf-idf - Wikipédia, a enciclopédia livre</a></li><li><a href="https://en.wikipedia.org/wiki/Okapi_BM25">Okapi BM25 - Wikipedia</a></li></ul><p>Another interesting solution would be to group similar words, treating plural, various modifications of the same word, etc: (Other, Other, another, stamped, embossed, printed, red, red, polyester, polyester …). Instead of working with the entire word in the vocabulary, we would try to work first with just your radical. Techniques for transforming words and decrease variations are called lemmatization and stemming. We could think of search dicionarizadas also applying a thesaurus and further diminishing our vocabulary. The stemming is applied to the Java version of the system, and dicionarizada search will be implemented in the near future.</p><p>An IPython notebook is available on GitHub for tests with stemming and lemmaizing using Python. A portuguese Stemmer is available inNLTK.</p><p><a href="http://www.nltk.org/howto/stem.html">Stemmers</a></p><pre>from nltk.stem import * <br> stemmer = SnowballStemmer(&quot;portuguese&quot;) <br> palavras = [&#39;TECIDOS&#39;, &#39;TECIDO&#39;, &#39;FIBRAS&#39;, &#39;FIBRA&#39;, &#39;SINTETICO&#39;, &#39;SINTETICA&#39;, &#39;OUTROS&#39;, &#39;OUTRAS&#39;, &#39;OUTRA&#39;] <br> stems = [stemmer.stem(palavra) for palavra in palavras] <br> print(&#39; &#39;.join(stems)) <br> lista = list (set(stems)) <br> print(lista) <br> &gt;&gt;&gt;&gt; <br> tec tec fibr fibr sintet sintet outr outr outr <br> [&#39;fibr&#39;, &#39;tec&#39;, &#39;sintet&#39;, &#39;outr&#39;]</pre><p>O código completo do script aqui demonstrado está disponível em</p><p><a href="https://github.com/IvanBrasilico/ClassificadorFiscal/blob/master/RanqueadorTEC.ipynb">IvanBrasilico/ClassificadorFiscal</a></p><p>To continue developing this work and implementing these solutions, certainly Python would be one of the best solutions currently available. However, due to the fact that, in my work, Python is not a widely adopted development language and I am currently involved in a large Java project, a project that even this Fiscal Classifier is part of, from this moment I converted the initial code in Python for Java + Swing. It was necessary to make some adaptations, because the initial version was using more than 1GB of RAM and I had to think about some optimizations that lowered the use of memory to less than 300MB. The code got bigger, the performance slightly lower, but the Java platform also has some facilities, especially in the design of interfaces, that ended up being useful.</p><p>The complete code (both Java and Python) is in my GitHub <a href="https://github.com/IvanBrasilico/">https://github.com/IvanBrasilico/</a></p><p>The Java version is already implementing BM25 + with parameters adjustment possibility, stemming, bigrams, among other improvements. I intend, as soon as possible, describe them and also implement them in Python version in Part 4 of this article.</p><h3>Part 3</h3><p><strong>And</strong> sta part is a brief manual to use the Java implementation of the system, available on GitHub.</p><p><a href="https://github.com/IvanBrasilico/">IvanBrasilico</a></p><p>This system uses search techniques and processing texts to a probability score.</p><p>The system runs fully embedded and can be used completely without access to networks, on any computers that have Java installed.</p><p>It was incorporated into the full-text system file for the last TEC published by the MDIC. When loaded, the system performs some pre-processing, which are to go all the text of the TEC and mount it in various structured forms, using artificial intelligence techniques and language processing (Vectorization words, TF-IDF, stemming, bigrams , among others).</p><p>The system offers seven tabs for research. Below describes each.</p><p>NCM Full tab <br>displays the text of the original TEC without preprocessing. <br> <strong>Button “Search Text”</strong> — search by word or part of them or just scroll the text. Important to remember that this tab the search is exact, case — sensitive and graphic signs (ex.:acentos) that is, “chapter”, “Chapter”, “Chapter” and “CHAPTER” are different searches. In TEC is spelled “Chapter”.</p><p>(This is the only tab is available for use immediately upon loading. The other tabbed must wait for the end preprocessing, which may take 1 to 2 minutes depending on the used computer)</p><p>NCM Search tab <br>Displays the TEC itself, hierarchical, only the text and code of subheadings to the subsection level with the final classification and alítquota of import duty. <br> <strong>Button “Search Code”</strong> -Search by code or part thereof.</p><p>Chapters and Sections tab <br>displays a list of chapters of the TEC. Select a chapter in the list displays your Notes</p><p>Suggestions tab <br>This tab is where it really is the use of algorithms “smart”. TEC displays the sub as a “complete” text, ie the text of subsection added to all higher-ranking positions. Moreover, the words of this sub-item scores that match the searched text according to the number of occurrences in the text. The result is sorted by score, from highest to lowest.</p><p>Position Feedback <br>This tab is identical to anterir but instead displays positions of subitems</p><p><strong>Button “Search Points”</strong> — Search for words, points, and displays the result in the “Suggestions” tab. <br>Parameters: <br>Using weighted weights TF / IDF (S / N) <br>Rather than simply counting the occurrences of the search terms in the TEC line, considers “weights” more scoring less frequent words in TEC and also the relative weight of one word on each line. <br>Plain text (S / N) <br>just looking for the word (s) (s) entered (s). Insensitive to box and graphic signs. <br>Stemming (S / N) <br>searches for words radicals. Stamped turns Estamp, Red turns TINT. <br>Bigrams (S / N)<br>just looking for the words entered. Insensitive to box and graphic signs. Just looking for the words in pairs, in the order entered. “Other fabrics”, “tissue”, “mesh”, etc.</p><p>Explanation Tab <br>Displays the search terms and some statistics. It lets you know if the words typed were found in TEC, and how often. Fits refinement and research correction. As an example, if researched “Tylenol”, this tab will not display statistics because the word does not exist in TEC. If you searched for “Paracetamol” information “PARACETAMOL appears. Total events: 3 “. Likewise, the search for “Embossed” return “STAMPING. Total Hits: 45 “. Have “Printed” without plural returns nothing.</p><p><strong>Example Screens</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*IxLDsWxvDbwsVgU06WFNzQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*W0AgAxVqWO3YU_bMKrFrzA.png" /></figure><p>Here, we started a simple search by typing only “other tissue” and clicking “Search score.” <br>Note that stopping the mouse pointer on a list item, a small window will open containing the line and every word found in the search line as well as the score of each word.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/1*Wdv6W5R5b-z81dRUaxW61Q.png" /></figure><p>In a second step, we begin to refine our search. Note that the words “fabric” and “red” and receive higher scores.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/1*BCHnrlaeMdYD4njNK-TXNw.png" /></figure><p>Adding the word “cotton” in the search</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GxetPny5s-saxj-L5YButQ.png" /></figure><p>Here, we select the “Explanation” tab to understand why each score. The score of each word will always be inversely proportional to its total occurrences.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HCP3wTZiu-SL_CZqwKUiuw.png" /></figure><p>Results looking at the tab “Position”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QS-IS5ZyumGzgC8m7BPy_g.png" /></figure><p>Modifying the search for other types of tissue:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5g8_b8ygb66usuwAEEP6JA.png" /></figure><p>You can use an exclamation point (!) Before the word searched. Thus, the score of this word will become negative and lines containing this word will go to the end of the list.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n5-ztObGPgA3rydAovri3A.png" /></figure><p>Below, the “NCM Complete” tab, where, in case of doubt, you can retrieve the full text of the TEC</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TD_4dSjmafOWZZZBkXk43g.png" /></figure><p>The Tab “Search NCM” displays the NCM hierarchically.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/941/1*VakgGtHp3FYzDNkXeNX3IQ.png" /></figure><p>The tab “chapters and notes” allow you to query each chapter, description and notes more conveniently and quickly</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*HC4AIwrg4v_FmwR4WdKSTg.png" /></figure><p>In the tab “Statistics chapter NCM” is available the percentage, by country of origin of Brazilian imports in each chapter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/1*NS-hDAZTdiPsT2ItoQ4UmQ.png" /></figure><p>The following screens show other research, results, stats and scores corresponding to demonstrate the possibilities of use</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BNfJ_l9XgnWaqDEY12Qt-Q.png" /></figure><p>A complex description, taken from a Report, displays the result desired in the third list. Note that the result is not primarily because this line, the words used in the TEC’s “Epoxy resins” used Award and “epoxy resin”. The stemming found the radicals, but the words “resin” and “epoxy” were not found. Not always stemming solve alone, so it’s important to look at the system return on the score of each line and refine the search.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wS4PmclQdJc3_gbfZAysJg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0KTNxpZNNiR1rPx7k9dTkQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CV6rl9kBtWXtnlAjq2oluQ.png" /></figure><p>An example of refinement: changing “washer” for “washers” or look for two terms. Remove the words “metal” and “metals” only plastic is desired.</p><p>In the case below, stemming also solve the search. Try various combinations until the desired sub-item be found on the first line can be more interesting than rolling several lines down.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sK6sakUKJ8AyoO14JnFeVA.png" /></figure><h3>Part 4</h3><p>Tthis part discuss alternative and / or complementary to the techniques already implemented.</p><p>The Java version has already implemented Stemmizaton, bigrams and unigrams in assembling the vocabulary, and was given the possibility of combining these methods when the ranking. Also it has also been implemented the possibility of combining with historical statistics NCM Country. Also the application of a thesaurus and stemming to reduce the vocabulary.</p><p>Other possibilities are the use of clustering, either by k-means or other method or by the hierarchy, scoring entire chapters and positions for example, indexes reversed Databases to allow a search for parts of words; Dimensionality reduction by PCA and the like, and then rank with regression trees, SVM or even common or recurrent neural networks.</p><p>In terms of using other data in the ranking, in addition to the country of origin NCM could generate estatísitcas to manufacturer, economic region, transport via a <em>trending</em> for approximate date, instead of statistics of several years.</p><p>All techniques can be combined with methods of “Ensembling” or simply multiplying the results. In the case of multiplication, a good practice would be before normalize the results. Example:</p><p>One approach to overcome the fact that some documents in the collection “listaTECResumo” are too short would create documents for positions in the same way that has been created for the sub-items and to rank the same way. Then multiply the score of position by the position of each sub-item. To treat equally regardless of the number of words, first normalize the resulting list of headings and sub dividing all scores lines for the highest scoring document score (thus the first position of the list would be 100%, the second a little less, etc.)</p><p>In addition to new scoring possibilities, product mix and <em>ensenblimg</em> , you can create test examples “Ground Truth” and then use machine learning to improve the parameters and / or find deficiencies in the methods already implemented by using valuation techniques of precision and recall F-score, applying the weighted ranking evaluation (evaluation Methodology Cranfield / weighted average precision and recall).</p><p>Once tests and improvements are carried out with some of these alternatives will be available on GitHub and discussed in this article.</p><h3>References</h3><ul><li><a href="http://dl.acm.org/citation.cfm?id=2915031">Text Data Management and Analysis: A Practical Introduction to Information Retrieval and Text Mining</a></li><li><a href="http://www.cambridge.org/catalogue/catalogue.asp?isbn=0521865719">Introduction to Information Retrieval - Cambridge University Press</a></li><li><a href="http://www.springer.com/la/book/9783642142666">Learning to Rank for Information Retrieval | Tie-Yan Liu | Springer</a></li><li><a href="https://www.coursera.org/learn/text-mining">Text Mining and Analytics | Coursera</a></li><li><a href="https://www.coursera.org/learn/text-retrieval/">Text Retrieval and Search Engines | Coursera</a></li><li><a href="https://www.udacity.com/course/intro-to-machine-learning--ud120">Introduction to Machine Learning | Udacity Free Courses</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d903fa3cf948" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/use-of-text-retrieval-and-search-engines-technology-for-tax-classification-d903fa3cf948">Use of Text Retrieval and Search Engines technology for tax classification</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Collections in a Flask — Part4 —The UI]]></title>
            <link>https://brasilico-ivan.medium.com/collections-in-a-flask-part4-the-ui-b0741ddf1dec?source=rss-642d583ec032------2</link>
            <guid isPermaLink="false">https://medium.com/p/b0741ddf1dec</guid>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Ivan Brasilico]]></dc:creator>
            <pubDate>Wed, 20 Sep 2017 23:33:19 GMT</pubDate>
            <atom:updated>2017-09-20T23:33:19.362Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Building a microservice Web2.0 Application from zero while learning and practicing HTML/Bootstrap/JQuery/Flask, NLP and Information Retrieval</blockquote><p>In this series of articles, I will show a hands on tutorial on the stack HTML/CSS (Bootstrap)/JavaScript (JQuery/JQueryui/Bootstrap components) /Flask/Python full web app with option to serve all HTML in static way. This Part talks about the User Interface:</p><p>5. The old-way interface: a simple search</p><p>6. Test again, debuging on browser and converting to JQuery/JSON</p><h3>A Simple Search</h3><p>We tested the model, the manager, the spell checker with some automated tests and with a simple command line interface. Now we want to make an interface to let common users use the methods we have build.</p><p>We will begin with a simple HTML page and Flask for doing the back-end work. Analysing ou interface in an MVC (Model, View, Controller) way, our Model is the classes we made in Part 2 and Part 3. The View will be a HTML Page, and the Controller will be built on Flask.</p><p>Flask has an amazing documentation, and the beggining of our User Interface will use the Quickstart Flash page guidelines.</p><p><a href="http://flask.pocoo.org/docs/0.12/quickstart/">Quickstart - Flask Documentation (0.12)</a></p><p>First, we can take a look in the rank method that we wrote and tested before:</p><pre>def bm25(self, words, k=1.4, b=0.75):<br>        (...)<br>        for docid, doc in docs.items():<br>            alist.append({&#39;score&#39;: score[docid],<br>                          &#39;title&#39;: doc.title,<br>                          &#39;contents&#39;: doc.contents})<br>        return sorted(alist, key=lambda rank: rank[&#39;score&#39;], reverse=True)</pre><p>The method expects a list of words and returns a list of dicts. So, ou HTML page should have an Input Text for the parameter words, and a Table to render our list of dicts. In Jinja templates, used by Flask, it will be like this:</p><pre>&lt;h1&gt;Simple Table Example&lt;/h1&gt;<br>&lt;p&gt;<br>&lt;form&gt;<br>  &lt;input type=&quot;text&quot; size=&quot;50&quot; name=&quot;words&quot; id=&quot;words&quot; /&gt;<br>  &lt;input type=&quot;submit&quot; /&gt;<br>  &lt;/form&gt;<br>&lt;table id=&quot;records_table&quot; border=&#39;1&#39;&gt;<br>&lt;thead&gt;<br>    &lt;tr&gt;<br>        &lt;th&gt;Score&lt;/th&gt;<br>        &lt;th&gt;Subitem&lt;/th&gt;<br>        &lt;th&gt;Descrição completa&lt;/th&gt;<br>    &lt;/tr&gt;<br>&lt;/thead&gt;<br>&lt;tbody&gt;<br>{% for line in result %}<br>&lt;tr&gt;<br>&lt;td&gt;{{line.score}}&lt;/td&gt;<br>&lt;td&gt;{{line.title}}&lt;/td&gt;<br>&lt;td&gt;{{line.contents}}&lt;/td&gt;<br>&lt;/tr&gt;<br>{% endfor %}<br>&lt;/tbody&gt;<br>&lt;/table&gt;</pre><p>Most of the above is simply HTML, except from the code into “{ }”. In Jinja templates, {% command %} defines special commands or blocks. We can use, as exemplified above, for statements just like in python, to iterate over a list. And when we use {{name}} Jinja will replace this content with the content in the variable with ‘name’, if the variable exists.</p><p>Finally, our Flask app, to serve the page and route the requests:</p><pre>from flask import Flask, render_template, request<br>from sqlalchemy.orm import sessionmaker<br>from models.models import engine<br>from models.models import Collection<br>from models.collectionmanager import CollectionManager</pre><pre>app = Flask(__name__, static_url_path=&#39;/static&#39;)</pre><pre>Session = sessionmaker(bind=engine)<br>session = Session()</pre><pre><a href="http://twitter.com/app">@app</a>.route(&#39;/ranktable/&#39;)<br>def ranktable():<br>    &quot;&quot;&quot;Get words, return ranked results&quot;&quot;&quot;<br>    words = request.args.get(&#39;words&#39;, &#39;&#39;, type=str)<br>    result = []<br>    if words and isinstance(words, str):<br>        collection = session.query(Collection).filter_by(<br>                                               id=1).one()<br>        manager = CollectionManager(session, collection)<br>        result = manager.bm25(words)<br>    return render_template(&#39;ranktable.html&#39;, result=result)</pre><pre>if __name__ == &#39;__main__&#39;:<br>    app.run() </pre><p>Session is from SQLAlchemy, and creates the connection with DataBase. app = Flask() creates the Flask object that will act as our web server. The @app.route is a “decorator”, an easy way to tell Flask that this function will be mapped to the url provided. The function ‘ranktable’ use another Flask shortcut, the request function, that stores for us the parameters passed with the call to the url, to see if the ‘words’ parameter was passed. Is if was provided, then we call our bm25 function, and passes the resulting list to Jinja process our HTML template, using Flask render_template function.</p><p>That is it! As simple as it can be, we built a View/User Interface, registered a URL to access it on our “Controller”, made the bindings between UI and the model, and returned a HTML response. So we can finally test it:</p><pre>&gt;&gt;&gt;python webapp.py<br>* Running on <a href="http://127.0.0.1:5000/">http://127.0.0.1:5000/</a> (Press CTRL+C to quit)</pre><p>Open a web browser and point it to <a href="http://127.0.0.1:5000/">http://127.0.0.1:5000/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*l7yBIyyH5vBJO6sQNUMWDA.png" /><figcaption>Our application comes alive!</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*Zk-6LqhD8l9071wo5937hw.jpeg" /><figcaption>Success! Time for making a toast!</figcaption></figure><p>Python has a bunch of web frameworks: Tornado, TurboGears, Django, Flask, and others. Each of them with strenghtness and weakness. All of them share the pythonic way: simple, ease to use, yet powerfull. Flask is specially built for modularity and extensiveness. It is a “micro” framework, uses the Werkzeug WSGI toolkit/web server and Jinja templates, and has extensions/easy integrations with a lot of common web and Python technologies. And, as we said, it is a kind of magic how we can quick develop a web application.</p><p>Of course, for putting our app in production, we would need to make more validation on the data entered for security concerns, and we would use some web server, like Apache, integrated into our Application. Since Flask is 100% WSGI compatible, integrating our application with Apache is very quick and easy, and I will show this configuration in a future article.</p><p>For now, the focus is on web development, so we will convert our simple app in an AJAX/JSON app.</p><blockquote><strong><em>TIP</em></strong>: JavaScript/CSS/HTML, although their growth in popularity in last years, can really be annoying for the developer. If you make a typo, forget some closing bracket, any ‘{‘ or ‘}’ or ‘&lt;’ or ‘&gt;’ or ‘/’ out of place, or simply forget to close a div or other element, strange things will happen. Or, worse, nothing will happen. A HTML/JavaScript who validates all this kind of things would be amazing. If any reader knows an editor that does it, please let me know!</blockquote><blockquote><strong><em>TIP2</em></strong>: When importing JavaScript, order matters! So, if you are using some library like Jqueryui or bootstrap.js, make sure you are importing then in the right order (in this case, jquery first, bootstrap second and jqueryui last). If not, no error will be shown, but when trying to use a component the console will complains “function not found”</blockquote><blockquote><strong>TIP3:</strong> This article is about Flask, Python, NLP, Web Development, and putting it all together. If you want to learn more about HTML, CSS, JavaScript and JQuery, freecodecamp and W3Schools are great.</blockquote><p>That said, Chrome and Firefox have great JavaScript/HTML/CSS Consoles. Just type F12 on Chrome to access it. Also, when writing JavaScript, console.log() can be your best friend. It is the equivalent of print() on Python and System.out.print() on Java. Don’t be afraid using it, just remember to delete the console.log() lines once the work is done.</p><p>Back on our application, we will use some JQuery commands to dinamically mount our table on the Client Side, so the browser will not have to reload and render all the page every request we make. This can reduce the network traffic and boost the application performance. Specially for cell phones, the user will perceive the application behave much more like a native app then just an internet web page.</p><p>So let’s modify our HTML/Jinja template to the JQuery version:</p><pre>{% block body %}</pre><pre>&lt;h1&gt;Simple Table JQuery Example&lt;/h1&gt;<br>&lt;p&gt;<br>  &lt;input type=&quot;text&quot; size=&quot;50&quot; name=&quot;words&quot; id=&quot;words&quot; /&gt;<br>  &lt;button id=&quot;btnrank&quot; type=&quot;button&quot;&gt;Rank!<br>                          &lt;/button&gt;</pre><pre>&lt;/p&gt;<br>&lt;table id=&quot;records_table&quot; border=&#39;1&#39;&gt;<br>&lt;thead&gt;<br>    &lt;tr&gt;<br>        &lt;th&gt;Score&lt;/th&gt;<br>        &lt;th&gt;Subitem&lt;/th&gt;<br>        &lt;th&gt;Descrição completa&lt;/th&gt;<br>    &lt;/tr&gt;<br>&lt;/thead&gt;<br>&lt;tbody&gt;<br>&lt;/tbody&gt;<br>&lt;/table&gt;</pre><pre>&lt;script src=&quot;/static/js/jquery.js&quot;&gt;&lt;/script&gt;<br>&lt;script type=&quot;text/javascript&quot;&gt;<br>  $(function() {<br>    var submit_form = function(e) {<br>      $.getJSON(&#39;/_mockrank&#39;, {<br>        words: $(&#39;input[name=&quot;words&quot;]&#39;).val(),<br>      }, function(data) {<br>        console.log(data);<br>        $(&#39;#records_table tbody tr&#39;).remove();<br>       $.each(data, function(i, item) {<br>        $(&#39;&lt;tr&gt;&#39;).append(<br>            $(&#39;&lt;td&gt;&#39;).text(item.score),<br>            $(&#39;&lt;td&gt;&#39;).text(item.title),<br>            $(&#39;&lt;td&gt;&#39;).text(item.contents)<br>        ).appendTo(&#39;#records_table&#39;);<br>        });<br>       $(&#39;input[name=&quot;words&quot;]&#39;).focus().select();<br>      });<br>      return false;<br>    };<br>    $(&#39;button#btnrank&#39;).bind(&#39;click&#39;, submit_form);<br>    $(&#39;input[type=&quot;text&quot;]&#39;).bind(&#39;keydown&#39;, function(e) {<br>      if (e.keyCode == 13) {<br>        submit_form(e);<br>      }<br>    });<br>    $(&#39;input[name=&quot;words&quot;]&#39;).focus();<br>  });<br>&lt;/script&gt;</pre><pre>{% endblock %}</pre><p>What have we done? Basically we removed the for statement that Jinja was using to mount our table AND we excluded the form, since we will not submit it, but will use JavaScript instead. Also, we included our JQuery code:</p><p>$(function() is the JQuery mode of defining our code.</p><p>We are defining a new function called ‘submit_form’. This function calls $.getJSON JQuery builtin function, passing a parameter “words= $(‘input[name=”words”]’).val()”. $(‘input[name=”words”]’).val() means “JavaScript, find an input element on HTML whose atribute ‘name’ is equal to ‘words’ and take its value”. The returning value of $.getJSON will be stored on ‘data’ variable.</p><p>Then, we print data value to console, for debugging purposes, and the next commands find the “#records_table” table, cleans it tbody trs, and iterates over data remouting “#records_table” “&lt;tr&gt;” and “&lt;td&gt;”.</p><p>The last lines just put focus on our input as default, binds the pressing of “Enter” and the pushing of our button to call the “submit_form” function.</p><p>Let’s restart the app, reload the page and press F12 to see our console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*wXlIXQQ-PvyMK7DEB5LSNw.png" /><figcaption>allThe console caught an error! What is error 404??</figcaption></figure><p>After pressing the “Rank!” button, we got an error 404? What is this? The “page” we are looking for was not found. Of course, we are not submitting the form to ranktable.html. We are trying to do a GET request in /_rank. This routing was not defined on our Flask app.</p><p>For now, we will do a MOCK function. A Mock function is a fake function that acts as designed, but is a simple simulation. It allows fast testing without having to wait for slow processes or dealing with DataBases. So we can do a simple test isolating what we want to test from other modules. Add to webapp.py:</p><pre><a href="http://twitter.com/app">@app</a>.route(&#39;/_mockrank&#39;)<br>def mockrank():<br>    return jsonify({&#39;score&#39;: &#39;10&#39;,<br>                    &#39;title&#39;: &#39;Mock 1&#39;,<br>                    &#39;contents&#39;: &#39;Testing is good! Mock isolates things&#39;},<br>                   {&#39;score&#39;: &#39;8,5&#39;,<br>                    &#39;title&#39;: &#39;Mock 2&#39;,<br>                    &#39;contents&#39;: &#39;Mocks can be your friends&#39;})</pre><p>Restart webapp.py, reload the page, click “Rank!”, open the console. Voi lá!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4NCv0iXoTnGBHLBqAN3BRA.png" /><figcaption>Now it works, and we can see our dict (or JSON) in the console, and a beautiful magic appearing table on HTML</figcaption></figure><p>Adapting the ranktable function to return a json is straightforward. Just replace return render_template(..) with return jsonify(result). Also modify the JQuery $.getJSON to point to our new URL.</p><pre><a href="http://twitter.com/app">@app</a>.route(&#39;/_rankjson&#39;)<br>def rankjson():<br>    &quot;&quot;&quot;Get words, return ranked results&quot;&quot;&quot;<br>    words = request.args.get(&#39;words&#39;, &#39;&#39;, type=str)<br>    result = []<br>    if words and isinstance(words, str):<br>        collection = session.query(Collection).filter_by(<br>                                               id=1).one()<br>        manager = CollectionManager(session, collection)<br>        result = manager.bm25(words)<br>    <strong>return jsonify(result)</strong></pre><pre>(...) <br>on HTML:<br>  $.getJSON(&#39;/<strong>_rankjson</strong>&#39;, {</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lZAcktkfxbjTdeAOLtecdg.png" /><figcaption>Gotcha!</figcaption></figure><p>That’s it!. Now we moved our web application from the 90’s to 2017. We have a full stack web app. Our HTML code is now an application by itself, that makes requests for another application (our Flask Server) that provides a JSON web service. We started to decompose our monolith into micro-services. With this architectural choice, we achieved great decoupling from the layers of our app. We can even produce a static HTML and publish it on a separate server.</p><p>Our application got alive in a lightning, but is still a bit ugly, just like Dr. Victor creation. Also it lacks a lot of functions that we planned. In the next articles, we will see how to use BootStrap and JQueryui to beautify the User Interface and also provide a smooth user experience, with autocomplete fields, navigation bars, tabs, and so on. We will move all HTML to a single page responsive application that will be served statically by a fast lightweight server like nginx. We will see Flask “magic” extensions, like CORS, Freeze, Bootstrap, that will help us a lot. The finished application is on GitHub, if you want to take a look and don’t bother about spoilers. Stay on!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b0741ddf1dec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Collections in a Flask]]></title>
            <link>https://brasilico-ivan.medium.com/collections-in-a-flask-7605662547f0?source=rss-642d583ec032------2</link>
            <guid isPermaLink="false">https://medium.com/p/7605662547f0</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[jquery]]></category>
            <category><![CDATA[bootstrap]]></category>
            <dc:creator><![CDATA[Ivan Brasilico]]></dc:creator>
            <pubDate>Sat, 16 Sep 2017 02:09:36 GMT</pubDate>
            <atom:updated>2017-10-02T10:50:50.271Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Building a microservice Web2.0 Application from zero while learning and practicing HTML/Bootstrap/JQuery/Flask, NLP and Information Retrieval</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7EKSApRPKeZxqm8vXQSfRg.jpeg" /><figcaption>Sometimes you may need help to find what you want in a sea of information.</figcaption></figure><p>In this article, I will show a hands on tutorial on the stack HTML/CSS (Bootstrap)/JavaScript (JQuery/JQueryui/Bootstrap components) /Flask/Python full web app with option to serve all HTML in static way.</p><p>On my previous article, I applied some NLP concepts, like Bag of Words, Stemming, TF-IDF, to a search/categorization problem on a specific Text(A Brazilian law/legal standard called “TEC”). In fact, the used techniques can be applied to any “Collection of Documents” which you need to classify or search. Even if it is only one archive, like the cited“TEC”, some parts, like lines, sections or paragraphs may be considered, for your needs, “documents”, and the entire document will be your “collection”. The concepts of “collections”, “documents”, “tokens”, and others, for NLP tasks, were discussed in the previous article and if you don’t feel comfortable with them you may want to read the previous article before this.</p><p>I also developed some Python scripts and an IPython notebook to illustrate, practice and test the concepts, and an entire Java/Swing Application, all available on my GitHub account:</p><p><a href="https://github.com/IvanBrasilico/ClassificadorFiscal">IvanBrasilico/ClassificadorFiscal</a></p><p>Now, I want to develop a more generic Application, that will store the collection in a database. I also would like to make a WEB2.0 Application, and put some MicroService architectural approach on this. After some research and some reading, specially the excellent PacktPub book “Python Microservices Development” from Tarek Ziadé, I choose to go on Flask. Also, I got to freecodecamp and other refs and decided to do the FrontEnd by the BootStrap/JQuery Stack and finally learn this stuff.</p><p><a href="https://www.packtpub.com/web-development/python-microservices-development">Python Microservices Development | PACKT Books</a></p><p>First things first, I got to Flask home page and saw they use SQLAlchemy for ORM Persistance. So, another lib to learn… No problem, like most of Python libraries, easy to install, and with a soft learning curve.</p><p>In the next lines, I will explain all the steps I got through the construction of the application. If you are like me, inpatient, the app is full and functional, published on GitHub. You can clone the repo and run by yourself. You can also go to my website and try a live version.</p><p><a href="https://github.com/IvanBrasilico/FlaskTFIDF">IvanBrasilico/FlaskTFIDF</a></p><p><a href="http://brasilico.pythonanywhere.com/collectionmanager.html">http://brasilico.pythonanywhere.com/collectionmanager.html</a></p><p>I am a big fan of the KISS principle, so I will always try to be as simple as possible when first building new stuff, and I also try to separate every concept and every domain, test and understand one part before going to another, do all the construction like a LEGO build.</p><p>One question that a reader can make is why do not use a library like ElasticSearch for the backend, a framework that provides optimized searching and indexing algorithms. The answer is that I wanted to make something clean and simple first, totally controlled and implement only a few algorithms, like spell correction and BM25. So I can first quickly develop the fully functional application, make proof of some concepts, dilute the initial complexity, and then after this, as soon as I can I will certainly make some tests using ElasticSearch or other framework as the backend of the application. So, in resume, here is the map of our journey:</p><ol><li>The Model — SQLAlchemy</li><li>Testing the model</li><li>The CollectionManager — some common operations, tokenizing, filtering, ranked search(BM 25+), spell checking</li><li>Feeding a collection and testing all stuff together</li><li>The old-way interface: a simple search</li><li>Test again, debuging on browser and converting to JQuery/JSON</li><li>The desired interface: autocomplete, dynamic table, JSON, JSON, +JSON. And some Flask Magic.</li><li>Freeze!!! Magically producing static files</li><li>Polishing the final frontend</li><li>NGINX configuration and gluing all</li><li>ElasticSearch as backend</li></ol><h3><a href="https://medium.com/@brasilico.ivan/collections-in-a-flask-part-2-eb5519fc9435">Click here to read Part 2</a></h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7605662547f0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Collections in a Flask — Part 3 — The Manager]]></title>
            <link>https://brasilico-ivan.medium.com/collections-in-a-flask-part-3-690bd8dbf840?source=rss-642d583ec032------2</link>
            <guid isPermaLink="false">https://medium.com/p/690bd8dbf840</guid>
            <category><![CDATA[search-engines]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[information-technology]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Ivan Brasilico]]></dc:creator>
            <pubDate>Sat, 16 Sep 2017 02:07:14 GMT</pubDate>
            <atom:updated>2017-09-20T23:34:36.543Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Building a microservice Web2.0 Application from zero while learning and practicing HTML/Bootstrap/JQuery/Flask, NLP and Information Retrieval</blockquote><p>In this series of articles, I will show a hands on tutorial on the stack HTML/CSS (Bootstrap)/JavaScript (JQuery/JQueryui/Bootstrap components) /Flask/Python full web app with option to serve all HTML in static way. This Part talks about the Core Classes and some algorithms for text retrieval.</p><p>3. The CollectionManager — some common operations, tokenizing, filtering, ranked search(BM 25+), spell checking</p><p>4 . Feeding a collection and testing all stuff together</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*1-70nsD9mzTrZrTF.jpg" /><figcaption>Take a close look</figcaption></figure><h3>The Collection Manager</h3><p>We build our model on previous part. But we need to add some intelligence to the model, not just store the data. So we will build a class to store that methods and wrap from and to the data of the model. For now, this class will be called “Collection Manager”.</p><pre>class CollectionManager():<br>    &quot;&quot;&quot;Manager for a collection. Unique interface for the model classes<br>    and provides methods for processing docs to index the collection&quot;&quot;&quot;<br>    def __init__(self, psession, pcollection=None):<br>        self.session = psession<br>        self.my_collection = pcollection</pre><p>The “CollectionManager” will provide common methods for managing a collection of documents. This includes inserting documents, mounting bag of words statistics, retrieving tf_idf parameters, retrieving vocabulary search/spell correction and so on. Stay in mind that only “Collections” and “Documents” are Model Classes in the common way. Words and Word_Occurrence are just statistics of the two previous classes. Words is our collection vocabulary, and Word_Occurrence our bag of words. So the application will not interact direct with the model, but with the manager.</p><pre>def add_document(self, ptitle, pcontent):<br>        &quot;&quot;&quot;Receives title and content and adds a document<br>        to Database related to the Collection already set&quot;&quot;&quot;<br>        one_document = Document(self.my_collection,<br>                                ptitle, pcontent)<br>        self.session.add(one_document)<br>        return one_document</pre><pre>def add_document_and_proccess(self, ptitle, pcontent, ptokenizer):<br>        &quot;&quot;&quot;Receives title and content and adds a document<br>        to Database related to the Collection already set,<br>        also calls the process method&quot;&quot;&quot;<br>        document = self.add_document(ptitle, pcontent)<br>        self.process(document, ptokenizer)</pre><p>What is “processing” a document? When a document is added to a Collection, we need to “index” it. Normally, we will extract tokens from the document and build an inverted index (that will be stored on word_occurrences). Tokens are simply the unity we choose. On majority of times, tokes will be words, and our tokenizer function, defined as a parameter, will do a split, like the example function bellow for Portuguese text:</p><pre>import nltk<br>import re<br>from unicodedata import normalize<br>import os</pre><pre>stopwords = nltk.corpus.stopwords.words(&#39;portuguese&#39;)</pre><pre>def remover_acentos(txt):<br>    return normalize(&#39;NFKD&#39;, txt).encode(<br>                     &#39;ASCII&#39;, &#39;ignore&#39;).decode(&#39;ASCII&#39;)</pre><pre>def somente_letras_e_numeros(raw):<br>    raw = remover_acentos(raw)<br>    clean = re.sub(&quot;[^a-zA-Z0-9]&quot;, &quot; &quot;, raw)<br>    return clean</pre><pre>def tokenize_to_words(sentence, splitter=&quot; &quot;):<br>    &quot;&quot;&quot;Generator of words tokens<br>    Usage: for word in tokenize_to_words(&quot;Tinha uma pedra no meio do caminho&quot;, &quot; &quot;):<br>               do something<br>    &quot;&quot;&quot;<br>    listofwords = sentence.split(splitter)<br>    result = []<br>    for word in listofwords:<br>        if ((len(word) &gt; 3) and (stopwords.count(word) == 0)):<br>            word = somente_letras_e_numeros(word)  # Tira tudo que não for A-B e 0-9<br>            word = word.strip().lower()<br>            result.append(word)<br>    return result</pre><p>If the code above and concepts like tokens, stopwords, text normalizing, tec, looks new or weird for you, please refer to my previous article:</p><p><a href="https://medium.com/@brasilico.ivan/utiliza%C3%A7%C3%A3o-das-t%C3%A9cnicas-de-recupera%C3%A7%C3%A3o-e-ranqueamento-de-texto-e-t%C3%A9cnicas-de-ia-para-aux%C3%ADlio-25d047d4fe06">Utilização de tecnologia de Recuperação e Ranqueamento de Texto classificação fiscal</a></p><p>And finally here is the code to “process” the document and populate ‘words’ and ‘word_occurrences’ tables:</p><pre>def process(self, pdocument, ptokenizer):<br>        &quot;&quot;&quot; Receives a word token generator and process the document with<br>        the received function. Adds receiver words to collection for<br>        statistical analysis<br>        &quot;&quot;&quot;<br>        wordmodellist = []<br>        wordlist = ptokenizer(pdocument.contents)<br>        doclength = len(wordlist)     # Could be calculated on demand from wo<br>        pdocument.length = doclength  # Store for better performance<br>        for aword in wordlist:<br>            # TODO: See best aproach to make unique words (Ignore DBERROR? SEARCH? MEMORY SET?)<br>            one_word = self.session.query(Word).filter_by(atoken=aword).first()<br>            if not one_word:<br>                one_word = Word(aword)<br>                self.session.add(one_word)<br>            wordmodellist.append(one_word)<br>        self.session.commit()</pre><pre>position = 0<br>        for one_word in wordmodellist:<br>            one_occurrence = WordOccurrence(one_word.id, pdocument.id, position)<br>            self.session.add(one_occurrence)<br>            position += 1<br>        self.session.commit()</pre><p>The code is pretty self explanatory. The document is tokenized into words, the words are searched to retrieve the word index. If word is new, it is added. Finally, word_occurrence is registered on table. The table will function like a Frequency Bag of Words. If the purpose isn’t all clear now, in the end of article we will feed a collection into the Database to see how it works.</p><p>We also implement at least one function to do the ranked search. We will implement the BM25 ranking function. The BM25 ranking function applies some heuristics to TF-IDF, has been shown to achieve great results in ranking documents. The article in wikipedia about BM25 is great and explains the function and its variations in details. TF is the acronym for Term Frequency. In our context, it is the count of occurrences of the word searched in each document. IDF stands for Inverse Document Frequency and is about penalizing common words and weighting high rare words. It is a logarithm function of the quantity of documents in the collection that the word occurs. Let’s see the code.</p><pre>def bm25(self, words, k=1.4, b=0.75):<br>        &quot;&quot;&quot;Okapi BM25 implementation&quot;&quot;&quot;<br>        C = self.collection_lenght()<br>        avgdl = self.avg_dl()<br>        score = Counter()<br>        docs = {}<br>        words = words.split(&quot; &quot;)<br>        for word in words:<br>            word = word.strip()<br>            docs = self.tf(word)<br>            ndocs = len(docs)<br>            idf = math.log((C - ndocs + 0.5) / (ndocs + 0.5))<br>            for docid, tf in docs.items():<br>                adocument = self.session.query(Document).filter_by(id=docid).one()<br>                D = adocument.length<br>                rank = idf * ((tf * (k+1)) / (tf + k + ((1 - b) + (b * D/avgdl))))<br>                score[docid] += rank<br>                docs[docid] = adocument<br>        alist = []<br>        for docid, doc in docs.items():<br>            alist.append({&#39;score&#39;: score[docid],<br>                          &#39;title&#39;: doc.title,<br>                          &#39;contents&#39;: doc.contents})<br>        return sorted(alist, key=lambda rank: rank[&#39;score&#39;], reverse=True)</pre><p>Also, in the Java Application we implemented a thesaurus, plural checking, stemmization, showed statistics about the occurrences of the words searched, all methods to try to help the searcher. This time, the implementation will use a different approach: we will do a spell check to do immediate feedback. This idea came from the amazing book “Text Analytics with Python”.</p><p>Explaining the idea: A user begins to type a word. We then search the vocabs for all the words beginning with the first letter of the word the user is typing and show a list of this available words. As the user goes typing, we continue to filter this list, but with some tolerance for typos (we assume that just the first word is right, and the user can have made a typo in two letters). Then the user will never be searching for words that are not in the vocab, and has immediate info about use of plurals and flexion of the same word in the vocab. Since there is no perfect algorithm for lemmatization and stemmization, maybe this feature can do a better work for users of our search.</p><pre># -*- coding: utf-8 -*-<br>&quot;&quot;&quot;<br>Created on Mon Aug 01 03:35:05 2016</pre><pre><a href="http://twitter.com/author">@author</a>: IvanBrasilico<br>Adapted from Peter Novig Algorithm exemplified on Dipajan Sarkar Text Analytics book</pre><pre>&quot;&quot;&quot;<br>import re</pre><pre>def tokens(text):<br>    &quot;&quot;&quot;<br>    Get all words from the corpus<br>    &quot;&quot;&quot;<br>    return re.findall(&#39;[a-z]+&#39;, text.lower())</pre><pre>def known(words, vocab):<br>    &quot;&quot;&quot;<br>    Return the subset of words that are actually<br>    in our WORD_COUNTS dictionary.<br>    &quot;&quot;&quot;<br>    return {w for w in words if w in vocab}</pre><pre>def edits0(word):<br>    &quot;&quot;&quot;<br>    Return all strings that are zero edits away<br>    from the input word (i.e., the word itself).<br>    &quot;&quot;&quot;<br>    return {word}</pre><pre>def edits1(word):<br>    &quot;&quot;&quot;<br>    Return all strings that are one edit away<br>    from the input word.<br>    &quot;&quot;&quot;<br>    alphabet = &#39;abcdefghijklmnopqrstuvwxyz&#39;<br>    def splits(word):<br>        &quot;&quot;&quot;<br>        Return a list of all possible (first, rest) pairs<br>        that the input word is made of.<br>        &quot;&quot;&quot;<br>        return [(word[:i], word[i:])<br>                for i in range(len(word)+1)]</pre><pre>pairs      = splits(word)<br>    deletes    = [a+b[1:]           for (a, b) in pairs if b]<br>    transposes = [a+b[1]+b[0]+b[2:] for (a, b) in pairs if len(b) &gt; 1]<br>    replaces   = [a+c+b[1:]         for (a, b) in pairs for c in alphabet if b]<br>    inserts    = [a+c+b             for (a, b) in pairs for c in alphabet]<br>    return set(deletes + transposes + replaces + inserts)</pre><pre>def edits2(word):<br>    &quot;&quot;&quot;Return all strings that are two edits away<br>    from the input word.<br>    &quot;&quot;&quot;<br>    return {e2 for e1 in edits1(word) for e2 in edits1(e1)}</pre><pre>def correct(word, vocab):<br>    &quot;&quot;&quot;<br>    Get the best correct spelling for the input word<br>    &quot;&quot;&quot;<br>    # Priority is for edit distance 0, then 1, then 2<br>    # else defaults to the input word itself.<br>    word = word[0:7] ##Limita a oito caracteres. <br>                     ##Mais do que isso a busca é muito custosa<br>    candidates = (known(edits0(word), vocab) and<br>                  known(edits1(word), vocab) or<br>                  known(edits2(word), vocab) or<br>                  [word])<br>    return candidates</pre><pre>def correct_match(match, vocab):<br>    &quot;&quot;&quot;<br>    Spell-correct word in match,<br>    and preserve proper upper/lower/title case.<br>    &quot;&quot;&quot;</pre><pre>word = match.group()<br>    def case_of(text):<br>        &quot;&quot;&quot;<br>        Return the case-function appropriate<br>        for text: upper, lower, title, or just str.:<br>            &quot;&quot;&quot;<br>        return (str.upper if text.isupper() else<br>                str.lower if text.islower() else<br>                str.title if text.istitle() else<br>                str)<br>    return case_of(word)(correct(word.lower(), vocab))</pre><pre>def correct_text_generic(text):<br>    &quot;&quot;&quot;<br>    Correct all the words within a text,<br>    returning the corrected text.<br>    &quot;&quot;&quot;<br>    return re.sub(&#39;[a-zA-Z]+&#39;, correct_match, text)</pre><h3>Feeding a collection</h3><p>To test the Manager, we need two stages: 1. Feed a Collection 2. Do some search.</p><p>We can use the TEC Collection from the last article. Taking the raw data and feeding a collection is about some heuristics and manual work. Depending on the data you want to feed and how you want to organize it, you will need to make some analysis and code a script. It does not matter what algorithm, what database, what technology you are using later: this pre-processing step is the human component of the system, needs human decisions and analytics to mount the collection, and this stage is what will be the most important for the final effectiveness of the search system. This stage is about WHAT and WHY you are searching. The later implementations are about HOW. As Seneca said, ““If a man knows not to which port he sails, no wind is favorable.”</p><pre>def montaTEC():<br>    arq = open(os.path.dirname(__file__)+&quot;/tec.txt&quot;)<br>    listaarquivoTEC = arq.readlines()<br>    return listaarquivoTEC<br>def montaNCM(plistaTEC):<br>    listaNCM = []<br>    r = 0<br>    while r &lt; len(plistaTEC):<br>        linha = plistaTEC[r]<br>        if len(linha) &lt; 12:<br>            i = linha.find(&quot;.&quot;)<br>            if ((i &gt;= 2) and (linha[0].isnumeric())):<br>                r = r + 1<br>                linha2 = plistaTEC[r]<br>                # Elimina as sequências de números (na parte 5 Regra de<br>                # Tributação para Produtos do Setor Aeronáutico da TEC)<br>                # Primeiro testa se linha não está vazia, depois, se é número<br>                if (not linha2 == &quot;\n&quot;):<br>                    if (not linha2[0].isnumeric()):<br>                        ncm = linha<br>                        descricao = linha2<br>                        linha3 = plistaTEC[r+1]<br>                        tec = &quot;&quot;<br>                        if ((not linha3) or (linha3[0].isnumeric())):<br>                            r = r + 1<br>                            tec = linha3<br>                        listaNCM.append([ncm.strip(),<br>                                         descricao.strip(), tec.strip()])<br>        r = r + 1<br>    return listaNCM</pre><pre>def montaTECResumo(plistaNCM):<br>    &quot;&quot;&quot; Monta linhas da TEC que contém II com descrição contendo a<br>    concatenação da descrição da linha e dos &quot;pais&quot;<br>    - posições, subposições, etc.&quot;&quot;&quot;<br>    listaTECResumo = []<br>    r = 0<br>    while r &lt; len(plistaNCM):<br>        linha = plistaNCM[r]<br>        II = linha[2]<br>        if (not II == &#39;&#39;):  # É uma Classificação válida/&quot;escolhível&quot;, buscar os &quot;pais&quot;<br>            codigo = linha[0]<br>            descricao = linha[1]<br>            s = r - 1<br>            while True:     # Loop DNA. Percorre a lista &quot;para cima&quot;<br>                            # procurando a árvore genealógica...<br>                linha = plistaNCM[s]<br>                codigo2 = linha[0]<br>                descricao2 = linha[1]<br>                lcodigo = codigo[0:2] + &quot;.&quot; + codigo[2:4]<br>                if lcodigo == codigo2:<br>                    descricao = descricao + &quot; &quot; + descricao2<br>                    listaTECResumo.append(codigo + &quot; &quot; + descricao)<br>                    break<br>                lcodigo = codigo[0:6]<br>                if lcodigo == codigo2:<br>                    descricao = descricao + &quot; &quot; + descricao2<br>                lcodigo = codigo[0:7]<br>                if lcodigo == codigo2:<br>                    descricao = descricao + &quot; &quot; + descricao2<br>                lcodigo = codigo[0:8]<br>                if lcodigo == codigo2:<br>                    descricao = descricao + &quot; &quot; + descricao2<br>                lcodigo = codigo[0:9]<br>                if lcodigo == codigo2:<br>                    descricao = descricao + &quot; &quot; + descricao2<br>                s = s - 1<br>                if ((s == -1) or ((r - s) &gt; 100)):  #Exceção encontrada, abortar!<br>                    listaTECResumo.append(codigo+&quot; &quot;+descricao)<br>                    break<br>        r = r + 1<br>    return listaTECResumo</pre><p>Now the code for feeeding the manager:</p><pre>from sqlalchemy.orm import sessionmaker<br>from models.models import engine<br>from models.collectionmanager import CollectionManager<br>import batch.processtec as pt</pre><pre>listaTEC = pt.montaTEC()<br>listaNCM = pt.montaNCM(listaTEC)<br>listaTECResumo = pt.montaTECResumo(listaNCM)<br># Base.metadata.drop_all(engine)<br># Base.metadata.create_all(engine)<br>Session = sessionmaker(bind=engine)<br>session = Session()</pre><pre>manager = CollectionManager(session)</pre><pre># Cria Collection principal - TEC Resumo<br>collection, exists = manager.add_collection(&quot;TEC&quot;)<br>if not exists:<br>    # Create Documents<br>    for linha in listaTECResumo:<br>        codigo = linha[:10]<br>        descricao = linha[11:]<br>        document = manager.add_document(codigo, descricao)<br>    manager.commit()<br>    # Retrieve documents, process then<br>    # manager.process_collection(pt.tokenize_to_words) TODO<br>    # manager.commit()<br>    documents = collection.documents<br>    for document in documents:<br>        manager.process(document, pt.tokenize_to_words)</pre><p>Let’s use sqlitebrowser, again, to take a look, again, in the data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SfqVeo6bsLL9EktcyRNXOQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-r--SdJcLQDY8oEv060cqw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3yfNf6-FNxaDxI-9zCOCTA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Usy_AAa6rKVxQ9OOFsQYSw.png" /></figure><p>As we did earlier for the Model, it is a good practice to create a test for our CollectionManager class. The process of feeding the Model itself was a good test for the Model and for the CollectionManager. Now, we need to test the search functions to validate we did things right way. Here is the code:</p><pre>from sqlalchemy.orm import sessionmaker<br>from models.models import engine, Collection<br>from models.collectionmanager import CollectionManager</pre><pre>Session = sessionmaker(bind=engine)<br>session = Session()</pre><pre>teccollection = session.query(Collection).filter_by(id=1).one()</pre><pre>manager = CollectionManager(session, teccollection)</pre><pre>print(&quot;Collection lenght: &quot;+str(manager.collection_lenght()))<br>print(&quot;Average Document Length: &quot;+str(manager.avg_dl()))<br>print(&quot;Term Frequency (times that appears per document for word &#39;arruelas&#39;)&quot;)<br>print(manager.tf(&#39;arruelas&#39;))<br>finaldict = manager.bm25(&#39;arruelas&#39;)<br>print(finaldict)<br>print(len(finaldict))</pre><pre>print(&quot;Term Frequency (times that appears per document for three words&quot; +<br>      &quot;&#39;arruelas obras plastico&#39;)&quot;)<br>finaldict = manager.bm25(&#39;arruelas obras plastico&#39;)<br>print(finaldict)<br>print(len(finaldict))</pre><pre>print(manager.filter_documents(&quot;01%&quot;))</pre><p>And the results:</p><pre>Collection lenght: 10147<br>Average Document Length: 22.503498571006208<br>Term Frequency (times that appears per document for word &#39;arruelas&#39;)<br>{7104: 1, 7105: 3, 7106: 2, 7107: 1, 4804: 1, 4805: 1, 7206: 1, 7207: 2, 7208: 1, 7109: 1, 7210: 1, 7294: 1, 4757: 1, 7209: 1, 7108: 1, 7098: 1, 7099: 1, 7100: 1, 7101: 1, 7102: 2, 7103: 1}<br>[{&#39;title&#39;: &#39;7318.21.00&#39;, &#39;contents&#39;: &#39;--\tArruelas (Anilhas*) de pressão e outras arruelas (anilhas*) de segurança -\tArtigos não roscados: Parafusos, pinos ou pernos, roscados, porcas, tira-fundos, ganchos roscados, rebites, chavetas, cavilhas, contrapinos ou troços, arruelas (anilhas*) (incluindo as de pressão) e artigos semelhantes, de ferro fundido, ferro ou aço.&#39;, &#39;score&#39;: 7.752116121674206}, {&#39;title&#39;: &#39;7318.22.00&#39;, &#39;contents&#39;: &#39;--\tOutras arruelas (anilhas*) -\tArtigos não roscados: Parafusos, pinos ou pernos, roscados, porcas, tira-fundos, ganchos roscados, rebites, chavetas, cavilhas, contrapinos ou troços, arruelas (anilhas*) (incluindo as de pressão) e artigos semelhantes, de ferro fundido, ferro ou aço.&#39;, &#39;score&#39;: 6.446019096047554}, {&#39;title&#39;: &#39;7318.15.00&#39;, &#39;contents&#39;: &#39;--\tOutros parafusos e pinos ou pernos, mesmo com as porcas e arruelas (anilhas*) -\tArtigos roscados: Parafusos, pinos ou pernos, roscados, porcas, tira-fundos, ganchos roscados, rebites, chavetas, cavilhas, contrapinos ou troços, arruelas (anilhas*) (incluindo as de pressão) e artigos semelhantes, de ferro fundido, ferro ou aço.&#39;, &#39;score&#39;: 6.263821398399809}, {&#39;title&#39;: &#39;7415.21.00&#39;, &#39;contents&#39;: &#39;--\tArruelas  (Anilhas*) (incluindo as de pressão) -\tOutros artigos, não roscados: Tachas, pregos, percevejos, escápulas e artigos semelhantes, de cobre ou de ferro ou aço com cabeça de cobre; parafusos, pinos ou pernos, roscados, porcas, ganchos roscados, rebites, chavetas, cavilhas, contrapinos ou troços, arruelas (anilhas*) (incluindo as de pressão), e artigos semelhantes, de cobre.&#39;, &#39;score&#39;: 6.091640271441095}, {&#39;title&#39;: &#39;3926.90.10&#39;, &#39;contents&#39;: &#39;Arruelas -\tOutras Outras obras de plástico e obras de outras matérias das posições 39.01 a 39.14.&#39;, &#39;score&#39;: 4.896775215166389}, {&#39;title&#39;: &#39;4006.90.00&#39;, &#39;contents&#39;: &#39;-\tOutros Outras formas (por exemplo, varetas, tubos, perfis) e artigos (por exemplo, discos, arruelas (anilhas*)), de borracha não vulcanizada.&#39;, &#39;score&#39;: 4.640432730683922}, {&#39;title&#39;: &#39;4006.10.00&#39;, &#39;contents&#39;: &#39;-\tPerfis para recauchutagem Outras formas (por exemplo, varetas, tubos, perfis) e artigos (por exemplo, discos, arruelas (anilhas*)), de borracha não vulcanizada.&#39;, &#39;score&#39;: 4.59235150406269}, {&#39;title&#39;: &#39;7616.10.00&#39;, &#39;contents&#39;: &#39;-\tTachas, pregos, escápulas, parafusos, pinos ou pernos roscados, porcas, ganchos roscados, rebites, chavetas, cavilhas, contrapinos ou troços, arruelas (anilhas*) e artigos semelhantes Outras obras de alumínio.&#39;, &#39;score&#39;: 4.366154840381264}, {&#39;title&#39;: &#39;7318.19.00&#39;, &#39;contents&#39;: &#39;--\tOutros -\tArtigos roscados: Parafusos, pinos ou pernos, roscados, porcas, tira-fundos, ganchos roscados, rebites, chavetas, cavilhas, contrapinos ou troços, arruelas (anilhas*) (incluindo as de pressão) e artigos semelhantes, de ferro fundido, ferro ou aço.&#39;, &#39;score&#39;: 4.200632819133858}, {&#39;title&#39;: &#39;7318.23.00&#39;, &#39;contents&#39;: &#39;--\tRebites -\tArtigos não roscados: Parafusos, pinos ou pernos, roscados, porcas, tira-fundos, ganchos roscados, rebites, chavetas, cavilhas, contrapinos ou troços, arruelas (anilhas*) (incluindo as de pressão) e artigos semelhantes, de ferro fundido, ferro ou aço.&#39;, &#39;score&#39;: 4.200632819133858}, {&#39;title&#39;: &#39;7318.29.00&#39;, &#39;contents&#39;: &#39;--\tOutros -\tArtigos não roscados: Parafusos, pinos ou pernos, roscados, porcas, tira-fundos, ganchos roscados, rebites, chavetas, cavilhas, contrapinos ou troços, arruelas (anilhas*) (incluindo as de pressão) e artigos semelhantes, de ferro fundido, ferro ou aço.&#39;, &#39;score&#39;: 4.200632819133858}, {&#39;title&#39;: &#39;7318.11.00&#39;, &#39;contents&#39;: &#39;--\tTira-fundos -\tArtigos roscados: Parafusos, pinos ou pernos, roscados, porcas, tira-fundos, ganchos roscados, rebites, chavetas, cavilhas, contrapinos ou troços, arruelas (anilhas*) (incluindo as de pressão) e artigos semelhantes, de ferro fundido, ferro ou aço.&#39;, &#39;score&#39;: 4.200632819133858}, {&#39;title&#39;: &#39;7318.16.00&#39;, &#39;contents&#39;: &#39;--\tPorcas -\tArtigos roscados: Parafusos, pinos ou pernos, roscados, porcas, tira-fundos, ganchos roscados, rebites, chavetas, cavilhas, contrapinos ou troços, arruelas (anilhas*) (incluindo as de pressão) e artigos semelhantes, de ferro fundido, ferro ou aço.&#39;, &#39;score&#39;: 4.200632819133858}, {&#39;title&#39;: &#39;7318.14.00&#39;, &#39;contents&#39;: &#39;--\tParafusos perfurantes -\tArtigos roscados: Parafusos, pinos ou pernos, roscados, porcas, tira-fundos, ganchos roscados, rebites, chavetas, cavilhas, contrapinos ou troços, arruelas (anilhas*) (incluindo as de pressão) e artigos semelhantes, de ferro fundido, ferro ou aço.&#39;, &#39;score&#39;: 4.161194835078855}, {&#39;title&#39;: &#39;7318.12.00&#39;, &#39;contents&#39;: &#39;--\tOutros parafusos para madeira -\tArtigos roscados: Parafusos, pinos ou pernos, roscados, porcas, tira-fundos, ganchos roscados, rebites, chavetas, cavilhas, contrapinos ou troços, arruelas (anilhas*) (incluindo as de pressão) e artigos semelhantes, de ferro fundido, ferro ou aço.&#39;, &#39;score&#39;: 4.122490496596541}, {&#39;title&#39;: &#39;7318.13.00&#39;, &#39;contents&#39;: &#39;--\tGanchos e armelas (pitões*) -\tArtigos roscados: Parafusos, pinos ou pernos, roscados, porcas, tira-fundos, ganchos roscados, rebites, chavetas, cavilhas, contrapinos ou troços, arruelas (anilhas*) (incluindo as de pressão) e artigos semelhantes, de ferro fundido, ferro ou aço.&#39;, &#39;score&#39;: 4.122490496596541}, {&#39;title&#39;: &#39;7318.24.00&#39;, &#39;contents&#39;: &#39;--\tChavetas, cavilhas e contrapinos ou troços -\tArtigos não roscados: Parafusos, pinos ou pernos, roscados, porcas, tira-fundos, ganchos roscados, rebites, chavetas, cavilhas, contrapinos ou troços, arruelas (anilhas*) (incluindo as de pressão) e artigos semelhantes, de ferro fundido, ferro ou aço.&#39;, &#39;score&#39;: 4.084499520866734}, {&#39;title&#39;: &#39;7415.29.00&#39;, &#39;contents&#39;: &#39;--\tOutros -\tOutros artigos, não roscados: Tachas, pregos, percevejos, escápulas e artigos semelhantes, de cobre ou de ferro ou aço com cabeça de cobre; parafusos, pinos ou pernos, roscados, porcas, ganchos roscados, rebites, chavetas, cavilhas, contrapinos ou troços, arruelas (anilhas*) (incluindo as de pressão), e artigos semelhantes, de cobre.&#39;, &#39;score&#39;: 3.9392888271386792}, {&#39;title&#39;: &#39;7415.39.00&#39;, &#39;contents&#39;: &#39;--\tOutros -\tOutros artigos, roscados: Tachas, pregos, percevejos, escápulas e artigos semelhantes, de cobre ou de ferro ou aço com cabeça de cobre; parafusos, pinos ou pernos, roscados, porcas, ganchos roscados, rebites, chavetas, cavilhas, contrapinos ou troços, arruelas (anilhas*) (incluindo as de pressão), e artigos semelhantes, de cobre.&#39;, &#39;score&#39;: 3.9392888271386792}, {&#39;title&#39;: &#39;7415.10.00&#39;, &#39;contents&#39;: &#39;-\tTachas, pregos, percevejos, escápulas e artigos semelhantes Tachas, pregos, percevejos, escápulas e artigos semelhantes, de cobre ou de ferro ou aço com cabeça de cobre; parafusos, pinos ou pernos, roscados, porcas, ganchos roscados, rebites, chavetas, cavilhas, contrapinos ou troços, arruelas (anilhas*) (incluindo as de pressão), e artigos semelhantes, de cobre.&#39;, &#39;score&#39;: 3.87048771655998}, {&#39;title&#39;: &#39;7415.33.00&#39;, &#39;contents&#39;: &#39;--\tParafusos; pinos ou pernos e porcas -\tOutros artigos, roscados: Tachas, pregos, percevejos, escápulas e artigos semelhantes, de cobre ou de ferro ou aço com cabeça de cobre; parafusos, pinos ou pernos, roscados, porcas, ganchos roscados, rebites, chavetas, cavilhas, contrapinos ou troços, arruelas (anilhas*) (incluindo as de pressão), e artigos semelhantes, de cobre.&#39;, &#39;score&#39;: 3.836980586566616}]<br>21</pre><p>Also the code to test “spell checking”, that we will use to implement an edit text with autocomplete:</p><pre>import utils.spelling_corrector as spell<br>from sqlalchemy.orm import sessionmaker<br>from models.models import Word, engine</pre><pre>Session = sessionmaker(bind=engine)<br>session = Session()</pre><pre>busca = &quot;inicia&quot;</pre><pre>while busca != &quot;&quot;:<br>    busca = input(&quot;Digite a palavra a corrigir:&quot;)<br>    vocab = [word.atoken for word in<br>             session.query(Word).filter(Word.atoken.like(busca[0]+&quot;%&quot;)).all()]<br>    correct = spell.correct(busca, vocab)<br>    parcial = [word.atoken for word in<br>               session.query(Word).filter(Word.atoken.like(busca+&quot;%&quot;)).all()]<br>    parcialcorrect = [word.atoken for word in<br>                      session.query(Word).filter(Word.atoken.like(str(list(correct)[0])+&quot;%&quot;)).all()]<br>    print(&quot;Corrigida:&quot;+str(correct))<br>    print(&quot;Parcial:&quot;+str(parcial))<br>    print(&quot;Parcial corrigida:&quot;+str(parcialcorrect))<br>    all_options = set(set(correct)  | set(parcial) | set(parcialcorrect))<br>    print(&quot;Final:&quot;+str(all_options))</pre><pre>&gt;&gt;&gt;&gt;</pre><pre>Digite a palavra a corrigir:tst</pre><pre>Corrigida:{&#39;tumt&#39;, &#39;tal&#39;, &#39;teto&#39;, &#39;tex&#39;, &#39;tem&#39;, &#39;teste&#39;, &#39;tsnr&#39;, &#39;tmq&#39;}</pre><pre>Parcial:[]</pre><pre>Parcial corrigida:[&#39;tumt&#39;]</pre><pre>Final:{&#39;tumt&#39;, &#39;tal&#39;, &#39;teto&#39;, &#39;tex&#39;, &#39;tem&#39;, &#39;teste&#39;, &#39;tsnr&#39;, &#39;tmq&#39;}</pre><pre>Digite a palavra a corrigir:paraceta</pre><pre>Corrigida:[&#39;paracet&#39;]</pre><pre>Parcial:[&#39;paracetamol&#39;]</pre><pre>Parcial corrigida:[&#39;paracetamol&#39;]</pre><pre>Final:{&#39;paracet&#39;, &#39;paracetamol&#39;}</pre><p>Now we have a Collection in our model, validating the work we made on Part 2. The index/search methods were sucessfully tested on this connection. 3. We can run tests every time we make a change on code to see if anything is working as expected. 4. We can even say we have a fully functional app. Time do build a fancy user interface!</p><p>On Part 4 we will see how to use Flask to create this UI.</p><p>References</p><p><a href="http://www.springer.com/us/book/9781484223871">Text Analytics with Python - A Practical Real-World Approach | Dipanjan Sarkar | Springer</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=690bd8dbf840" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>