<?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 Lakshmi Narayana Santha on Medium]]></title>
        <description><![CDATA[Stories by Lakshmi Narayana Santha on Medium]]></description>
        <link>https://medium.com/@santhalakshminarayana?source=rss-3ce01f4ebce8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*F25W4KHq6oyPMawsnHwWMA.jpeg</url>
            <title>Stories by Lakshmi Narayana Santha on Medium</title>
            <link>https://medium.com/@santhalakshminarayana?source=rss-3ce01f4ebce8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 01:54:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@santhalakshminarayana/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[Build Rag With Llamaindex To Make LLM Answer About Yourself, Like in an Interview or About General…]]></title>
            <link>https://pub.towardsai.net/build-rag-with-llamaindex-to-make-llm-answer-about-yourself-like-in-interview-or-about-general-68bb2037f8b6?source=rss-3ce01f4ebce8------2</link>
            <guid isPermaLink="false">https://medium.com/p/68bb2037f8b6</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[llamaindex]]></category>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[retrieval-augmented]]></category>
            <dc:creator><![CDATA[Lakshmi Narayana Santha]]></dc:creator>
            <pubDate>Sun, 26 May 2024 21:05:24 GMT</pubDate>
            <atom:updated>2024-05-30T13:58:00.229Z</atom:updated>
            <content:encoded><![CDATA[<h3>Build Rag With Llamaindex To Make LLM Answer About Yourself, Like in an Interview or About General Information</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6q69styF-M0oDu-f9k8AHw.jpeg" /><figcaption>Advanced RAG pipeline with Llamaindex for chatting with yourself</figcaption></figure><p>From the day ChatGPT was introduced, the whole NLP/AI ecosystem was changed and came up with numerous new techniques to integrate the LLMs into various fields and use-cases. One of those gems that evolved along with the LLMs is <strong>RAG (Retrieved Augmentation Generation)</strong>. Even with LLMs like Gemini supporting context up to millions of length, RAG is still relevant and has been used for building various applications like chatting with the documents, helping with research processes for specific domain, providing domain-specific data for LLM to inference, and mostly providing companies to integrate AI capabilities with their sensitive customer data.</p><p>In this blog, we will see how to build one such use-case with RAG to make LLM answer about yourself. The input data could be your resume or even general information about yourself. I have used some general information like my interests in movies and TV, and brief technical information of my professional career.</p><p>Check out my Github repo for a full-stack chat bot application that I have built with Docker, Next.js, and Python (FastAPI, Llamaindex). Refer to the sub-repo <strong>doppalf-ai</strong> for the Python application</p><p><a href="https://github.com/santhalakshminarayana/doppalf">GitHub - santhalakshminarayana/doppalf: Doppalf is RAG powered AI chat bot application</a></p><p>After the final building of the RAG pipeline with Llamaindex, we can see the response from LLM like the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Oh7txTjBpyIaNJuQrGU7HA.png" /><figcaption>A simple response from LLM that assumes your character and answers about you</figcaption></figure><p>I have used Cohere as LLM and Qdrant for storing vector embeddings. You can create free APIs for both of these to use.</p><p>Create <a href="https://dashboard.cohere.com/api-keys">Cohere API trail key</a> and <a href="https://cloud.qdrant.io/">Qdrant Cloud API key</a> that offers a free 1 GB cluster for storing vectors.</p><blockquote>You can use any other LLM and vector store (or even in-memory storage)</blockquote><p>With Llamaindex, we can build a full chat engine with the following steps:</p><ol><li>Load Documents from the directory</li><li>Parse text into Sentences (as nodes) with a Window size as 1 (configurable)</li><li>Get vector embeddings for each node (sentences) (Cohere embeddings)</li><li>Index the nodes and store the vector embeddings (Qdrant cloud)</li><li>Persist the index for re-use further run-times</li><li>Build a Chat engine from the index with a retrieval strategy as “Small-to-Big” and with some buffered chat memory history</li><li>Provide the retrieved context and use Cohere Rerank for re-ranking the retrieved nodes</li><li>Synthesis the response using LLM (Cohere AI) with the retrieved context</li></ol><p>The following is the whole RAG pipeline we will build with Llamaindex</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6q69styF-M0oDu-f9k8AHw.jpeg" /><figcaption>The whole RAG pipeline described above</figcaption></figure><p>Install the following Python packages first</p><pre>python-dotenv<br>fastapi<br>uvicorn<br>llama-index<br>llama-index-embeddings-cohere<br>llama-index-llms-cohere<br>llama-index-postprocessor-cohere-rerank<br>llama-index-vector-stores-qdrant<br>cohere<br>qdrant-client</pre><p>The above dependencies install the FastAPI and core Llamaindex packages. As I am using Cohere and Qdrant with Llamaindex, the above list contains those Llamaindex support packages.</p><p>Getting into the real action. First, we will get the required configuration (like API Keys, documents location, etc.,) from <em>.env</em> file and load them into the runtime using <strong>python-dotenv</strong> package</p><pre>DOCS_DIR=&quot;documents&quot;<br>INDEX_STORAGE_DIR=&quot;pstorage&quot;<br>COLLECTION_NAME=&quot;ps_rag&quot;<br><br>MAX_BUFFER_MEMORY_TOKENS=4096<br><br>COHERE_API_KEY=&lt;cohere-api-key&gt;<br>QDRANT_API_KEY=&lt;qdrant-api-key&gt;<br>QDRANT_CLOUD_URL=&lt;qdrant-cloud-url&gt;</pre><p>Load the above <em>.env</em> file into the program runtime as</p><pre>from typing import Self<br>import os<br>from threading import Lock<br><br>from dotenv import load_dotenv<br><br><br>load_dotenv()<br><br>env_keys = {<br>    &quot;DOCS_DIR&quot;: &quot;DOCS_DIR&quot;,<br>    &quot;INDEX_STORAGE_DIR&quot;: &quot;INDEX_STORAGE_DIR&quot;,<br>    &quot;COLLECTION_NAME&quot;: &quot;COLLECTION_NAME&quot;,<br>    &quot;MAX_BUFFER_MEMORY_TOKENS&quot;: &quot;MAX_BUFFER_MEMORY_TOKENS&quot;,<br>    &quot;COHERE_API_KEY&quot;: &quot;COHERE_API_KEY&quot;,<br>    &quot;QDRANT_API_KEY&quot;: &quot;QDRANT_API_KEY&quot;,<br>    &quot;QDRANT_CLOUD_URL&quot;: &quot;QDRANT_CLOUD_URL&quot;,<br>}<br><br>def check_all_dict_keys_not_none(o: dict) -&gt; bool:<br>    for v in o.values():<br>        if v is None:<br>            return False<br>    <br>    return True<br><br>class ENV():<br>    _env_instance = None<br>    _env_config = {}<br>    _lock = Lock()<br><br>    def __new__(cls) -&gt; Self:<br>        if cls._env_instance is None:<br>            with cls._lock:<br>                if cls._env_instance is None:<br>                    cls._env_instance = super(ENV, cls).__new__(cls)<br>                    cls._env_instance._load_env()<br><br>        return cls._env_instance<br>    <br>    def _load_env(self):<br>        config = {}<br>        for v in env_keys.values():<br>            config[v] = os.getenv(v)<br><br>        if not check_all_dict_keys_not_none(config):<br>            raise ValueError(&quot;env has some values missing&quot;)<br><br>        self._env_config = config<br><br>    <br>    def get(self, key:str) -&gt; any:<br>        return self._env_config.get(key)</pre><p>We have loaded the environment variables into a Single class and we can get the loaded object that has environment variables stored.</p><p>I have used the following brief information about my professional career:</p><pre>Santha Lakshmi Narayana holds the role of Senior Software Engineer at Nouveau Labs in Bengaluru, India. His expertise lies in AI, Machine Learning, and Backend technologies, with a deep understanding of Advanced Image Processing, Computer Vision, NLP, and System Design &amp; Architecture. Throughout his career, he has contributed to various projects, including Contact-center solutions (both call and chat), AutoML, Image enhancement, Search information extraction, and Name matching &amp; mapping.<br><br>With a strong belief in prioritizing performance-optimized code quality over quantity, Lakshmi Narayana is dedicated to delivering robust software solutions that remain resilient even with new additions or modifications.<br><br>His core proficiencies encompass Python, Go, OpenCV, Keras, Pytorch, Tensorflow, Redis, and MySQL. Additionally, he has experience in JavaScript, TypeScript, React, React Native, Next.js, Flutter, and Dart.<br><br>For effective service management, he relies on tools such as Git, Nginx, Docker, and Kubernetes. He actively shares his insights, project developments, comprehensive research, and other tech-related content through his blog hosted at https://santhalakshminarayana.github.io.<br><br>He also maintains an active presence on GitHub (https://github.com/santhalakshminarayana), where he oversees repositories for side projects like AutoML and Image enhancement.</pre><p>Along with this I have also provided some personal interests in Movies and TV. All these documents are stored inside the directory <strong><em>documents,</em></strong> and Llamaindex loads the documents from this directory</p><p>And finally, the whole code for the RAG pipeline is</p><pre>from llama_index.core import load_index_from_storage<br>from llama_index.core.memory import ChatMemoryBuffer<br>from llama_index.core.node_parser import SentenceWindowNodeParser<br>from llama_index.core.postprocessor import MetadataReplacementPostProcessor<br>from llama_index.embeddings.cohere import CohereEmbedding<br>from llama_index.llms.cohere import Cohere<br>from llama_index.postprocessor.cohere_rerank import CohereRerank<br>from llama_index.vector_stores.qdrant import QdrantVectorStore<br>from qdrant_client import QdrantClient<br><br>from src.config.env import ENV, env_keys<br>from src.config.logger import get_logger<br><br>from .constants import CHAT_PROMPT<br><br>envk = ENV()<br>logger = get_logger()<br><br>index = None<br>chat_engine = None<br><br>def load_rag() -&gt; None:<br>    global index<br>    global chat_engine<br><br>    cdir = os.getcwd()<br>    docs_dir = envk.get(env_keys.get(&quot;DOCS_DIR&quot;))<br>    docs_path = os.path.join(cdir, docs_dir)<br><br>    # check if any documents are provided for index<br>    if not os.path.exists(docs_path):<br>        raise FileNotFoundError(f&quot;Documents dir at path: {docs_path} not exists.&quot;)<br>    if not os.listdir(docs_dir):<br>        raise FileNotFoundError(f&quot;Provide documents inside directory: {docs_path} for indexing.&quot;)<br>    <br>    storage_dir = envk.get(env_keys.get(&quot;INDEX_STORAGE_DIR&quot;))<br>    storage_path = os.path.join(cdir, storage_dir)<br>    <br>    cohere_api_key = envk.get(env_keys.get(&quot;COHERE_API_KEY&quot;))<br>    qdrant_api_key = envk.get(env_keys.get(&quot;QDRANT_API_KEY&quot;))<br><br>    Settings.llm = Cohere(<br>        api_key=cohere_api_key,<br>        model=&quot;command-r-plus&quot;, <br>    )<br>    Settings.embed_model = CohereEmbedding(<br>        cohere_api_key=cohere_api_key,<br>        model_name=&quot;embed-english-v3.0&quot;,<br>        input_type=&quot;search_document&quot;,<br>    )<br>    <br>    qd_client = QdrantClient(<br>        envk.get(env_keys.get(&quot;QDRANT_CLOUD_URL&quot;)),<br>        api_key=qdrant_api_key,<br>    )<br><br>    sentence_node_parser = SentenceWindowNodeParser.from_defaults(<br>        window_size=1,<br>        window_metadata_key=&quot;window&quot;,<br>        original_text_metadata_key=&quot;original_text&quot;, <br>    )<br><br>    vector_store = QdrantVectorStore(<br>        client=qd_client, <br>        collection_name=envk.get(env_keys.get(&quot;COLLECTION_NAME&quot;)),<br>    )<br><br>    # index was previously persisted<br>    if os.path.exists(storage_path) and os.listdir(storage_path):<br>        logger.debug(&quot;Using existing index.&quot;)<br>        storage_context = StorageContext.from_defaults(<br>            vector_store=vector_store, persist_dir=storage_path<br>        )<br>        <br>        index = load_index_from_storage(storage_context)<br><br>    else:<br>        logger.debug(&quot;Creating new index for documents.&quot;)<br>        reader = SimpleDirectoryReader(input_dir=docs_path)<br>        <br>        all_docs = []<br>        for docs in reader.iter_data():<br>            all_docs.extend(docs)<br>        <br>        for doc in all_docs:<br>            logger.debug(f&quot;id: {doc.doc_id}\nmetada: {doc.metadata}&quot;)<br><br>        nodes = sentence_node_parser.get_nodes_from_documents(all_docs)<br>        <br>        storage_context = StorageContext.from_defaults(vector_store=vector_store)<br>        <br>        index = VectorStoreIndex(nodes, storage_context=storage_context)<br><br>        index.storage_context.persist(persist_dir=storage_path)<br><br><br>    chat_engine = index.as_chat_engine(<br>        chat_mode=&quot;condense_plus_context&quot;,<br>        memory=ChatMemoryBuffer.from_defaults(token_limit=int(envk.get(env_keys.get(&quot;MAX_BUFFER_MEMORY_TOKENS&quot;)))),<br>        context_prompt=CHAT_PROMPT,<br>        similarity_top_k=3, <br>        node_postprocessors=[<br>            MetadataReplacementPostProcessor(target_metadata_key=&quot;window&quot;),<br>            CohereRerank(api_key=cohere_api_key, top_n=3),<br>        ],<br>        verbose=False,<br>    )<br><br><br>def chat(query: str):<br>    global chat_engine<br>    <br>    response = chat_engine.stream_chat(query)<br>    for res in response.response_gen:<br>        yield f&quot;data: {json.dumps({&quot;message&quot;:res})}\n\n&quot;</pre><p>The <strong>load_rag()</strong> function will first check if any previously stored index exists for re-using else it will build one. If no index is stored in the given <em>storage_path</em> directory, it will build the index by loading the documents from the <em>docs_dir</em> directory. <strong>SentenceWindowNodeParser</strong> is used for parsing the sentences into nodes with a window size of 1. This window size makes the post-retrieval context have surrounding sentences also part of it for better answer synthesis.</p><p>For created nodes, get the vector embeddings from the Cohere embeddings and store them in the Qdrant Cloud. And finally store the index for skipping this whole process again when the application restarts.</p><p>From the index, build the chat engine with some memory (4096 tokens here) for memorising past conversations with the user and provide Cohere Re-ranker as post node retrieval processer for reranking the nodes based on the query relevancy. This chat engine retrieves the surrounding context for each retrieved node for more information and finally sends the whole retrieved-context and the query to the LLM for answer generation as a prompt. I have used a custom prompt for making LLM answer as me.</p><pre>CHAT_PROMPT=(<br>    &quot;You are impersonating the human &#39;Lakshmi Narayana&#39; and so your name.&quot;<br>    &quot;So you are Lakshmi Narayana and answers in first person.When asked any question about you, you will answer as if Lakshmi Narayana is answering.&quot;<br>    &quot;You will answer politely and take the help of the following context for more relevant answers.&quot;<br>    &quot;If you don&#39;t have any sufficient information from the context, use your knowledge to answer.&quot;<br>    &quot;Or don&#39;t hallucinate if you are sure you cannot answer.&quot;<br>    &quot;Here are the relevant documents for the context:\n{context_str}\n&quot;<br>    &quot;Instruction: Use the previous chat history, or the context above, to interact and help the user and answer as if you are Lakshmi Narayana.&quot;<br>    &quot;Don&#39;t add any additional data if the answer can be derived from context.&quot;<br>    &quot;Generate the response in markdown format.&quot;<br>)</pre><p>LLamaindex uses this prompt for context ingestion and sends this to LLM for answer generation.</p><p>Finally, the chat generation API is exposed for streaming the response using FastAPI as follows</p><pre>from fastapi import APIRouter, HTTPException<br>from pydantic import BaseModel<br>from starlette.responses import StreamingResponse<br><br>from .rag import chat<br><br><br>class GenerateModel(BaseModel):<br>    message: str<br><br><br>grouter = APIRouter(tags=[&quot;generate&quot;])<br><br><br>@grouter.post(&quot;&quot;)<br>async def generate(data: GenerateModel):<br>    try:<br>        return StreamingResponse(<br>            chat(data.message), <br>            media_type=&#39;text/event-stream&#39;,<br>        )<br>    except Exception as e:<br>        raise HTTPException(status_code=500, detail=e)</pre><p>The above API <strong>generate</strong> takes the user query as part of request body data with key message and calls the <strong>chat</strong> function for generating the answer.</p><p>This will generate the response and stream to the client as SSE (Server Sent Event).</p><p>With all of the above things done, if the API is requested with a user query like the following and the LLM will answer about me as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bf1wFfW86EQZ_PZebnlhrA.png" /></figure><p>With the help Llamaindex and a small RAG pipeline we could build a AI chat bot that answer about ourselves. Hope this small article provides a guidance on how to build simple RAG powered chat bot applications for real world scenarios.</p><p>I have written a comprehensive blog about this whole full-stack project Doppalf on my personal blog. Read the following blog for more details</p><p><a href="https://santhalakshminarayana.github.io/blog/doppalf-rag-powered-ai-chatbot">Doppalf: RAG powered full-stack AI chatbot like ChatGPT- Santha Lakshmi Narayana</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u9a5nLTTnkDzbQgQG6RjFQ.gif" /><figcaption>Chatbot with UI like Chat GPT</figcaption></figure><p>You can get the whole project code for end-to-end chatbot application with UI (streaming answers like ChatGPT) and backend in my Github repo:</p><p><a href="https://github.com/santhalakshminarayana/doppalf">GitHub - santhalakshminarayana/doppalf: Doppalf is RAG powered AI chat bot application</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68bb2037f8b6" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/build-rag-with-llamaindex-to-make-llm-answer-about-yourself-like-in-interview-or-about-general-68bb2037f8b6">Build Rag With Llamaindex To Make LLM Answer About Yourself, Like in an Interview or About General…</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Image Search Engine using Image Hashing technique in Python]]></title>
            <link>https://medium.com/analytics-vidhya/image-search-engine-using-image-hashing-technique-in-python-e6749dacc8f7?source=rss-3ce01f4ebce8------2</link>
            <guid isPermaLink="false">https://medium.com/p/e6749dacc8f7</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[p-hash]]></category>
            <category><![CDATA[perceptual-hashing]]></category>
            <category><![CDATA[reverse-image-search]]></category>
            <category><![CDATA[image-retrieval]]></category>
            <dc:creator><![CDATA[Lakshmi Narayana Santha]]></dc:creator>
            <pubDate>Tue, 20 Jul 2021 19:48:06 GMT</pubDate>
            <atom:updated>2021-07-26T06:15:32.014Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E8cDAkO_z-J2x5eAEfqlUg.jpeg" /><figcaption>`From <a href="https://unsplash.com/photos/afW1hht0NSs?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditShareLink">Unsplash</a></figcaption></figure><p>Image searching is a type of information retrieval method in which similar images are retrieved based on the query which is also an image. Image searching is widely used in Forensics, Surveillance, etc.</p><p>Every modern browser provides an image searching feature to retrieve websites that have similar images asked in the query. These search engines are powered by heavy deep learning models processing and indexing billions of images daily. These search engines first index the images by extracting features from a deep learning model, and to retrieve the images, they calculate features for the query image and show similar images sorted based on the similarity rate. Also, some engines use a hybrid approach to search the images by indexing images based on both metadata and image content.</p><p>Before the popularity of deep learning, some search engines were using hashing techniques to index the images. In this tutorial, we discuss how to implement this image searching using the image hashing technique.</p><p>To build a search engine, we must implement the following steps</p><ol><li>Setup an image database.</li><li>Index images using hashing.</li><li>Fetch similar images by comparing hash values of a query image and images in the database. Similar images are fetched based on the similarity score of hashes.</li></ol><h3>1. Setup Image database</h3><p>The image database contains images of the top 5 <a href="https://en.wikipedia.org/wiki/List_of_tallest_buildings">tallest buildings of world</a> images. For each building (Burj Khalifa, Shanghai Tower, Abraj Al-Bait Clock Tower, Ping An Finance Center, and Lotte World Tower), the image database contains 5 different images of that building and a total of 25 images in the database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*boC-I0490UP0EX0xhTDLuQ.jpeg" /></figure><h3>2. Image indexing</h3><p>To index images, we use image hash values and store them in the database to compare images.</p><h4>Image Hashing</h4><blockquote>Image hashing is the process of giving a unique hash code to an image.</blockquote><p>As we can encode an image to a unique code, this code can be used to index the images. So we retrieve similar images by comparing hash codes and their similarity.</p><p>There are a variety of image hashing algorithms to hashing of images and most of the algorithms are simple and fast. Some of the popular algorithms are</p><ul><li>Average Hashing (aHash)</li><li>Median Hashing (mHash)</li><li>Perceptual Hashing (pHash)</li><li>Difference Hashing (dHash)</li><li>Block Hashing (bHash)</li><li>Wavelet Hashing (wHash)</li><li>ColorMoment Hashing</li></ul><p>If you are not familiar with the image hashing concept, learn about image hashing in this famous <a href="http://www.hackerfactor.com/blog/index.php?/archives/432-Looks-Like-It.html">blog</a>.</p><p>For now, we hash images using <a href="https://en.wikipedia.org/wiki/Perceptual_hashing">Perceptual Hashing</a> (pHash) algorithm which computes hashing on top of <a href="https://en.wikipedia.org/wiki/Discrete_cosine_transform">Discrete Cosine Transform</a> (DCT) that transforms data from spatial domain to frequency domain.</p><h4>pHash (Perceptual Hashing)</h4><p>pHash is a simple algorithm that calculates image hash based on the DCT values of the image. The algorithm involves the following steps</p><ul><li>Re-scale image — Re-scale the image to multiples of 4 like 8*8, 32*32, etc.</li><li>Convert to Gray-scale image.</li><li>Calculate DCT block for 8*8 or 32*32 image.</li><li>Compute average DCT value excluding the value at (0, 0) as it influences larger deviation in computing average.</li><li>Compute binary DCT block by setting entries either 0 or 1 by comparing average value (if value &gt; average then 1 else 0).</li><li>Construct hash by traversing the binary DCT block from left to right and top to bottom. As values are only 0 or 1, the hash can be stored in a 64-bit integer for 8*8 DCT block.</li></ul><p>For every image, we calculate the image hash from the above pHash algorithm and store these hashes as indices for images.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eeb0bd9b07b23354ce30c8281b1563e4/href">https://medium.com/media/eeb0bd9b07b23354ce30c8281b1563e4/href</a></iframe><p>In the above snippet, <strong>image_names</strong> contains all image paths in the images directory, and for every image, we calculate the hash value and store it in <strong>image_hash_dict</strong> for future use.</p><pre>Image names</pre><pre>images/abraj-al-bait-1.jpg<br>images/abraj-al-bait-2.jpg<br>images/abraj-al-bait-3.jpg<br>images/abraj-al-bait-4.jpg<br>images/abraj-al-bait-5.jpg<br>images/burj-khalifa-1.jpg<br>images/burj-khalifa-2.jpg<br>images/burj-khalifa-3.jpg<br>images/burj-khalifa-4.jpg<br>images/burj-khalifa-5.jpg<br>images/lotte-1.jpg<br>images/lotte-2.jpg<br>images/lotte-3.jpg<br>images/lotte-4.jpg<br>images/lotte-5.jpg<br>images/ping-an-1.jpg<br>images/ping-an-2.jpg<br>images/ping-an-3.jpg<br>images/ping-an-4.jpg<br>images/ping-an-5.jpg<br>images/shanghai-tower-1.jpg<br>images/shanghai-tower-2.jpg<br>images/shanghai-tower-3.jpg<br>images/shanghai-tower-4.jpg<br>images/shanghai-tower-5.jpg</pre><p><strong><em>hash_array_to_hash_hex()</em></strong> converts 1D binary array to hex string value and <strong><em>hash_hex_to_hash_array()</em></strong> hex string value to 1D binary array of data type float.</p><p>String hash values occupy less space and are flexible to store in a text or csv file. These values could be used for indexing images in the database.</p><p>Hash value for <strong><em>“images/shanghai-tower-1.jpg”</em></strong> is <strong>0xb1934cf40a79140b</strong></p><p>There are python libraries for calculating image hashes like <a href="https://github.com/JohannesBuchner/imagehash">ImageHash</a> and <a href="https://github.com/thorn-oss/perception">Perception</a> which provide different hash methods and other tools to implement image hashing.</p><h3>3. Fetching similar images</h3><p>Now for a query image, similar images are fetched as</p><ul><li>Calculate the image hash value for the query image.</li><li>As we already stored hash values for images in the database, compare their hash values with the hash value of the query image. Metric functions like Hamming distance can be used to compare hashes.</li><li>Now sort the images based on metric score.</li><li>Show images having the metric score above the threshold.</li></ul><p>As we already have image hash calculated, we can retrieve similar images by comparing hash values against query image hash value.</p><p>If the query image is “images/burj-khalifa-3.jpg”, to get similar images, calculate the hamming distance for all image hashes against query hash like</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/23a221c9584b9ffbc5fa0abf91372dfc/href">https://medium.com/media/23a221c9584b9ffbc5fa0abf91372dfc/href</a></iframe><p>This gives distance scores for images as below</p><pre>images/abraj-al-bait-1.jpg     0.46875<br>images/abraj-al-bait-2.jpg     0.609375<br>images/abraj-al-bait-3.jpg     0.640625<br>images/abraj-al-bait-4.jpg     0.578125<br>images/abraj-al-bait-5.jpg     0.5</pre><pre>images/burj-khalifa-1.jpg      0.53125<br>images/burj-khalifa-2.jpg      0.453125<br>images/burj-khalifa-3.jpg      0.0<br>images/burj-khalifa-4.jpg      0.390625<br>images/burj-khalifa-5.jpg      0.4375</pre><pre>images/lotte-1.jpg             0.453125<br>images/lotte-2.jpg             0.53125<br>images/lotte-3.jpg             0.625<br>images/lotte-4.jpg             0.4375<br>images/lotte-5.jpg             0.375</pre><pre>images/ping-an-1.jpg           0.453125<br>images/ping-an-2.jpg           0.609375<br>images/ping-an-3.jpg           0.484375<br>images/ping-an-4.jpg           0.484375<br>images/ping-an-5.jpg           0.453125</pre><pre>images/shanghai-tower-1.jpg    0.4375<br>images/shanghai-tower-2.jpg    0.328125<br>images/shanghai-tower-3.jpg    0.515625<br>images/shanghai-tower-4.jpg    0.359375<br>images/shanghai-tower-5.jpg    0.453125</pre><p>These scores indicate the similarity of an image to query image. Lower the score then more it is similar to the query image. Scores for the Burj Khalifa images are in range of 0.3–0.5 and some other images also lie in this range as buildings have a similar structure and it is difficult to differentiate structures.</p><p>Image hashing results could be not accurate than Deep Learning methods but they are very fast to implement and require less storage. Image hashing methods can be used for detecting strict duplicate images in large databases. With some pre-processing images and tweaking the pHash algorithm, we can achieve better results for retrieving similar images.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e6749dacc8f7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/image-search-engine-using-image-hashing-technique-in-python-e6749dacc8f7">Image Search Engine using Image Hashing technique in Python</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AutoML — A GUI Application to Make ML for Everyone]]></title>
            <link>https://pub.towardsai.net/automl-a-gui-application-to-make-ml-for-everyone-31d18ca84d89?source=rss-3ce01f4ebce8------2</link>
            <guid isPermaLink="false">https://medium.com/p/31d18ca84d89</guid>
            <category><![CDATA[eels]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[automl]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[pythongui]]></category>
            <dc:creator><![CDATA[Lakshmi Narayana Santha]]></dc:creator>
            <pubDate>Wed, 14 Oct 2020 12:57:15 GMT</pubDate>
            <atom:updated>2020-10-15T15:02:57.266Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="https://towardsai.net/p/category/automl">Automated Machine Learning</a></h4><h3>AutoML — A GUI Application to Make ML for Everyone</h3><h4>A desktop application that automates most of the ML pipeline tasks written in Python.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fwJqrJsAPNOWFUyje4UJBg.png" /><figcaption>AutoML</figcaption></figure><p>Machine Learning helps us to automate simple task which needs human intervention. This article explains how I developed a simple AutoML application to automated ML pipelines.</p><p>There are plenty of tools and libraries that exist like Google Cloud AutoML, AutoKeras, H2o’s AutoML. But most of these tools are expensive or script-based means don’t provide UI. Normal people who don’t have much knowledge in ML finds it hard to use these tools. So making AutoML with GUI would extend ML usage and helps users to learn ML through interactivity.</p><h4>Application setup</h4><p>Download the repository to run locally</p><p><a href="https://github.com/santhalakshminarayana/AutoML">santhalakshminarayana/AutoML</a></p><pre>$ git clone <a href="https://github.com/santhalakshminarayana/AutoML">https://github.com/santhalakshminarayana/AutoML</a>.git</pre><p>Create Virtual Environment</p><pre>$ virtualenv AutoML<br>$ source AutoML/bin/activate<br>$ cd AutoML</pre><p>Install requirements to run the application</p><pre>$ pip install -r requirements.txt</pre><p>Run application</p><pre>$ python app.py</pre><p>If everything is downloaded and got a place in the proper location then you can see a Welcome screen like the top image.</p><h4><strong>Making a GUI application</strong></h4><p>I’m not good at UI development and learned only basic HTML, CSS, and JS. And for application backend should be in Python where all computations happen. Now I need a framework or library which allows me to integrate JS and Python. After researching how to make UI in little time with my knowledge I came across Electron which provides the possibility of creating Cross-platform applications but it is heavy. I looked out for an alternative to Electron then found this Python library called <a href="https://github.com/samuelhwilliams/Eel">Eel (Python library)</a>.</p><p>Eel creation of desktop applications is easy and doesn’t require learning new packages or libraries if you know basic JS. Eel makes a bridge between JS and Python and passes data from one side to another just like Flask, Django but can run locally as a desktop application depends on the CEF browser (Chrome, Firefox, Edge …).</p><h4><strong>Architecture of the application</strong></h4><p>After deciding the tools required and before starting coding designing the base architecture of the application gives an abstract idea of working.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/0*-EOo-OGqgb057ytl" /><figcaption>Abstract Architecture of AutoML application</figcaption></figure><p>Workflow is simple:</p><ol><li>The user interacts with the application to select a type of model and enters data,</li><li>JS passes data to Python backend with the help of Eel,</li><li>Computation happen in Python and sends data to JS,</li><li>Display results to Users.</li></ol><p>The next step is to decide what things should be automated and requirements from the user.</p><h4><strong>Machine Learning Pipeline</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*hm_1lPxSNfQs3Wi-1or0ew.png" /></figure><p>Generally, a Machine Learning model follows pipeline steps like:</p><ol><li>Data extraction / preparation</li><li>Data processing</li><li>Feature extraction</li><li>Model selection</li><li>Model training</li><li>Model tuning</li><li>Model evaluation</li><li>Model prediction</li></ol><p>Except for Data extraction, Model Selection, and Model prediction all other steps can be automated by taking data from the user.</p><p>So, to automate the above things User has to provide data.</p><p><strong>Requirements from User<br></strong>User interacts with application for entering necessary details and user interaction should be minimal. Expected behaviour from user includes:</p><ol><li>Model selection in the context of dataset</li><li>Providing dataset related to model selected</li><li>Entering parameters for Model tuning</li><li>Look out for model insights and analysis</li></ol><p>Detailed end-to-end workflow</p><h3><strong>Step 1: Model Selection</strong></h3><p>User has to select the type of Problem from the following types:</p><ol><li>Regression</li><li>Classification</li><li>Clustering</li><li>Anomaly Detection</li><li>Dimension Reduction</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N7P5qcRhMWH4HTt0XOGaIw.png" /><figcaption>Different Problem Types</figcaption></figure><p>Each Problem type provides different models to select from, like</p><p><strong>Regression:</strong></p><ul><li>K-nn</li><li>Linear Regression</li><li>Support Vector Regressor (SVR)</li><li>Random Forest Regressor</li></ul><p><strong>Classification:</strong></p><ul><li>K-nn</li><li>Logistic Regression</li><li>Support Vector Machine (SVM)</li><li>Random Forest Classifier</li></ul><p><strong>Clustering:</strong></p><ul><li>K-means</li><li>Agglomerative / Hierarchial</li><li>DBSCAN</li></ul><p><strong>Anomaly Detection:</strong></p><ul><li>Multivariate Gaussian</li><li>DBSCAN</li><li>Isolation Forest</li></ul><p><strong>Dimension Reduction:</strong></p><ul><li>PCA</li><li>TSNE</li><li>Truncated SVD</li></ul><p>After selecting the problem type and model user has to provide Dataset and select parameters for the model</p><h3><strong>Step 2: Dataset entry and Parameter selection</strong></h3><p>The user provides Train Dataset and for Supervised learning provides Test Dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X3dMRlbfK40bfBCcdzsZ0Q.png" /></figure><p>An ML model requires many parameters that differ from model to model. Model parameters could be different types like <strong>int, string, float.</strong></p><p>If the user wants to run <strong>Hyper-parameter tuning, the </strong>user can provide multiple values for the same attribute.</p><p>If the user doesn’t select any parameters or cleared the default then default values stored will be used as parameters for the Model.</p><p>Now, the user interaction is done and it’s time for the backend to take action after the user clicks the <strong>Next </strong>button.</p><h3>Step 3: Dataset Pre-processing</h3><p>Data pre-processing includes</p><ul><li>Checking dataset suitability for Model selected</li><li>Assigning missing column names for each column in the dataset</li><li>Removing duplicate data/rows</li><li>Filling missing values according to problem type — Mean for regression, Mode for classification dataset.</li><li>Converting categorical values to numerical values — used <strong>BackwardDifferenceEncoder </strong>for conversion</li><li>Splitting into Train and Evaluation datasets if applies</li><li>Standardizing data</li><li>Applying PCA for feature extraction</li></ul><p>All these steps are automatically computed and the user will get logs printed in UI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RljwwU1zMcSGY3KYdZCUaQ.png" /><figcaption>Dataset pre-processing steps applied</figcaption></figure><p>The user would get an error in the following situations:</p><ul><li>Improper dataset</li><li>Dataset not related for the selected model</li><li>Improper model parameters provided by the user</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*obrasLY5XcnIdpdiOiFLMQ.png" /><figcaption>Model build failed</figcaption></figure><h3>Step 4: Model training with Hyper-parameter tuning</h3><p>If the dataset provided is successfully processed then the next step is to train Model with dataset. If multiple values for different parameters are provided then the model is Hyper-parameter tuned with <strong>GridSearchCV </strong>and the best parameter set which gives high accuracy is taken as Model parameters and displayed to the user telling the best parameter set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X_jvr6NfdvZbm2nybt53ow.png" /><figcaption>The best model with the parameter set taken from GridSearchCV</figcaption></figure><p>If any error occurs then the user informed by logs telling what went wrong in the model building process.</p><h3>Step 5: Model Performance Evaluation</h3><p>With data provided from users after splitting into Train data and Eval data, the trained model is evaluated and results are shown to the user in the form of different plots for different problem types.</p><p><strong>Regression Evaluation</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0qWrwCjCh9tumtDU_WpJEg.png" /><figcaption>Regression Metrics</figcaption></figure><p>In Regression, the plot contains MAE, MSE, RMSE, R**2, Adj. R**2 metrics on both Training data and Evaluation data shown.</p><p><strong>Classification Evaluation</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5D6Ph1QnaUEYihLps05ATA.png" /><figcaption>Classification Metrics</figcaption></figure><p>For Classification, Confusion Matrix of classes and Other details like f1_score, accuracy, precision, and recall are shown.</p><p><strong>Clustering Predictions</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Q0YTVCcADazVBnwu_dHGg.png" /><figcaption>Clustering Prediction</figcaption></figure><p>For Clustering, according to the model, a bar chart of the different class count is shown.</p><p><strong>Anomaly Detection Predictions</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PlAOwqz61Z9xWlP_p0endQ.png" /><figcaption>Anomaly Detection Predictions</figcaption></figure><p>For Anomaly Detection, a bar chart of <strong>Anomaly</strong> and <strong>Not Anomaly </strong>count is shown.</p><p><strong>Dimension Reduction Performance</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Hi7EX2p-rXOB5JOtoq1dQ.png" /><figcaption>Dimension Reduction Performance</figcaption></figure><p>For Dimension Reduction, aggregation of <strong>Variance</strong> for all components is shown.</p><h3>Step 6: Result</h3><p>Based on the problem type, the result is saved as a <strong>.csv </strong>file.</p><p>That’s the end of the show for now. I developed a simple application in view of providing an ML experience for normal users who are working in other domains.</p><p>This application can be used</p><ul><li>As a learning tool at beginning of the ML journey</li><li>For a quick understanding of dataset for Data Scientists or ML developers and many more.</li></ul><h4>Future Improvements</h4><p>This application can be extended by adding</p><ul><li>Support for Deep Learning</li><li>Web support</li><li>More ML models and types</li><li>Re-design UI for better user experience</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31d18ca84d89" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/automl-a-gui-application-to-make-ml-for-everyone-31d18ca84d89">AutoML — A GUI Application to Make ML for Everyone</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generate Quotes with Web Scrapping, Glove Embeddings, and LSTM in Pytorch]]></title>
            <link>https://pub.towardsai.net/quotes-generation-for-social-media-with-web-scrapping-glove-embeddings-training-and-lstm-in-e07c03491f15?source=rss-3ce01f4ebce8------2</link>
            <guid isPermaLink="false">https://medium.com/p/e07c03491f15</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[text-generation]]></category>
            <category><![CDATA[gloves]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[pytorch]]></category>
            <dc:creator><![CDATA[Lakshmi Narayana Santha]]></dc:creator>
            <pubDate>Mon, 06 Jan 2020 09:40:57 GMT</pubDate>
            <atom:updated>2020-10-26T07:05:16.472Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0oQqMCR0D4VFWVBr5UXWzg.png" /></figure><h3>Introduction</h3><p>With the rise of advancement in research in NLP specially in Language Models, text generation - a classical machine learning task which solved using Recurrent Networks.</p><p>In this article we walk through generate English Quotations from scratch using Word-level language model proceeding follows:<br>1. Web Scrapping to get a dataset<br>2. Glove Embedding training<br>3. LSTM model<br>4. Prediction</p><h3>Web Scrapping</h3><p>We use web scrapping to collect quotes from website <a href="http://www.wiseoldsayings.com/">Wise Old Sayings</a>. <br>This website almost 4000 quotes of different categories. I won’t tell how to do this in this article which is out of scope here. But it is legal to scrap from this website as ‘robots.txt’ allows.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4f0efa811a51a063b7c156a61145bfe1/href">https://medium.com/media/4f0efa811a51a063b7c156a61145bfe1/href</a></iframe><p>As the home page of this website lists all categories and crawling over each category is different from the only suffix to home URL, first, gather all categories and in the next step crawl over each category and extract quotes from pages.<br><strong>Note:</strong> A single category may contain multiple pages like page-1, page-2…</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d01a7fa423508b6253244bdfbbe39b59/href">https://medium.com/media/d01a7fa423508b6253244bdfbbe39b59/href</a></iframe><p><strong>I have uploaded these extracted quotes in Kaggle as a dataset.</strong></p><p><a href="https://www.kaggle.com/santhalnr/quotations">English Quotations</a></p><h3>Glove (Global Vectors for Word Representation)</h3><p>For language models mappings word to embeddings make dimension space low compared to one-hot vector encoding as Vocabulary size is very large.</p><p>The glove method captures both the global context and local context for word pairs.<br>Read more on Glove in a paper published <a href="https://nlp.stanford.edu/pubs/glove.pdf">here</a>.</p><p>Using <a href="https://nlp.stanford.edu/projects/glove/">pre-trained</a> Glove weights correctly represents word into dimensional space, but in this article, we implement our own Glove embeddings for word.<br>Words in vocabulary are represented as embeddings and trained with the Glove approach. So prepare vocabulary while getting quotes from the dataset in raw form.</p><pre>Read quotes with minimum word count of 5 (User Choice) to maintain minimum length quotation.<br>As quotes contain &#39;,&#39; &#39;.&#39;, and &#39;-&#39; next to a word like &quot;Ciao Bello, Howdy? &quot;, for better tokenization add space between words and special characters.<br>Also append &#39;;&#39; as end-of-quote token.</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd90137e64bfecf6105069948e9a24a2/href">https://medium.com/media/fd90137e64bfecf6105069948e9a24a2/href</a></iframe><p>In each quote take unique words and make vocabulary.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b413d5d6fcca92d86950903b17696c9/href">https://medium.com/media/0b413d5d6fcca92d86950903b17696c9/href</a></iframe><p>Also, words are cannot be used directly in the neural networks, map words to integers and integers to words for getting words back.</p><pre>To train glove embeddings we need co-occurance matrix between words in vocabulary.<br>Follow sliding window method by fixing window size (context range between words) iterating each quote, and calcuate similarity as a function of reciprocal of distance between two words with in window.</pre><p>The co-occurrence matrix captures the global context of words in the corpus. The co-occurrence matrix is a dictionary with word-pairs as keys and values as similarity_score.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/707/1*_Omm5m3k25JT7jOpspCtHA.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8cdbc917ff131141771bae85719e81ab/href">https://medium.com/media/8cdbc917ff131141771bae85719e81ab/href</a></iframe><p>Observe the distribution of similarity score between words:</p><pre>topk,ind=torch.topk(torch.tensor(list(co_occ_matrix.values())),200)<br>sns.distplot(topk)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/396/1*ne8jkRaqBbwTRtgnpS6x0A.png" /></figure><p>The plot shows the distribution of top 200 similarity scores which lies mostly below 100 this is due to less size of the corpus.</p><pre>elem_den = []<br>for i <strong>in</strong> co_occ_matrix.values():<br>    if i &gt; 0 <strong>and</strong> i &lt; 10:<br>        elem_den.append(i)<br>sns.violinplot(x = elem_den)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/361/1*mUcQK_l1QSbgUH2e08h8MQ.png" /></figure><p>Violin plot shows that most percentage of word-pairs presence in the corpus is very rare with similarity less than 1 for given context range 5.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/37b6d45058539ff69824932e61562753/href">https://medium.com/media/37b6d45058539ff69824932e61562753/href</a></iframe><p>These word-pairs stored in a dictionary as keys capture local context and we use these keys to train embeddings.</p><p>Glove tries to represent vector embeddings close to both global context and local context by moving dimensions of local context word pairs close to global context similarity.</p><p>Like all neural networks, Glove embeddings are trained by defining the loss function shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*rQKl31brZcR4VPqONfzCEg.png" /></figure><p>Imagine the part product and bias adding as classic MLP network outputs <br>y-hat and we train these vectors to reduce loss close to zero mapping y-hat to y which is log of similarity score here.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ff1cbe67f4968a4f8dca11bc47a73213/href">https://medium.com/media/ff1cbe67f4968a4f8dca11bc47a73213/href</a></iframe><p>The loss function is a custom loss with weighted summation where weights represent how much impact the current word-pair consists in calculating loss by reducing rare word-pair scores in reciprocal powers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*qdqYuuow-i3r64XAPhBsew.png" /></figure><p>In the above expression, alpha is less than one and word-pairs with similarity score less than the threshold similarity given less weight and similarity above threshold leaves as it is.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0f79aa6cec74bfb8fa6dd7da0b655d0d/href">https://medium.com/media/0f79aa6cec74bfb8fa6dd7da0b655d0d/href</a></iframe><p>We use 128 dimensions for word embeddings and train for only 100 epochs to avoid overfitting as the corpus size is small.</p><p>Input for Glove model is a vector representation of word-pairs in batches of shape <strong>( batch_size, indices_1, indices_2)</strong> where <strong>indices</strong> are numeric integers of words in given batch and Pytorch embeddings layer creates vector dimensions for these indices automatically of shape <strong>(vocab_len, num_dim)</strong>.</p><p>Weights trained in the Glove model are of shape <strong>(Vocab_len, num_dim)</strong> are embeddings for each word in vocabulary with dimensions <strong>num_dim.</strong></p><p>As we stored word-pairs duplicates as both <strong>a-b</strong> and <strong>b-a</strong> type to increase input size we simply add both weights <strong>Ui</strong> and <strong>Uj.</strong></p><pre>emb_i = glove.ui.weight.cpu().data.numpy()<br>emb_j = glove.uj.weight.cpu().data.numpy()<br>emb = emb_i + emb_j</pre><p><strong>emb </strong>is final word embeddings for words in the vocabulary of dimension <strong>(Vocab_len, num_dim).</strong></p><p>Visualize these embeddings by mapping high dimensional vector space to 2D using TSNE.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e6e24ae5f499a8ce1585b5b199b7ab26/href">https://medium.com/media/e6e24ae5f499a8ce1585b5b199b7ab26/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*VWWLFvCOcB5DaKq5PNKw7A.png" /><figcaption>First 100 Words representation in 2D</figcaption></figure><p><a href="https://colab.research.google.com/drive/1MlsQUliIUiyWe42gS5OkItwFpe-FuwpV">Google Colaboratory</a></p><p>Run model in Google Colab if it wants to.</p><h3>Quotation generation — LSTM Model</h3><p>Like all language models, sequences with variable length cannot directly feed to network as neural networks only accept fixed dimension inputs. For this, we take fixed-size sequence lengths and break extra sequences for the next input.<br>We follow the classic text generation model with passing a fixed input sequences and get the next word in sequence as output. We prepare the dataset by getting a fixed-size input sequence and output as the next word after the current sequence. We do this for all quotes in the corpus.</p><pre><strong>Ex:</strong> Sequence &quot;Love means never having to say you&#39;re sorry . ;&quot;<br>&#39;;&#39; is end-of-sequence. If fixed input length 7 then input and next word as output are</pre><pre>              input                              next word<br>_______________________________________    _________________________<br>Love means never having to say you&#39;re              sorry<br>means never having to say you&#39;re sorry               .<br>never having to say you&#39;re sorry .                   ;         </pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d5c833309b890ae4d35b540a820e8747/href">https://medium.com/media/d5c833309b890ae4d35b540a820e8747/href</a></iframe><p>We use a simple model to generate text with a single LSTM layer following the Dense layer to get probabilities for the next word with loss function Cross_Entropy_Loss.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b02bc0e5a6fdc4dc34946794c27489e3/href">https://medium.com/media/b02bc0e5a6fdc4dc34946794c27489e3/href</a></iframe><p>For each epoch <strong>cell_state (h_c)</strong> and <strong>hidden_activation (h_h) </strong>must re-initialize if not loss won’t decrease and there will be no training. As vocabulary size is very large and calculation values may large depend on network size using gradient clipping prevents the model from exploding gradient which results in <strong>nan </strong>as a loss.</p><h3>Generating Quotes</h3><p>After training model which outputs probabilities for next word for given input sequence, quote-generating is done by feeding initial seed to network to get probabilities for next word, these probabilities are sampled using technique <a href="https://towardsdatascience.com/how-to-sample-from-language-models-682bceb97277">temperature</a> and next word generated is added to the last index while removing the first word in previous input to maintain window size to feed into network. Repeat this until end-of-quote character as output or generated_length less than max_len.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/681dc3f8a7cbc2b4e555afd6ac7955ab/href">https://medium.com/media/681dc3f8a7cbc2b4e555afd6ac7955ab/href</a></iframe><p>With little training epochs, small size corpus and without hyper-parameter tuning model generated quote :</p><pre>&quot;there is no one love was . life being you&#39;ll or and the , is all her all heaven comes with order they to you . , you hurt get when hope that for , of the which for for no others having take being the gone free is me the by knows where for&quot;</pre><p>Kaggle Notebook:</p><p><a href="https://www.kaggle.com/santhalnr/quote-generation-glove-training-lstm-pytorch">Quote Generation Glove training+LSTM pytorch</a></p><p>Github repo:</p><p><a href="https://github.com/santhalakshminarayana/Quotation_Generation_Glove_LSTM_Pytorch">santhalakshminarayana/Quotation_Generation_Glove_LSTM_Pytorch</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e07c03491f15" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/quotes-generation-for-social-media-with-web-scrapping-glove-embeddings-training-and-lstm-in-e07c03491f15">Generate Quotes with Web Scrapping, Glove Embeddings, and LSTM in Pytorch</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Semantic Segmentation in PSPNet with implementation in Keras]]></title>
            <link>https://medium.com/analytics-vidhya/semantic-segmentation-in-pspnet-with-implementation-in-keras-4843d05fc025?source=rss-3ce01f4ebce8------2</link>
            <guid isPermaLink="false">https://medium.com/p/4843d05fc025</guid>
            <category><![CDATA[pspnet]]></category>
            <category><![CDATA[semantic-segmentation]]></category>
            <category><![CDATA[keras]]></category>
            <category><![CDATA[object-segmentation]]></category>
            <dc:creator><![CDATA[Lakshmi Narayana Santha]]></dc:creator>
            <pubDate>Mon, 18 Nov 2019 10:43:42 GMT</pubDate>
            <atom:updated>2020-06-02T05:27:10.408Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JcERmCEgvcm3QEwBNUKedQ.png" /></figure><p>For Image scene semantic segmentation PSPNet performs better than other semantic segmentation nets like FCN,U-Net,Deeplab.</p><p>In this article,we’ll discuss about PSPNet and implementation in Keras.</p><h3>Pyramid Scene Parsing Network (PSPNet)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*emYC4xYASMLb5bSHNLZHOg.png" /></figure><h4>a) Input Image</h4><p>Input image of any shape usually dimensions greater than (256, 256) feed to the network.</p><h4>b) Feature Map</h4><p>Takes input image and constructs feature maps for image. Feature maps are extracted by feeding image using transfer learning or scratch network with dilated convolutions. As large size kernels extracts more useful information than small size kernel but computation cost is higher, dilated convolutions gathers large size area information with small size kernel for higher <strong>dilation_rates</strong> to <strong>keep dimensions same</strong> as <strong>input Image</strong>.Generally <strong>residual blocks</strong> with <strong>dilations</strong> are used to construct feature maps.No.of feature maps <strong>N</strong> is a hyperparameter and needs to be tuned for good result.</p><h4>c) Pyramid Pooling Module</h4><p>An Image contains objects of sizes ranging from small area to large area in different regions.Fully Convolution Network(FCN),U-Net and other networks constructs feature maps by upsampling and doing segmentation at different levels for segmentation of all objects in all regions.But in PSPNet to correctly segment all size objects, feature maps are pooled average pooled at different pool size.</p><p>Sub-region average pooling is done at different scales like <strong>Global Average Pooling,(2*2),(3*3),(4*4),(6*6),(8*8)..</strong><br>After average pooling of<strong> N</strong> feature maps with <strong>n</strong> different sizes, feature maps at each level reduced to <strong>N/n</strong> feature maps by performing <strong>1*1</strong> convolutions.</p><p>For instance, if N=512 feature maps and n=4 sizes like Global Average Pooling,(2*2),(4*4),(8*8) then at each level 512 feature maps are reduced to 126 feature maps.</p><p>N/n feature maps at each level <strong>upsampled</strong> to have the <strong>same dimensions of input Image. </strong>For upsampling , bilinear_interpolation or convolution_transpose methods used instead simple upsampling.</p><p>Output of Pyramid Pooling Module is <strong>concatenation</strong> of base feature maps from <strong>b</strong> and upsampled average pooled feature maps from <strong>c</strong>.</p><h4>d) Final Prediction</h4><p><strong>2*N</strong> feature maps are feed to convolution layer and final prediction of classes are generated on how output layer is constructed say different channels for different objects or single channel.</p><h3>Implementation in Keras/Tensorflow</h3><p>Dataset we are applying semantic segmentation in PSPNet is on Kaggle’s <a href="https://www.kaggle.com/dansbecker/cityscapes-image-pairs">Cityscapes Image Pairs</a> dataset of size 106 Mb.</p><h4>Dataset</h4><p>Dataset contains two folders Training images (train) folder and Validation images (val) folder.In each folder each image is of shape <strong>(512, 256, 3 ) </strong>and <strong>width=512, height=256, channels=3</strong>. Where each image contains original image without segmentation and segmented image. Separate normal image into <strong>train_imgs, valid_imgs</strong> and segmented image into arrays <strong>train_masks, valid_masks</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b22e1dd319e1442aa4d2c99c8ec0db42/href">https://medium.com/media/b22e1dd319e1442aa4d2c99c8ec0db42/href</a></iframe><h4>Network Architecture</h4><p>A simple PSPNet architecture with following parameters,</p><p><strong>Module b</strong> constructed with 3 layers of Residual blocks with Dilation Convolutions outputs <strong>256 feature maps</strong>.</p><p><strong>Module C</strong> defined with <strong>pool_sizes GlobalAveragePooling, (2*2), (4*4), (8*8) </strong>and for<strong> Upsampling, bilinear_interpolation </strong>used. Each <strong>256 pooled feature maps</strong> are reduced to <strong>64 feature maps</strong> combining <strong>512 feature maps total</strong>.</p><p><strong>Module D</strong> is simply a convolution layer of 512 feature maps output <strong>(256,256,3) dimensional feature maps</strong> which are <strong>flattened</strong> into a single array of size (256*256*3).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b06155db75fc658910103c276b95020b/href">https://medium.com/media/b06155db75fc658910103c276b95020b/href</a></iframe><p><a href="https://www.kaggle.com/santhalnr/cityscapes-image-segmentation-pspnet">Cityscapes Image Segmentation PSPNet</a></p><h4>Predictions</h4><p>To keep things simple, Mean Square Error (MSE) as loss function to predict segmentation of images.</p><p>Model trained with batch_size=10 and optimizers Adam,SGD,Nadam with learning rates [ 0.001, 0.001 , 0.01] .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*_Nt4yGww4l7NG4jyDqEURQ.png" /><figcaption>1.Normal Image, 2. Original Mask, 3.Predicted Mask</figcaption></figure><p>I’ve trained model for less than 3 hrs. But results are not much bad.</p><h4>How can we improve?</h4><p>I’ve taken bare pixel values from (0–255), small network and loss function MSE which is not optimal for Segmentation tasks. By doing following will improve image segmentation.</p><ul><li>Large network with higher dilation_rates.</li><li>Construct output channels of size ‘c’ for <strong>c</strong> class by applying binary mask or simply numbering classes for only <strong>single</strong> channel.</li><li>Apply Categorical Cross Entropy for numbering of classes of <strong>single</strong> channel or any other loss function like Dice Loss, Weighted Cross Entropy, Focal Loss for <strong>c</strong> channel mask.</li><li>Tune parameters <strong>N, n and pool sizes .</strong></li></ul><p><a href="https://neptune.ai/blog/image-segmentation-in-2020">Image segmentation in 2020: Architectures, Losses, Datasets, and Frameworks | Neptune Blog</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4843d05fc025" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/semantic-segmentation-in-pspnet-with-implementation-in-keras-4843d05fc025">Semantic Segmentation in PSPNet with implementation in Keras</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Face Recognition with VGG-Face in Keras.]]></title>
            <link>https://medium.com/analytics-vidhya/face-recognition-with-vgg-face-in-keras-96e6bc1951d5?source=rss-3ce01f4ebce8------2</link>
            <guid isPermaLink="false">https://medium.com/p/96e6bc1951d5</guid>
            <category><![CDATA[face-recognition]]></category>
            <category><![CDATA[vgg-face]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[face-detection-opencv]]></category>
            <category><![CDATA[tensorflow-keras]]></category>
            <dc:creator><![CDATA[Lakshmi Narayana Santha]]></dc:creator>
            <pubDate>Wed, 16 Oct 2019 16:48:09 GMT</pubDate>
            <atom:updated>2019-10-21T09:21:09.914Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*j-sma006c-c8NPPbt3LSSA.jpeg" /></figure><h3>1. Get dataset/images of persons.</h3><p>I have collected images of top 5 most powerful leaders in the world Donald Trump, Vladimir Putin, Xi Jinping, Angela Merkel, Narendara Modi. Train dataset contains 10 images of each person and also to check model working also included my images. Name this folder as “Images” .</p><h3>2.Detect faces in image.</h3><p>To get better predictions we first detect faces in image and use only faces for recognition. To do so we first detect faces in an image,for this we use ‘mmod_human_face_detector’ a cnn_face_detector which identifies faces in image and returns position of each face in image with finding rectangle bounding box as (left,top,right,bottom) positions. ‘dlib’ in python uses these weights and detect images,but dlib doesn’t provide this detector as in-built. We must download and provide to ‘dlib’ classes for extracting face. Download mmod_human_face_detector from here</p><blockquote><a href="http://dlib.net/files/mmod_human_face_detector.dat.bz2">‘http://dlib.net/files/mmod_human_face_detector.dat.bz2&#39;</a></blockquote><p>As it is .bz2 file,extract it</p><pre>$ wget <a href="http://dlib.net/files/mmod_human_face_detector.dat.bz2">http://dlib.net/files/mmod_human_face_detector.dat.bz2</a> <br>$ bzip2 -dk mmod_human_face_detector.dat.bz2 </pre><h3>3. Extract faces from images.</h3><p>Extract face from images,crop face and store as image in separate folder with image name as person name.</p><p>We use images with only one face</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/052607e6bda7047beb8fdbe186c3bd44/href">https://medium.com/media/052607e6bda7047beb8fdbe186c3bd44/href</a></iframe><p>Above snippet shows how to extract face from image and save them for recognition. Do the same for all images in train dataset and test dataset saving with person names as image names. Store each person cropped image in a separate folder like Ex: All ‘modi_*.jpg’ images are saved in ‘modi’ folder.</p><p>After extracting faces directory structures looks like:</p><pre>Directory structure :<br>|Images /<br>|  |-- (60 images)<br>|Images_crop /<br>|  |--angelamerkel (10 images)<br>|  |--jinping / (10 images)<br>|  |--lakshminarayana / (10 images)<br>|  |--modi / (10 images)<br>|  |--putin / (10 images) <br>|  |--trump / (10 images)<br>|Images_test / <br>|  |-- .. / (18 images)<br>|Images_test_crop / <br>|  |--angelamerkel / (3 images)<br>|  |--jinping / (3 images)<br>|  |--lakshminarayana / (3 imgaes)<br>|  |--modi / (3 images)<br>|  |--putin / (3 images) <br>|Face_Recognition.ipynb<br>|mmod_human_face_detector.dat</pre><h3>4.Use VGG-face model to create embeddings for faces.</h3><p>We create embeddings for each face/person which defines the person in numeric data. Pre-trained networks like DeepFace,OpenFace provides embeddings in less than 5 lines of code. But we use VGG_Face_net which trained on millions of images to recognize labelled faces in the wild (LFW). The original model takes an image in WildFace dataset on which VGG_face_net trained and classifies/recognize person in image. It ouputs 2622 embeddings for an image,we take this 2622 embeddings for each cropped_image for later classification of image. VGG_face_net weights are not available for tensorflow or keras models in official <a href="https://www.robots.ox.ac.uk/~vgg/software/vgg_face/">site</a>, in this <a href="https://sefiks.com/2018/09/03/face-recognition-with-facenet-in-keras/">blog</a> .mat weights are converted to .h5 file weights.<br>Donwnload .h5 weights file for VGG_Face_net here</p><blockquote><a href="https://drive.google.com/uc?id=1CPSeum3HpopfomUEK1gybeuIVoeJT_Eo">‘https://drive.google.com/uc?id=1CPSeum3HpopfomUEK1gybeuIVoeJT_Eo’</a></blockquote><p>As it stored in google drive,we can download to our local storage with python ‘gdown’ package.</p><pre>$ gdown https://drive.google.com/ucid=1CPSeum3HpopfomUEK1gybeuIVoeJT_Eo </pre><p>We have .h5 vgg_face_net weights now and use it to build vgg_face_net model in keras/tensorflow.</p><h3>5.Build vgg_face_architecture and get embeddings for faces.</h3><p>To loal weights for model we must define model architecture. VGG_Face model in keras as</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d24f263a49ba04df898c363d42a33d06/href">https://medium.com/media/d24f263a49ba04df898c363d42a33d06/href</a></iframe><p>In the output layer they used softmax layer for recognising image in WildFaces dataset. We do only require embeddings which are output for last but one layer i.e,. Flatten() layer. So our model requires upto last Flatten() layer.</p><pre># Remove last Softmax layer and get model upto last flatten layer #with outputs 2622 units </pre><pre>vgg_face=Model(inputs=model.layers[0].input,outputs=model.layers[-2].output) </pre><p>In the above line we defined model upto Flatten() layer. Now we can feed any image to get embeddings which will be used to train our own classifier/recognizer.</p><h3>6. Prepare train data and test data</h3><p>Prepare train data and test data which contains embeddings as rows for each face and label as person name.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/978f4b1816c97903b6a9b725a3dcfef8/href">https://medium.com/media/978f4b1816c97903b6a9b725a3dcfef8/href</a></iframe><p>Earlier we stored each cropped face image in corresponding person folder, walk through each folder and in each folder for each image, load image from keras in-built function load_img() which is PIL image with <br><strong>target_size=(224,224)</strong>, since VGG_face_net expects image shape in (224,224) format. For each loaded image it is preprocessed into scale of [<strong>-1,1] </strong>and feed into vgg_face() model which outputs <strong>(1,2262)</strong> dimensional Tensor, it is converted into list and append to train and test data. Also,for each person we label that person in numeric number like</p><blockquote>Ex: { 0: ‘modi’, 1: ‘trump’, 2: ‘angelamerkel’, 3: ‘jinping’, …. …. }</blockquote><p>We got (x_train, y_train) and (x_test, y_test) as lists ,to use in keras models we first convert them to numpy arrays.</p><pre>x_train=np.array(x_train) <br>y_train=np.array(y_train)<br>x_test=np.array(x_test) <br>y_test=np.array(y_test) </pre><h3>7. Train softmax classifier.</h3><p>We end up with train data and test data with face embeddings and labels as person encodings. Now we train simple softmax classifier and save model to get predictions for unseen image face in dataset.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a66197a53a3fcfbd806bfc00c17597a/href">https://medium.com/media/6a66197a53a3fcfbd806bfc00c17597a/href</a></iframe><p>We trained softmax classifier to classify image, it takes face embeddings as input and outputs corresponding image number which is encode for person name.</p><p><a href="https://github.com/santhalakshminarayana/face-recognition">santhalakshminarayana/face-recognition</a></p><h3>8. Recognize faces.</h3><p>Now we can recognize any face in image if we get embeddings for face with help of vgg_face model and feed into to classifier then get person name. With opencv draw rectangle box around face and write person name for each face in image.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/453f09f8c96458f2ea29dde2d9e3cad6/href">https://medium.com/media/453f09f8c96458f2ea29dde2d9e3cad6/href</a></iframe><p>In above snippet it takes image path and outputs recognized faces in image with rectangle box around face and person name.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*OXK5dLfFmeMzlgsNIPV9Ow.png" /></figure><p>My Image</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/359/1*6AZZIP_cFtkTOjrLODxjdg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=96e6bc1951d5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/face-recognition-with-vgg-face-in-keras-96e6bc1951d5">Face Recognition with VGG-Face in Keras.</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build working web app for Image documents to scanned PDF document conversion using Python.]]></title>
            <link>https://medium.com/analytics-vidhya/build-working-web-app-for-image-documents-to-scanned-pdf-document-conversion-using-python-5badf2c1e4eb?source=rss-3ce01f4ebce8------2</link>
            <guid isPermaLink="false">https://medium.com/p/5badf2c1e4eb</guid>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[opencv-python]]></category>
            <category><![CDATA[herokuapp]]></category>
            <category><![CDATA[pdf-to-image]]></category>
            <dc:creator><![CDATA[Lakshmi Narayana Santha]]></dc:creator>
            <pubDate>Fri, 27 Sep 2019 19:31:42 GMT</pubDate>
            <atom:updated>2019-10-22T09:01:04.066Z</atom:updated>
            <content:encoded><![CDATA[<h3>Build a Web App to convert Image document to scanned PDF document using Python</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R4zi-4vF8g9NUn3bWjTq4w.jpeg" /><figcaption>Image Credits:21Wallpaper:<a href="https://d3n32ilufxuvd1.cloudfront.net/5a46aa90c9cbeb0b048db35b/1404778/upload-70fe63fc-930d-4ad4-b79b-d75a77084cd2.jpg">https://d3n32ilufxuvd1.cloudfront.net/5a46aa90c9cbeb0b048db35b/1404778/upload-70fe63fc-930d-4ad4-b79b-d75a77084cd2.jpg</a></figcaption></figure><p>This article is about converting multiple Images of text documents to scanned PDF document and deploying this model as Web app using Flask in Python.</p><h3>Setup Virtual Environment for our project</h3><pre>$ pip install virtualenv</pre><p>Create virtual environment and name it “imagetopdf”</p><pre>$ virtualenv imagetopdf</pre><p>Activate our virtual environment</p><pre>$ source imagetopdf/bin/activate</pre><p>Move to our project folder “imagetopdf” and create a new folder “app”.<br>All our files are stored in this directory with path<br>“~/../imagetopdf/app/ “</p><pre>$ cd imagetopdf &amp;&amp; mkdir app &amp;&amp; cd app</pre><p>Now install required dependencies</p><pre>$ pip install opencv-python<br>$ pip install PIL<br>$ pip install scikit-image</pre><p>Open text editor and create a python file with name “imagetopdf.py”</p><h3>Import packages</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/47e43f1be8ad06eb512c66b709309852/href">https://medium.com/media/47e43f1be8ad06eb512c66b709309852/href</a></iframe><h3>Load Images using cv2 and covert to binary images</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3a9ed8a9be0f9d4daaa49b8ec0cd6851/href">https://medium.com/media/3a9ed8a9be0f9d4daaa49b8ec0cd6851/href</a></iframe><p>Load images in current working directory with file extensions .jpeg, .png, .jpg<br>as cv2 arrays which are usually in format “BGR”.Insert all images in a list by loading from directory.</p><p><strong>NOTE: </strong>PDF pages are constructed in the same order as reading images from directory. So, images with names ‘img_1’,’img_2&#39;,….. makes sense of desired order of images.</p><p>For better image operations convert “RGB” images to binary images.</p><pre>img_gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)</pre><p>converts image from ‘rgb’ format to ‘gray’ scale.</p><pre>clahe=cv2.createCLAHE(clipLimit=4.0,tileGridSize=(16,16))<br>img_gray=clahe.apply(img_gray)</pre><p>above lines improve image contrast by applying <a href="https://docs.opencv.org/master/d5/daf/tutorial_py_histogram_equalization.html">“Histogram Equalization”</a></p><pre>ret,th=cv2.threshold(img_gray,130,255,cv2.THRESH_BINARY)<br>thsh_images.append(th)</pre><p>apply image threshold to gray scale image with threshold_value=130 and store binary images in list.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*acMMiZTCxJDMG8qcz-ygEA.jpeg" /></figure><h3>Find contours in image and fit Maximum area contour to image</h3><p>There may cases of image not taken with area of interest only that is image contains other content and background which not desired and should be scaled to single page only.Like below image which contains background and some part of next page</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*LQF5ozGShL0ztTzcd3UQEA.jpeg" /></figure><p>To get only important content from image we extract our area of interest from using contours in opencv.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/31178a481f398b82eca2535bdb8ab909/href">https://medium.com/media/31178a481f398b82eca2535bdb8ab909/href</a></iframe><p>Since our area of interest is largest area of an image, it can be identified using maximum contour area which can be close to rectangle shape.For each image get maximum area contour which is our single page document of image and fit that contour to image which is same as drawing something in image.</p><pre>contours,_=cv2.findContours(img.copy(),cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)</pre><p>cv2.RETR_TREE method finds contours in hierarchy order and cv2.CHAIN_APPROX_SIMPLE just fits outline position co-ordinates of contour which describes entire contour instead entire contour co-ordinates which takes more space.</p><pre>area=cv2.contourArea(cnt)<br>if area &gt; max_area:<br>   max_area=area<br>   max_ind=ind</pre><p>retrieves the area of each contour and finds maximum area of contour to fit like below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*HCb5PbKQbBmMyzhB2hTeVg.jpeg" /></figure><h3>Draw closest rectangle shape to maximum contour which usually describes a page of PDF</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8874a66b7660e938628fb84fff8b95d2/href">https://medium.com/media/8874a66b7660e938628fb84fff8b95d2/href</a></iframe><p>Fitted contours can be any shape but we are looking for rectangle shape which is the shape of normal screens of desktop,smart phones…</p><pre>epsilon=0.02*cv2.arcLength(image_conts[ind[max_area_conts[ind]],True)<br>approx=cv2.approxPolyDP(image_conts[ind[max_area_conts[ind]],epsilon,True)</pre><p>above lines finds the closest rectangle points for our fitted maximum area contour like below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*lGDbcuQORMS6zAUJn9thOQ.jpeg" /></figure><h3>Using perspective transformation transform four sides of rectangle to full co-ordinates of an image</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/33bf5feb5df9826912ee7406bb325492/href">https://medium.com/media/33bf5feb5df9826912ee7406bb325492/href</a></iframe><p>We end up with a rectangle shape contour which is area of interest.Now enlarge or extract this rectangle shape only like from img1 to img2</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*9CITlMSvJQbDX19oVq29Kg.jpeg" /><figcaption>img1 : original image with unwanted background</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*9GoBFFOZ71jEvhgUgaXt0A.jpeg" /><figcaption>img2: all background is removed for some extent</figcaption></figure><h3>Improve gray scale image contrast using scikit-image and save images</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/65148817afd19cbbf7dde44bb9d2ef59/href">https://medium.com/media/65148817afd19cbbf7dde44bb9d2ef59/href</a></iframe><pre>th=threshold_local(img_gray.copy(),101,offset=10,method=”gaussian”)</pre><p>$ pip install gunicorn<br>$ echo “web: gunicorn -w 4 -b “0.0.0.0:$PORT” app:app” &gt; Procfileabove scikit-image’s threshold_local() function increases low contrast image very high contrast like from img1 to img2 below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*tdq5yOhIA2A6OF8fFyVZMQ.jpeg" /><figcaption>img1: low contrast image</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*mKT_dpysIce4wa3sSC41aA.jpeg" /><figcaption>img2: improved image contrast</figcaption></figure><p>save high contrast images with name “digitised_+ original name“ of image which helps in finding images to convert as PDF.</p><h3>Load saved high contrast images and save as PDF using PIL</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/28cf462ae22aabba25115b261e449d4f/href">https://medium.com/media/28cf462ae22aabba25115b261e449d4f/href</a></iframe><p>Load saved images with prefix “digitised_” with PIL Image and save them as PDF document.</p><h3>Make Web Interface using Flask</h3><p>Install Flask and Werkzeug</p><pre>$ pip install Flask</pre><p>Flask is a light weight framework for building simple back end app engines in python.</p><p>A flask model typically contains following skeleton.</p><pre>from flask import Flask <br> <br>app = Flask(__name__)   </pre><pre>@app.route(&quot;/&quot;) <br>def hello():     <br>    return &quot;Hello World!&quot;   </pre><pre>if __name__ == &#39;__main__&#39;:     <br>    app.run(debug=True)</pre><p>First line imports Flask class from flask package, <br>Second line creates app object for Flask class with “__name__” which is home url for our app,<br>Third line defines a decorator that routes for any name after prefix that is home url with “/” like <a href="http://home/,">http://home/,</a><br>Fourth and fifth lines defines a function that must be executed for above decorator,<br>Seventh line runs our app engine with ‘debug=True’ means debug mode on.<br>If we run this script with filename saved as “app.py” and if there is no errors we can see screen like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*ZPT04uKRNXxIXJNg9207qA.png" /></figure><p>To test our app, open browser and type “localhost:5000”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/331/1*AWoKrPfSWRElBfQdRt8fKA.png" /></figure><p>Now to deploy our model make changes to “app.py” file with HTML to add interface to take files from user like</p><pre>&quot;index.html&quot;</pre><pre>&lt;html&gt;<br>    &lt;head&gt;<br>    &lt;/head&gt;<br>    &lt;body&gt;   <br>        &lt;!-- File Uploading--&gt;  <br>        &lt;form action=&#39;/uploadimages&#39; method=&quot;POST&quot;  <br>                       enctype=&quot;mutlipart/form-data&gt;              <br>            &lt;input type=&quot;file&quot; name=&quot;files&quot; multiple /&gt;   <br>            &lt;input value=&quot;Upload&quot;&gt;<br>        &lt;/form&gt;<br>     &lt;/body&gt;<br>&lt;/html&gt;</pre><p>In above snippet, in &lt;form action=”/uploadimages” …… &gt; , the part “/uploadimages” states where should app engine route when this form is submitted. Here “uploadimages” is name of the app.route(“/uploadimages”) decorator we define function to handle this file request.</p><p>To handle HTML file request we must save our HTML file in a separate folder with name “templates” which would be identify by Flask for routing HTML pages. You can add more CSS, JS ,JQuery,Bootstrap and media content like Images,Videos etc., but all these files must save in another folder with name “static”.</p><p><strong>NOTE:</strong>Change “imagetopdf.py” by adding class with name “Imagetopdf” whose function “convert()” contains all our previous code to convert Images to PDF.</p><pre>from flask import Flask,requests,render_template,send_from_directory<br>from imagetopdf import Imagetopdf<br>import os</pre><pre>app=Flask(__name__)</pre><pre>@app.route(&#39;/uploadimages&#39;, methods=[&#39;POST&#39;,&#39;GET&#39;])<br>def uploadimages():<br>    file_names=[]<br>    curr_path=os.getcwd() <br>    files_in_dir=os.listdir()<br>    for file in file_names:<br>        if file.split(&#39;.&#39;)[-1] is in [&#39;jpeg&#39;,&#39;png&#39;,&#39;jpg&#39;,&#39;pdf&#39;]:<br>            os.remove(file)<br>    uploaded_files=request.files.getlist(&quot;files&quot;) <br>    for file in uploaded_files:  <br>        if file.filename.split(&#39;.&#39;)[-1] is in [&#39;jpeg&#39;,&#39;png&#39;,&#39;jpg&#39;]:<br>            file.save(file.filename)<br>    imagetopdf_obj=imagetopdf.Imagetopdf()<br>    imagetopdf.convert()<br>    try:<br>        return send_from_directory(curr_path,&#39;digitised_images.pdf&#39;,<br>                                             as_attachment=True)<br>    except Exception:<br>        abort(404)                     </pre><pre>@app.route(&quot;/&quot;)<br>def index():<br>    render_template(&quot;index.html&quot;)</pre><pre>if __name__ == &quot;__main__&quot;:<br>    return app.run(debug=True)</pre><p>In the above snippet we change our “app.py” by adding file requests handling routine.We first removes any previous Image or PDF files and then saves uploaded images which uses our “imagetopdf.py” to convert to PDF.</p><h3>Deploy to web with Heroku free hosting</h3><p>Install Heroku CLI with command</p><p>$ sudo snap install --classic heroku</p><p>Before that create an account in <a href="https://www.heroku.com/">Heroku</a></p><p>Login into your Heroku account</p><pre>$ heroku login -i</pre><p>Now create an app engine in Heroku</p><pre>$ heroku create {name of your app}</pre><p>Go to project directory “app” of our virtual environment where our files and other sub directories structure be</p><pre>app<br>--templates<br>--static<br>-app.py<br>-imagetopdf.py</pre><p>Create a “Procfile” as with text “web: gunicorn -w 4 -b “0.0.0.0:$PORT” app:app”. To do so , first install ‘gunicorn’</p><pre>$ pip install gunicorn<br>$ echo “web: gunicorn -w 4 -b “0.0.0.0:$PORT” app:app” &gt; Procfile</pre><p>As our app requires dependencies Heroku installs these if provided in a separate file called “requirements.txt”. This dependencies can be easily retrieved with command “pip freeze” and save it to file “requirements.txt” as</p><pre>$ pip freeze &gt; requirements.txt</pre><p><strong>IMPORTANT NOTE :</strong>OpenCv errors like <br>“can’t import shared library libsm.co.6 …..” <br>may encounter if deployed directly to Heroku.This can be handled by changing <br>“opencv-python==4.1.1.26” to “opencv-python-headless==4.1.1.26” in “requirements.txt” file. This changes state of using GPU support by Opencv to CPU only.</p><p>Now our files structure looks like</p><pre>app<br>--templates<br>--static<br>-app.py<br>-imagetopdf.py<br>-Procfile<br>-requirements.txt</pre><p>We are good to deploy our app to Heroku though ‘git’.</p><pre>$ git init<br>$ heroku git:remote -a {name of your app}<br>$ git add . <br>$ git commit -m “some message”<br>$ git push heroku master</pre><p>Check logs in Heroku dashboard about successful build. If everything goes right our app is now a deployed to web and anyone can access this using url<br>“https://{nameofourapp}.herokuapp.com/”</p><p>Here is link for site I deployed my model <a href="https://imagetopts.herokuapp.com/imagetopdf">https://imagetopts.herokuapp.com/imagetopdf</a> (works only imagetopdf feature)</p><p><strong>Note:</strong> Upload small size images as free accounts may face timeout errors and <br>it takes 20 seconds to re-start from sleep state as we haven’t subscribed.</p><p>One can also test locally using command</p><pre>$ heroku open</pre><p>If not started or got application errors check logs using command</p><pre>$ heroku logs -t </pre><p>Check my Github repository which I added two other features Imagetotext and Imagetospeech.</p><p><a href="https://github.com/santhalakshminarayana/image-to-pdf-text-speech">santhalakshminarayana/image-to-pdf-text-speech</a></p><p>Feel free to connect<br><a href="https://www.linkedin.com/in/santhalakshminarayana/">Linkedin</a> <a href="https://github.com/santhalakshminarayana">Github</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5badf2c1e4eb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/build-working-web-app-for-image-documents-to-scanned-pdf-document-conversion-using-python-5badf2c1e4eb">Build working web app for Image documents to scanned PDF document conversion using Python.</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>