<?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 Mikal Shrestha on Medium]]></title>
        <description><![CDATA[Stories by Mikal Shrestha on Medium]]></description>
        <link>https://medium.com/@mikalshrestha?source=rss-4aaab36b00a8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*7_pFU2t7sP-lOH0c.jpg</url>
            <title>Stories by Mikal Shrestha on Medium</title>
            <link>https://medium.com/@mikalshrestha?source=rss-4aaab36b00a8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 19:10:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mikalshrestha/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[End to End LLM Application in Local using Llama2 , Flask and Android]]></title>
            <link>https://mikalshrestha.medium.com/end-to-end-llm-application-in-local-using-llama2-flask-and-android-6bbe0ec0730d?source=rss-4aaab36b00a8------2</link>
            <guid isPermaLink="false">https://medium.com/p/6bbe0ec0730d</guid>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[llama-2]]></category>
            <category><![CDATA[flask]]></category>
            <dc:creator><![CDATA[Mikal Shrestha]]></dc:creator>
            <pubDate>Mon, 08 Apr 2024 15:41:08 GMT</pubDate>
            <atom:updated>2024-04-08T15:41:08.788Z</atom:updated>
            <content:encoded><![CDATA[<h3>End to End LLM Application in Local using Llama2 , Flask and Android</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*00Y4qXzXm4GFu_elzzLg1w.png" /></figure><p>In this story, I will explain and guide you through how to implement the end to end LLM applications by leveraging Llama2 model with Langchain framework, Flask server and Android mobile application.</p><p>In recent years, large language models (LLMs) have revolutionized the field of natural language processing (NLP), enabling machines to understand and generate human-like text with remarkable accuracy. With the advent of tools like Llama2, Flask, and Android, now we have the opportunity to harness the full potential of these models and integrate them seamlessly into real-world applications.</p><p>In this article, we’ll delve into constructing a real-world application powered by the impressive Llama2 LLM. We’ll utilize Flask to create a robust backend API and develop a sleek Android frontend to deliver a seamless user experience.</p><p>If you have basic knowledge of large language models, langchain framework and making REST API with Flask and building android applications would be better to grab this stories.</p><h4>Tech Stack</h4><p><strong>Llama2</strong>: Open-source LLM from Meta AI provides the core intelligence for our text processing tasks.<br><strong>LangChain</strong>: LangChain is a framework designed to simplify the creation of applications using large language models . It offers modularity and abstractions, making it easier to build complex chains of LLM calls, incorporate external data sources, and manage different memory formats.<br><strong>Flask</strong>: A lightweight Python web framework, perfect for building a RESTful API to interact with our LLM.<br><strong>Android</strong>: We’ll use Kotlin to craft a user-friendly Android application that communicates with our Flask backend.</p><p>For more about llama2 and finetuning llama2, go through my previous <a href="https://medium.com/@mikalshrestha/how-to-make-own-conversational-ai-system-by-fine-tuning-llama2-llm-model-e01faa03e81c">article</a>.<br><a href="https://medium.com/@mikalshrestha/how-to-make-own-conversational-ai-system-by-fine-tuning-llama2-llm-model-e01faa03e81c">https://medium.com/@mikalshrestha/how-to-make-own-conversational-ai-system-by-fine-tuning-llama2-llm-model-e01faa03e81c</a></p><h4>Langchain and Llama2</h4><p>LangChain is a framework that simplifies the process of creating generative AI application interfaces. LangChain streamlines this process. For example, LLMs have to access large volumes of big data, so LangChain organizes these large quantities of data so that they can be accessed with ease. In this story, Langchain is used to fetch the response from llama2 model with the help of CTransformers and PromptTemplate APIs. The following function will generates the response based on input query from the llama2 model. Download llama2 model on local machine and add model into models folder of your root project.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/35c28c8c01ddfb9edc19bc4a3b77226d/href">https://medium.com/media/35c28c8c01ddfb9edc19bc4a3b77226d/href</a></iframe><p>CTransformers is a library focused on providing high-performance bindings for Transformer models built in C/C++ using the GGML library.<br>It aims to deliver faster execution times compared to some traditional Transformer implementations.</p><p>Initialize CTransformers with model, model_type and config.<br><strong>Model</strong>: Loads the specified LLM (Llama-2 7B variant) from the file “llama-2–7b-chat.ggmlv3.q2_K.bin’. which is quantized version of Llama2 7B model.<br><strong>Model Type: </strong>llama.<br><strong>Config</strong>: max_new_tokens: Limits the maximum number of new tokens (roughly words or word parts) the model can generate in its response to 256.<br>temperature: Controls the randomness/creativity of the responses. A low temperature (0.01 here) means more predictable, less surprising text.<br><strong>Prompt Template:<br></strong>template = “””{input_text}”””<br>Defines a very simple template where the provided input_text will be inserted. This is where you would build more elaborate prompts to guide how the LLM processes the text.<br>Prompt templates are predefined recipes for generating prompts for language models. A template may include instructions, few-shot examples, and specific context and questions appropriate for a given task. LangChain provides tooling to create and work with prompt templates. LangChain strives to create model agnostic templates to make it easy to reuse existing templates across different language models. Typically, language models expect the prompt to either be a string or else a list of chat messages.<br><strong>Response Generation:<br></strong>response = llm(prompt.format(blog_style=blog_style, input_text=input_text, no_words=no_words))<br>This is where the magic happens!<br>The prompt.format(…) fills in the template based on the provided parameters.<br>The llm object is called with the formatted prompt, and it produces the actual LLM response.</p><h4>Making REST API with Flask</h4><p><strong>Step 1</strong>: Navigate to root folder of your project and create requirements.txt file and add all required dependencies as follows::<strong><br></strong>sentence-transformers<br>ctransformers<br>langchain<br>flask<br><strong>Step 2</strong>: To install all dependencies, hit following command in terminal:<br>pip install -r requirements.txt</p><p><strong>Step 3</strong>: Create a REST API<br>Create an app.py file in root folder of your project and initialize Flask app as:<br>app = Flask(__name__)<br>Make generate_response() function in app.py:<br>@app.route(&#39;/llm/generate_text&#39;, methods=[&#39;POST&#39;]): Defines a route within the Flask application. The /llm/generate_text URL will trigger the generate_response function. It only accepts POST requests. Which handles the logic to retrieve data from the incoming POST request, call an external LLM (Large Language Model) to generate text and format the generated text into a JSON response.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2f628e903edb8290a61c9a3d6c7fbd07/href">https://medium.com/media/2f628e903edb8290a61c9a3d6c7fbd07/href</a></iframe><p><strong>Step 4: </strong>Test API<br>To run Flask application, open a terminal, navigate to your project directory, and run:<br>python app.py<br>This will start a development server with url: <a href="http://127.0.0.1:5000/llm/generate_text">http://127.0.0.1:5000/llm/generate_text</a><br>Testing on Postman as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O_2ldGJ7Mvscysw_sE3rhw.png" /></figure><p><strong>Making Android App: ChatLlama</strong></p><ul><li>Download and install Android Studio from the official website <a href="https://developer.android.com/studio?gad_source=1&amp;gclid=Cj0KCQjwq86wBhDiARIsAJhuphmlri3ixYVgq8uAqZAYh0QEXuKRWetwo4Qz3QF7bXgmXIAisgMdydMaAtFiEALw_wcB&amp;gclsrc=aw.ds">here</a>. And Open Android Studio and create a new project. Add dependencies like Retrofit (REST client), OkHttp, Gson, etc.</li><li>Design Chat layout.</li><li>Create a data class ChatModelRequest.kt and ChatModelResponse.kt to sent payload to server and get response from the server.<br>- request payload format:<br>{<br> “input_text”: “What is the modern sense of abduction concerned with?”,<br> “no_words”: “100”,<br> “blog_style”: “Test”<br>}</li></ul><p>- response format:<br>{<br>“response”: “test response”<br>}</p><blockquote>Create an ApiService.kt file. Define a function that outlines the API call&#39;s structure.</blockquote><pre>interface ApiService {<br><br>    @POST(&quot;llm/generate_text&quot;)<br>    fun createPost(@Body post: ChatModelRequest): Call&lt;ChatModelResponse&gt;<br>}</pre><blockquote>Create a MainActivity<em>.kt</em> and create all required variables and initialize it. Configure Retrofit with baseUrl and Okhttp client and make api call as follows with required payload to get the response. Almost 4–5 minutes time were taken to get the response in my local machine so timeout is set as 10 minutes while configuring Okhttp client.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/25b192ef891044fa2a886a6acefc76e3/href">https://medium.com/media/25b192ef891044fa2a886a6acefc76e3/href</a></iframe><p>That’s it run android app on emulator or you can run on real device(baseUrl must be your assigned hosted IP address in case of real device and both PC and mobile device must be connected on same network)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*rj5JnTuXuxeA1UEHHbqGUQ.jpeg" /></figure><p><strong>Demo (Running on Emulator)</strong></p><p>prompt-1: “Give me a step by step process to cook chicken biryani with recipe”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*dvTZmkVCgOuFPSyxynogmw.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*1K_q1t_wcPOtQ6RQBWiGLQ.gif" /></figure><p>If you stuck on any point, checkout my github repo for reference.<br><a href="https://github.com/mikalshrestha/ChatLlama">https://github.com/mikalshrestha/ChatLlama</a></p><p>If you have any other queries, feel free to comment down and give thumbs up if you really like it. Thanks 🙏 . Happy Learning.</p><ul><li><a href="https://github.com/mikalshrestha/ChatLlama">GitHub - mikalshrestha/ChatLlama: End to End LLM Application with Llama2, Flask and Android.</a></li><li><a href="https://github.com/marella/ctransformers">GitHub - marella/ctransformers: Python bindings for the Transformer models implemented in C/C++ using GGML library.</a></li><li><a href="https://llama.meta.com/llama2/">Llama 2</a></li><li><a href="https://huggingface.co/meta-llama/Llama-2-7b">meta-llama/Llama-2-7b · Hugging Face</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6bbe0ec0730d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to make own Conversational AI System by Fine-tuning Llama2 LLM model?]]></title>
            <link>https://mikalshrestha.medium.com/how-to-make-own-conversational-ai-system-by-fine-tuning-llama2-llm-model-e01faa03e81c?source=rss-4aaab36b00a8------2</link>
            <guid isPermaLink="false">https://medium.com/p/e01faa03e81c</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[llama-2]]></category>
            <category><![CDATA[conversational-ai]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[transformers]]></category>
            <dc:creator><![CDATA[Mikal Shrestha]]></dc:creator>
            <pubDate>Wed, 06 Mar 2024 01:25:24 GMT</pubDate>
            <atom:updated>2024-03-06T01:25:24.667Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/735/1*t8z3uvYwLYdhKteDDdAtGw.jpeg" /></figure><p>So, you’ve decided to explore into the world of large language models, because why not add another one to the options already out there, right? Well, fear not <a href="https://emojipedia.org/face-with-tears-of-joy">😂</a>, because In this story I will sharing you how to make your own conversational AI system by fine tuning Llama2 model for own custom dataset.</p><p>The world of large language models (LLMs) is rapidly evolving, and with it comes exciting opportunities to build powerful applications. One such application is a Question Answering (QA) system like ChatGPT, where users can ask questions and receive relevant answers from a specific domain.</p><p>The Llama2 model is an open-source Large Language Model developed by Meta and built upon the Transformer architecture with Billions of parameters. It excels in various tasks like text summarization, question answering, and machine translation. To know more about Llama2 model checkout: <a href="https://llama.meta.com/">https://llama.meta.com/</a></p><p><strong>Why Fine-tuning?</strong></p><p>Fine-tuning involves taking a pre-trained model and further training it on a specific task or dataset. This process allows the model to adapt to the target task, resulting in better performance. By fine-tuning Llama2 on a QA dataset, we can tailor it to excel in answering questions accurately.</p><p><strong>Dataset</strong></p><p>For this fine tuning, I will be using <a href="https://huggingface.co/datasets/sayhan/strix-philosophy-qa?row=0">sayhan/strix-philosophy-qa</a> dataset. This dataset have three columns with category, question and answer representing philosophical texts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JjUZ04OLKpEWXo9NVv9kwA.png" /><figcaption>Original dataset format</figcaption></figure><p><strong>Data Pre-Processing</strong></p><p>Before fine-tune on Llama2 model, we have to pre-process the <a href="https://huggingface.co/datasets/sayhan/strix-philosophy-qa?row=0">sayhan/strix-philosophy-qa</a> this dataset into Llama2 required data format. Basically Llama2 required data format as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*6AXyqMmG4A3R7_p4i24r9g.png" /></figure><p>All the models and dataset will be taking from <a href="https://huggingface.co/">Hugging Face</a> platform which is repository for AI models and datasets. Most of the open-source LLMs models were hosted on this platform.</p><p>So to change data format, I will write simple python scripts.<br>To load dataset from hugging face, I will use huggincg face CLI to authorize and download the dataset.</p><blockquote>!pip install -q datasets<br>!huggingface-cli login</blockquote><p>You can use Jupyter Notebook to execute one by one cell code. After running these command, you will need your <em>write token</em> from hugging face. <br>After enter the token, The following simple python script will convert the dataset into desired format:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/907cbb9e9973e549371d97d0b6d18930/href">https://medium.com/media/907cbb9e9973e549371d97d0b6d18930/href</a></iframe><p>Then, To push formatted dataset into the hugging face:</p><blockquote>formatted_dataset.push_to_hub(“mikalshrestha/strix-philosophy-qa-llama2”)</blockquote><p>You can create your own dataset repo from hugging face. Here I created strix-philosophy-qa-llama2 dataset repo with my username: mikalshrestha<br>You can still found this formatted dataset <a href="https://huggingface.co/datasets/mikalshrestha/strix-philosophy-qa-llama2">here</a> where I already pushed. Formatted dataset:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tcrFbyUJqXfhknGReiyEgg.png" /></figure><p>Our dataset is ready for fine tuning <a href="https://emojipedia.org/smiling-face-with-smiling-eyes">😊</a>. Lets start fine tuning process.</p><p><strong>Fine Tuning</strong></p><p>I will be using PyTorch, Transformer, TRL and PEFT library to fine tune the Llama2 model. And I will be using <a href="https://huggingface.co/NousResearch/Llama-2-7b-chat-hf">Llama2–7B-Chat model </a>from hugging face.</p><p>PyTorch is a frameworks to build deep learning models and Transformer are a type of neural network architecture that transforms or changes an input sequence into an output sequence. They do this by learning context and tracking relationships between sequence components.</p><p>And <a href="https://github.com/huggingface/trl">TRL</a> is a full stack library where we provide a set of tools to train transformer language models with Reinforcement Learning, from the Supervised Fine-tuning step (SFT), Reward Modeling step (RM) to the Proximal Policy Optimization (PPO) step</p><p>One thing you need to know more about is PEFT: Parameter-Efficient Fine-Tuning which enable efficient adaptation of pre-trained models to downstream applications without fine-tuning all the model’s parameters. PEFT supports the widely-used Low-Rank Adaptation of Large Language Models (LoRA). Basically it helps for quantization of LLMs means the weight of neural networks are stored in a higher bit for LLMs but we can reduce the bits for storing weights of LLMs in such a way that we can fine tune the model in specific task in lower resources as well.</p><blockquote>I used Google Collab Pro version for fine tuning as following specs:<br>RAM: 52 GB<br>GPU: 15GB<br>Disk: 200 GB</blockquote><p><strong>Step1: Install following required libraries:</strong></p><blockquote>!pip install -q accelerate==0.21.0 peft==0.4.0 bitsandbytes==0.40.2 transformers==4.31.0 trl==0.4.7</blockquote><p><strong>Step2: Import libraries:</strong></p><blockquote>import os<br>import torch<br>from datasets import load_dataset<br>from transformers import (AutoModelForCausalLM, AutoTokenizer,BitsAndBytesConfig,HfArgumentParser, TrainingArguments,pipeline, logging,)<br>from peft import LoraConfig, PeftModel<br>from trl import SFTTrainer</blockquote><p><strong>AutoModelForCausalLM</strong>: This class allows you to load a pre-trained, causal language model from the Hugging Face model hub. These models can generate text sequentially, one word at a time, based on the preceding context.</p><p><strong>AutoTokenizer</strong>: This class automatically loads the tokenizer associated with the chosen model from AutoModelForCausalLM. The tokenizer prepares text data for the model by handling tasks like vocabulary building, tokenization (splitting text into units), and padding.</p><p><strong>BitsAndBytesConfig</strong>: This class, from the bitsandbytes library, is used for configuring quantization techniques in models. Quantization aims to reduce the memory footprint and speed up computations by using lower-precision data types. However, this might come at the cost of slightly decreased accuracy.</p><p><strong>HfArgumentParser</strong>: This class helps with creating command-line arguments for fine-tuning or training language models. It simplifies the process of defining arguments, parsing user input, and handling defaults.</p><p><strong>TrainingArguments</strong>: This class defines training arguments for your model. It includes settings like learning rate, number of training epochs, batch size, and logging options.</p><p><strong>pipeline</strong>: This function from the transformers library allows you to create pre-made pipelines for various NLP tasks. It simplifies the process of using pre-trained models for specific tasks like text summarization, question answering, or text generation.</p><p><strong>logging</strong>: This module provides functionalities for logging information during training or inference. It helps track the progress and performance of your model.</p><p><strong>Step 3: Configure all training parameters:</strong></p><ul><li>configuring bitsandbytes for 4-bit quantization.</li><li>Loading the Llama 2 model in 4-bit precision on a GPU with the corresponding tokenizer.</li><li>Loading configurations for QLoRA</li><li>SFT training parameters</li></ul><p>I have used configurations as follows:<br><a href="https://gist.github.com/mikalshrestha/8139d7e7788870c3d45f07d35585480d">https://gist.github.com/mikalshrestha/8139d7e7788870c3d45f07d35585480d</a></p><p><strong>Step 3: Setup parameters and Start Train</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b2b361e7f268fe809c00b67500a16551/href">https://medium.com/media/b2b361e7f268fe809c00b67500a16551/href</a></iframe><p>SFTTrainer class from rtl package Optimized for fine-tuning pre-trained models with supervised learning tasks.</p><ol><li>model :</li></ol><blockquote># Load base model<br>model = AutoModelForCausalLM.from_pretrained(<br> model_name,<br> quantization_config=bnb_config,<br> device_map=device_map<br>)<br>model.config.use_cache = False<br>model.config.pretraining_tp = 1</blockquote><p>Loads a pre-trained causal language model from the Hugging Face model hub. The specific model is selected using the model_name parameter. model name is:</p><blockquote>model_name = “NousResearch/Llama-2–7b-chat-hf”</blockquote><p>quantization_config parameter that specifies a configuration for applying quantization to the model. bnb_config refers to an instance of the BitsAndBytesConfig class. Quantization can reduce the model’s size and improve inference speed, but may slightly decrease accuracy.</p><p>device_map parameter that specifies the device (e.g., CPU or GPU) the model should be loaded onto.</p><p>2. train_dataset:<br>Load dataset from hugging face.</p><blockquote>dataset_name = “mikalshrestha/strix-philosophy-qa-llama2”<br>dataset = load_dataset(dataset_name, split=”train”)</blockquote><p>3. peft_config:<br>We can initialize LoraConfig class for perft as follows. We can give necessary parameter according to requirements. Do checkout my <a href="https://gist.github.com/mikalshrestha/8139d7e7788870c3d45f07d35585480d">configuration gist</a> for further details.</p><blockquote># Load LoRA configuration<br>peft_config = LoraConfig(<br> lora_alpha=lora_alpha,<br> lora_dropout=lora_dropout,<br> r=lora_r,<br> bias=”none”,<br> task_type=”CAUSAL_LM”,<br>)</blockquote><p>4. packaging:<br>Pack multiple short examples in the same input sequence to increase efficiency. Must be true or false.</p><p>5. tokenizer:<br>Loads the tokenizer associated with the pre-trained LLaMA model specified by <a href="https://huggingface.co/NousResearch/Llama-2-7b-chat-hf">model_name</a>. This tokenizer is responsible for processing text data into a format suitable for the model, including tokenization and creating numerical representations for those tokens.</p><blockquote># Load LLaMA tokenizer<br>tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)<br>tokenizer.pad_token = tokenizer.eos_token<br>tokenizer.padding_side = “right”</blockquote><p>6. args(Training arguments):<br>Set following training arguments.</p><blockquote># Set training parameters<br>training_arguments = TrainingArguments(<br> output_dir=output_dir,<br> num_train_epochs=num_train_epochs,<br> per_device_train_batch_size=per_device_train_batch_size,<br> gradient_accumulation_steps=gradient_accumulation_steps,<br> optim=optim,<br> save_steps=save_steps,<br> logging_steps=logging_steps,<br> learning_rate=learning_rate,<br> weight_decay=weight_decay,<br> fp16=fp16,<br> bf16=bf16,<br> max_grad_norm=max_grad_norm,<br> max_steps=max_steps,<br> warmup_ratio=warmup_ratio,<br> group_by_length=group_by_length,<br> lr_scheduler_type=lr_scheduler_type,<br> report_to=”tensorboard”<br>)</blockquote><p>Then to train the model:</p><blockquote># Train model<br>trainer.train()</blockquote><p>Almost 20 minutes time were required to complete training for 0.01 epochs. It takes based on resources you are using for training.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vUdsgR8yiUuH08ae5PInHA.png" /><figcaption>model training summary</figcaption></figure><blockquote>Save the trained model:<br>trainer.model.save_pretrained(new_model)</blockquote><p>You can also push fine tune model into hugging face as well. You can find my finetune model in hugging face<strong> </strong><a href="https://huggingface.co/mikalshrestha/strix-philosophy-qa-llama2-finetune"><strong>here</strong></a>.</p><p>Fine tuning process is done let’s test the response of original model vs fine tune model. Original model responses will generated from their console and this fine tune model resposnes will generate as follows:</p><blockquote># Run text generation pipeline with our model<br>prompt = “What is quantum machine learning?”<br>pipe = pipeline(task=”text-generation”, model=model, tokenizer=tokenizer, max_length=200)<br>result = pipe(f”&lt;s&gt;[INST] {prompt} [/INST]”)<br>print(result[0][‘generated_text’])</blockquote><p>prompt1(general question): “What is quantum machine learning?”<br><strong>Original model response</strong>: Quantum Machine Learning (QML) is an emerging field that combines quantum computing and machine learning to develop new algorithms and models for solving complex problems in various fields, such as computer vision, natural language processing, and recommender systems. QML leverages the power of quantum computing to perform complex computations exponentially faster than classical computers, enabling breakthroughs in areas like drug discovery, climate modeling, and artificial intelligence.\n\n In summary, Quantum Machine Learning is a rapidly growing field that harnesses the potential of quantum computing to revolutionize machine learning algorithms and models, leading to groundbreaking advancements in various fields.</p><p><strong>fine-tune model response</strong>: Quantum machine learning is a subfield of quantum computing that focuses on developing algorithms and models that can be used to solve machine learning problems. This includes developing quantum algorithms for tasks such as classification, regression, clustering, and dimensionality reduction. Quantum machine learning is a rapidly developing field, with many researchers exploring its potential applications in areas such as drug discovery, natural language processing, and computer vision.</p><p>prompt2(task specific question): “What is the second sense in which the term abduction is used in the philosophical literature?”<br><strong>Original model response</strong>: In philosophy, the term \”abduction\” has two distinct meanings. The first refers to the process of making inferences or drawing conclusions from observations and data. This type of abduction allows researchers to explore alternative perspectives and think outside the box.\n \n In this blog post, we will delve into the second sense of abduction and explore how it can be applied in various fields such as science, technology, engineering, and mathematics (STEM). We will also discuss the benefits of using abduction in research and how it can lead to innovative solutions.\n \n By understanding the concept of abduction and its applications, researchers can develop new ideas and approaches that challenge existing norms and push boundaries. This blog post is a must-read for anyone interested in exploring the power of imagination in research and innovation.<br><strong>fine-tune model response</strong>: The second sense in which the term abduction is used in the philosophical literature refers to the process of making a guess or an inference about a particular situation or phenomenon based on a set of observations or data. This sense of abduction is often contrasted with the first sense, which refers to the process of making a generalization or a conclusion based on a set of observations or data. In this sense, abduction is a process of making a specific inference or prediction based on a set of observations or data, rather than making a generalization or conclusion based on a set of observations or data. This sense of abduction is often used in the context of scientific inquiry, where it is used to describe the process of making a specific prediction or inference based on a set of observations or data.<br>This shows, Fine tune model generate more context aware specific texts of that fine tune dataset than the original model.</p><p>In next story, I will sharing you how to make end to end LLMs application of text generations by making REST APIs with frontend application.</p><p>That’s it. Thanks for reading and don’t forgot to thumbs up <a href="https://www.piliapp.com/emoji/list/thumbs-up/">👍</a> if you like it. Happy Learning<a href="https://emojipedia.org/smiling-face-with-smiling-eyes">😊</a>.</p><ul><li><a href="https://github.com/mikalshrestha/mikalshrestha-strix-philosophy-qa-llama2">GitHub - mikalshrestha/mikalshrestha-strix-philosophy-qa-llama2: Fine tune Llama2 in strix-philosophy-qa dataset</a></li><li><a href="https://huggingface.co/datasets/mikalshrestha/strix-philosophy-qa-llama2?row=1">mikalshrestha/strix-philosophy-qa-llama2 · Datasets at Hugging Face</a></li><li><a href="https://huggingface.co/datasets/sayhan/strix-philosophy-qa?row=0">sayhan/strix-philosophy-qa · Datasets at Hugging Face</a></li><li><a href="https://huggingface.co/NousResearch/Llama-2-7b-chat-hf">NousResearch/Llama-2-7b-chat-hf · Hugging Face</a></li><li><a href="https://huggingface.co/mikalshrestha/strix-philosophy-qa-llama2-finetune">mikalshrestha/strix-philosophy-qa-llama2-finetune · Hugging Face</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e01faa03e81c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Build and Run Neural Network model on Edge Devices?]]></title>
            <link>https://mikalshrestha.medium.com/how-to-build-and-run-neural-network-model-on-edge-devices-43ab77941d2c?source=rss-4aaab36b00a8------2</link>
            <guid isPermaLink="false">https://medium.com/p/43ab77941d2c</guid>
            <category><![CDATA[image-classification]]></category>
            <category><![CDATA[convolutional-network]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Mikal Shrestha]]></dc:creator>
            <pubDate>Wed, 11 Jan 2023 17:25:29 GMT</pubDate>
            <atom:updated>2023-01-11T17:25:29.033Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OaouFNBybdW6uJEI4XPO8g.png" /><figcaption>Overall flow for running NN model on android</figcaption></figure><p>Hey folks, welcome to this story. In this story I will share you how to implement a neural network model and run into the edge mobile devices. For offline or real-time machine learning on edge devices, we can deploy machine learning or deep learning model directly into the edge devices rather send data to server for processing. It will reduce the latency and helps to get the instant results. Here I will explain by taking a one example of image classification.</p><p>I think all of us know about the approach of deploying model by making APIs to interact with the edge devices and server. But can we deploy the model directly into the edge devices so that we can achieve better performance for some applications? The answer is yes. Here TensorFlow Lite comes into the picture.</p><p>For who don’t know, TensorFlow is an open source framework developed by Google to build and run machine learning, deep learning and other statistical and predictive analytics model. And TensorFlow Lite is an open source deep learning framework that is designed to run machine learning models on mobile and embedded devices. It allows developers to build and deploy machine learning models on devices with limited computational resources, such as smartphones and IoT devices.</p><h4>Dataset</h4><p>Fruits 360 dataset is used for this example to train and test the model. It is a dataset with 90380 images of 131 fruits and vegetables which is publicly available in Kaggle. You can checkout for more details about the dataset from Kaggle website.<br><a href="https://www.kaggle.com/datasets/moltean/fruits">https://www.kaggle.com/datasets/moltean/fruits</a></p><h4>Building and Training CNN Model</h4><p>Let’s understand about the Convolutional Neural Network(CNN) first. It is a kind of network architecture for deep learning algorithms and is specifically used for image recognition and tasks that involve the processing of pixel data. Some of the terminologies used in CNN are:<br><strong>Kernel or Filter or Feature Detectors: </strong>Used to extract the features from the images.<br><strong>Stride: </strong>Stride is a parameter of the neural network’s filter that modifies the amount of movement over the image.<br><strong>Padding</strong>: Padding is a term relevant to convolutional neural networks as it refers to the number of pixels added to an image when it is being processed by the kernel of a CNN.<br><strong>Pooling</strong>: Pooling in convolutional neural networks is a technique for generalizing features extracted by convolutional filters and helping the network recognize features independent of their location in the image.<br><strong>Flatten</strong>: Flattening is used to convert all the resultant 2-Dimensional arrays from pooled feature maps into a single long continuous linear vector. The flattened matrix is fed as input to the fully connected layer to classify the image.<br>The typical CNN model architecture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*ERM2KbxLtbBg-1dpkJj5Bw.jpeg" /></figure><p>There are other types of neural networks in deep learning, but for identifying and recognizing objects, CNNs are the network architecture of choice. Ohh that’s alot about CNN::</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*n7hoUEv4Fk8jscSJVRnV5A.jpeg" /></figure><p>Let’s jump into the implementation part. Here I used TensorFlow and Keras library. And For IDE you can use Google Collab or Jupyter notebook for coding. Let’s create a new workspace notebook in Google Collab and change runtime environment to GPU or TPU.</p><p>First step is to download the dataset from the kaggle. Here I am using keras utils class to download the dataset from the link and and extract the zip and store it. After extracting the dataset there will be two directory one is Training and another is Test. Images under Training directory is used for model training purpose and Images under Test directory is used for model testing purpose.</p><pre>#download dataset from the kaggle link <br>data = tf.keras.utils.get_file(origin=&quot;https://storage.googleapis.com/kaggle-data-sets/5857/414958/bundle/archive.zip?X-Goog-Algorithm=GOOG4-RSA-SHA256&amp;X-Goog-Credential=gcp-kaggle-com%40kaggle-161607.iam.gserviceaccount.com%2F20230110%2Fauto%2Fstorage%2Fgoog4_request&amp;X-Goog-Date=20230110T001704Z&amp;X-Goog-Expires=259200&amp;X-Goog-SignedHeaders=host&amp;X-Goog-Signature=773ba1adaf07ebbf2be894c4997884c7f05562b27afe4ba8b1f1336c35ebcc5b0a2beddca8712ac029124daa606c1590c305bcd0b4ef1abfa5b836e77a5d7f62a33dac1478b6eae61e5371e9d6d46e8f643418813d76b54333ee6a1300328d3fbc57a7f3edf974ffb89d35264d04103e89bc971d935334f5a1c1e0ea8d34ac244e7e64fe775bc9a03713e8d0d7583d9b582269751263e014d26094082159a3409a50eadf13f26a4f6d0f578579b2ce41f98d4d3f9e85d72d8c1c5c551c96cab5809bc4e650eb85cdd7295116f03b57d854eaa6294d52ee20a1d50c8ef8ffa318e248f94626e94bf29a571f3d1609fef550df0021992f37ac3fe5cbf78b3d7bd8&quot;,<br>                                   fname=&quot;fruits-360.zip&quot;, extract=True)<br>base_dir, _ = os.path.splitext(data)<br><br>train_dir = os.path.join(base_dir, &#39;Training&#39;)<br>test_dir = os.path.join(base_dir, &#39;Test&#39;)</pre><p>Now split the dataset into train set and test set. Keras ImageDataGenerator is used to take the inputs of the original data and then transform it on a random basis, returning the output resultant containing solely the newly changed data. <em>flow_from_directory</em>() method of ImageDataGenerator class takes an input of image directory, batch size and target size. Batch size is a number of samples processed before the model is updated and target size is a size of the input image. The <em>flow_from_directory</em>() method allows you to read the images directly from the directory and augment them while the neural network model is learning on the training data.</p><pre>train_datagen = tf.keras.preprocessing.image.ImageDataGenerator()<br><br>train_generator = train_datagen.flow_from_directory(directory=train_dir, target_size=(image_size, image_size), batch_size=batch_size)<br><br>test_datagen = tf.keras.preprocessing.image.ImageDataGenerator()<br><br>test_generator = test_datagen.flow_from_directory(directory=test_dir, target_size=(image_size, image_size), batch_size=batch_size)</pre><p>After splitting into train and test generator, we will apply transfer learning approach before training the custom dataset. Transfer learning is a research problem in machine learning that focuses on storing knowledge gained while solving one problem and applying it to a different but related problem. Basically it is the reuse of a pre-trained model on a new problem. Here I am using MobileNet model for transfer learning. <br>MobileNet is a deep learning model designed to run efficiently on mobile devices. It was developed by Google and introduced in a 2017 research paper. The model is based on the idea of using depthwise separable convolutions, which factorize a standard convolution into a depthwise convolution (which acts on each input channel separately) followed by a pointwise convolution (which mixes the output of the depthwise convolution). This approach allows for a significant reduction in the number of parameters and computational complexity of the model, making it well-suited for deployment on mobile devices with limited resources. MobileNet also uses other techniques such as using smaller filter sizes and using fewer layers to further reduce the computational requirements of the model. <br>The trainable property of the model is set to False. This means the weights of the model will not change but just be used. We’re going to use the version of MobileNet that’s trained on images of sizes 128*128 because image size of input dataset is 100*100 which is nearest to the 128*128.</p><pre>#Transfer Learning: used pre-trained MobileNet Model<br>pre_trained_model = tf.keras.applications.MobileNet(input_shape=IMG_SHAPE, include_top=False)<br>pre_trained_model.trainable = False</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/570/1*k07Vymik80Jp9MnmzbUqeQ.jpeg" /></figure><p>Yes that’s not enough to classify custom image dataset we have to build our own custom model which is pre-trained on MobileNet with the help of transfer learning. The Sequential class is used to add layers to the model architecture that are compatible with our dataset. A new model can be made using a list of layers that is accepted. The base model is the first item on the list. This indicates that the new model includes all levels in MobileNet, with the exception of its top layers. In addition to these layers, average pooling and dense layers are two new layers that are added. Basically Dense Layer is simple layer of neurons in which each neuron receives input from all the neurons of previous layer.<strong> </strong>Due to the 102 classes in our dataset, the dense layer has 102 neurons. The compile() method is used to compile the new model that the Sequential class returned after being saved in the model variable. The optimizer, loss function, and metrics are all accepted by this approach. 50 epochs is used for training the model.</p><pre>#Create Own Custom Model<br>model = tf.keras.Sequential([<br>  pre_trained_model,<br>  tf.keras.layers.GlobalAveragePooling2D(),<br>  tf.keras.layers.Dense(102, activation=&#39;softmax&#39;)<br>])<br>model.summary()<br>model.compile(optimizer=tf.keras.optimizers.Adam(),<br>              loss=&#39;categorical_crossentropy&#39;,<br>              metrics=[&#39;accuracy&#39;])<br>epochs = 50<br>steps_per_epoch = numpy.ceil(train_generator.n / batch_size)<br>test_steps = numpy.ceil(test_generator.n / batch_size)<br><br>model.fit_generator(generator=train_generator,<br>                              steps_per_epoch = steps_per_epoch,<br>                              epochs=epochs,<br>                              validation_data=test_generator,<br>                              validation_steps=test_steps)</pre><p>Softmax activation function is used in each neuron which determines the neuron should activated or not. It transforms the raw outputs of the neural network into a vector of probabilities, essentially a probability distribution over the input classes. And Adam optimizer is used for minimize the loss.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*QLZqsgXA2b8GyNZ1VHJQ3Q.png" /></figure><p>You can also checkout full snippet of code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e427db413adef5828ba1abe12affce2/href">https://medium.com/media/4e427db413adef5828ba1abe12affce2/href</a></iframe><p>Summary of model training epoch by epoch:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZFNsQs3FeGcEOCML7SJpPg.png" /></figure><h4>Converting Trained Model to TensorFlow Lite Format</h4><p>After compiling the model, we need to save the trained model then convert to tensorflow lite format using TFLiteConverter. After conversion is completed, model.tflite file will generate. Then generate the labels of respective train class fruits label. Which is saved as a label.txt.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7aaadd743aa4332c1c41050e2c5ad97b/href">https://medium.com/media/7aaadd743aa4332c1c41050e2c5ad97b/href</a></iframe><p>That’s it on the Google Collab, we got trained tflite model and labels of images. Now let’s build the android app and make use of that model.</p><h4>Building an Android Application</h4><p>For developing android app, kotlin programming language is used and Android Studio is used as a IDE. First create a new project from android studio by filling up project name and, application id and other required fields. Then do the following steps.</p><ol><li>In app/src/main location, create a new directory named “assets”</li><li>Add model.tflite and labels.txt file into assets folder</li><li>In the app-level build.gradle file, add the following dependencies for leverage the tensorflow lite in android.</li></ol><pre>implementation &#39;org.tensorflow:tensorflow-lite:2.x.x&#39;<br>implementation &#39;org.tensorflow:tensorflow-lite-gpu:2.x.</pre><p>4. Create a MainActivity.kt class and in onCreate() initialize the TensorFlow lite interpreter. And load the model and labels from assets folder.</p><pre>        val model = loadModelFile(assetManager, &quot;model.tflite&quot;)<br>        val labels = loadLines(context, &quot;labels.txt&quot;)<br>        val options = Interpreter.Options()<br>        gpuDelegate = GpuDelegate()<br>        options.addDelegate(gpuDelegate)<br>        val interpreter = Interpreter(model, options)</pre><p>5. After camera captured the image, convert bitmap image into ByteBuffer. run() function of interpreter class takes an input: ByteBuffer Object and output: list of labels object. Runs model inference if the model takes only one input, and provides only one output. run() function returns the string which is label name of image detected by the model which is then populate in the View.</p><pre>val byteBuffer = convertBitmapToByteBuffer(resizedImage)<br>val output = Array(1) { FloatArray(labels.size) }<br>val startTime = SystemClock.uptimeMillis()<br>interpreter?.run(byteBuffer, output)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/693/1*BuD2jHYLixg5qNsOatPp_Q.png" /><figcaption>Android processing flow</figcaption></figure><h4>Output</h4><p>Tested on real android device which classify image with pretty good accuracy. But this model can be optimized alot more. You can try it on your own custom dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*etDaxMIdmB2vSFNhEcuqLA.png" /></figure><p>That’s it folks. Thanks for reading this story 📗. If you find this helpful, hit the clap button 😄 and If you are stuck on any point feel free to ask below. <strong>Keep learning!!</strong></p><ul><li><a href="https://github.com/mikalshrestha/ImageClassificationAndroid">GitHub - mikalshrestha/ImageClassificationAndroid: Implementation of image classification using custom CNN model in Android.</a></li><li><a href="https://github.com/tensorflow/examples/tree/master/lite/examples">examples/lite/examples at master · tensorflow/examples</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=43ab77941d2c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sending Push Notification To Android From React App Using Spring Boot REST API And FCM]]></title>
            <link>https://mikalshrestha.medium.com/sending-push-notification-to-android-from-react-app-using-spring-boot-rest-api-and-fcm-a4bde40d62f1?source=rss-4aaab36b00a8------2</link>
            <guid isPermaLink="false">https://medium.com/p/a4bde40d62f1</guid>
            <category><![CDATA[fcm]]></category>
            <category><![CDATA[push-notification]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Mikal Shrestha]]></dc:creator>
            <pubDate>Fri, 30 Jul 2021 04:12:02 GMT</pubDate>
            <atom:updated>2021-07-30T04:12:02.594Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xVn39u3IBqeO3a9XFLVkrg.png" /><figcaption>fig-1: Push Notification Flow</figcaption></figure><p>In this story, I will explain how to send a push notification to android client from react admin dashboard using FCM service and Spring Boot REST API. Firebase Cloud Messaging(FCM) is one of the popular cloud service for push notification used by many applications. However building a full fledged push notification feature might be little tricky and complex so in this story I will explain the complete process step by step in easiest way.</p><h3>Table of contents</h3><ol><li>Intro And Flow Explanation</li><li>Creating And Configuring Firebase Project</li><li>Building an Android Application</li><li>Building a Spring Boot Application</li><li>Building a React Application</li><li>How You Can Improve?</li><li>Conclusion</li><li>References</li></ol><h3>Intro And Flow Explanation:</h3><p>Push notification is a message that pops on the top of the screen of mobile devices. Behind the scene multiple services are running for displaying push notification in mobile devices.</p><p>Here I am using Firebase Cloud Messaging(FCM) service for push notification so first we need to create a firebase project and then we need to configure Android and Spring Boot Application with FCM for communicating between them. After registering the android application to the firebase and configure on android app, firebase provides a unique token for each android devices. React app(admin dashboard) hits an API call to Spring Boot backend with title, message then Spring Boot communicates with FCM service and sends the push notification to android based on the token.</p><h3>Creating And Configuring Firebase Project:</h3><ul><li>Go on <a href="https://console.firebase.google.com/u/1/">https://console.firebase.google.com</a> and create a new project(Add Project) by filling up project name with other simple 3/4 steps.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ivewkb-XihfXWZJVlpGF4Q.png" /></figure><p>I have created FirebasePushNotificationDemo firebase project. Then go on dashboard of that project.</p><ul><li>Go on Project Overview → Project Settings</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HlXv0ARCXolQTnSi1IrPhw.png" /></figure><ul><li>Add your android app. Before doing this you need to create an android app project from android studio. Then we can get package name of our android app from there.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iYzNL8xMqmTqJkPBD7MPKg.png" /></figure><ul><li>Select android and you need to registering android package there.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ScZpAICvQKIXXCooVLTI7A.png" /></figure><ul><li>After registering package name of android app we will get google-services.json. Then we need to put that json file in our android app under app folder.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*TUt5nM0Y58559RoxVswdOw.png" /></figure><h3>Building an Android Application:</h3><ul><li>First create an empty new android project. And add google-services.json file under app folder as described in above point.</li><li>Under project level build.gradle add following:</li></ul><pre>classpath &#39;com.google.gms:google-services:4.3.8&#39;</pre><ul><li>Under app level build.gradle add following dependencies and sync it.</li></ul><pre>implementation platform(&#39;com.google.firebase:firebase-bom:28.3.0&#39;)<br>implementation &#39;com.google.firebase:firebase-messaging&#39;<br>implementation &#39;com.google.firebase:firebase-analytics&#39;</pre><ul><li>Create a MyFirebaseMessagingService class which extends FirebaseMessagingService class. Basically this class helps for getting notification that is sent from the server. We can get title, description, image link etc. on onMessageReceived method. Under this method we need to set that remoteMessage parameter into the NotificationCompat and build it. For android version Build.VERSION_CODES.<em>O and higher, we should use </em>NotificationChannel class for channel creation and setting all the parameters. Then with the help of NotificationManager we can display notification on android.[1]</li></ul><p>FirebaseMessagingService.java</p><pre>public class MyFirebaseMessagingService extends FirebaseMessagingService {<br><br>    @Override<br>    public void onMessageReceived(@NonNull RemoteMessage remoteMessage) {<br>        super.onMessageReceived(remoteMessage);<br>        getFCMNotification(remoteMessage.getNotification().getTitle(), remoteMessage.getNotification().getBody());<br>    }<br><br>    public void getFCMNotification(String title, String message) {<br>        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, &quot;myFirebaseChannel&quot;)<br>                .setSmallIcon(R.drawable.<em>ic_baseline_notifications_active_24</em>)<br>                .setContentTitle(title)<br>                .setContentText(message)<br>                .setAutoCancel(true);<br><br>        NotificationManager mNotificationManager = (NotificationManager)<br>                this.getSystemService(Context.<em>NOTIFICATION_SERVICE</em>);<br><br>        if (Build.VERSION.<em>SDK_INT </em>&gt;= Build.VERSION_CODES.<em>O</em>) {<br>            CharSequence name = title;<br>            String description = message;<br>            int importance = NotificationManager.<em>IMPORTANCE_DEFAULT</em>;<br>            NotificationChannel channel = new NotificationChannel(&quot;myFirebaseChannel&quot;, name, importance);<br>            channel.setDescription(description);<br>            try {<br>                mNotificationManager.createNotificationChannel(channel);<br>            } catch (NullPointerException e) {<br>            }<br>        }<br><br>        Notification notification = builder.build();<br>        notification.flags |= Notification.<em>FLAG_AUTO_CANCEL</em>;<br><br>        mNotificationManager.notify(999, notification);<br><br>    }<br>}</pre><ul><li>Register MyFirebaseMessagingService in AndroidMenifest.xml file as a message event service.</li></ul><pre>&lt;service<br>    android:name=&quot;.MyFirebaseMessagingService&quot;&gt;<br>    &lt;intent-filter&gt;<br>        &lt;action android:name=&quot;com.google.firebase.MESSAGING_EVENT&quot; /&gt;<br>    &lt;/intent-filter&gt;<br>&lt;/service&gt;</pre><ul><li>Then under onCreate method of MainActivity class, we need to subscribe the FCM on the basis of subscribeToTopic method using FirebaseMessaging class. And for getting registration token provide by FCM service, we need to call getToken() method of FirebaseMessaging class. This token is very important because on the basis of this token server sends the notification to that android device. For this purpose, here I am sending this token from react app form with title and message. This is not best way to do in real application. I will explain this process in section-6 “How You Can Improve?”.</li></ul><p>Subscribe→</p><pre>//For FCM Subscription<br>        FirebaseMessaging.<em>getInstance</em>().subscribeToTopic(&quot;weather&quot;)<br>               .addOnCompleteListener(new OnCompleteListener&lt;Void(){<br>                   @Override<br>                   public void onComplete(@NonNull Task&lt;Void&gt; task){<br>                        String msg = &quot;Succcess&quot;;<br>                        if (!task.isSuccessful()) {<br>                            msg = &quot;Failed&quot;;<br>                        }<br>                     Toast.<em>makeText</em>(MainActivity.this, msg,  Toast.<em>LENGTH_SHORT</em>).show();<br>                    }<br>                   });</pre><p>Get Registration Token →</p><pre>//For Registration Token<br>        FirebaseMessaging.<em>getInstance</em>().getToken()<br>                .addOnCompleteListener(new     OnCompleteListener&lt;String&gt;() {<br>                    @Override<br>                    public void onComplete(@NonNull Task&lt;String&gt; task) {<br>                        if (!task.isSuccessful()) {<br>                            Log.<em>w</em>(&quot;TAG&quot;, &quot;Fetching FCM registration token failed&quot;, task.getException());<br>                            return;<br>                        }<br><br>                        // Get new FCM registration token<br>                        String token = task.getResult();<br><br>                        Log.<em>d</em>(&quot;TAG&quot;, token);<br>                        Toast.<em>makeText</em>(MainActivity.this, token, Toast.<em>LENGTH_SHORT</em>).show();<br>                        System.<em>out</em>.println(token);<br>                    }<br>                });</pre><ul><li>Run the application. Then you can get registration token on logcat.</li></ul><h3>Building a Spring Boot Application:</h3><ul><li>Create a maven project from IntelliJ IDEA or from <a href="https://start.spring.io/">Spring Initializer</a> .</li><li>Add following dependencies in pom.xml.</li></ul><pre>&lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;<br>&lt;/dependency&gt;<br><br>&lt;dependency&gt;<br>   &lt;groupId&gt;com.google.firebase&lt;/groupId&gt;<br>   &lt;artifactId&gt;firebase-admin&lt;/artifactId&gt;<br>   &lt;version&gt;6.11.0&lt;/version&gt;<br>&lt;/dependency&gt;</pre><ul><li>Go on firebase console then, Project Overview → Project settings → Service accounts → Firebase Admin SDK.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fvZyZAzU_tN5oR5tkBdNCg.png" /></figure><ul><li>Select java and generate new private key. Then you can get json file like this:</li></ul><p>fir-pushnotificationdemo-ed2b3-firebase-adminsdk-hqmki-2035384892.json</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kl8pglYM-l8J-YS9D1B21g.png" /></figure><ul><li>After that, add this json file under src/main/resources folder.</li><li>Define port number and reference variable for json file under application.properties.</li></ul><pre>server.port=8081<br><br>app.firebase-configuration-file=fir-pushnotificationdemo-ed2b3-firebase-adminsdk-hqmki-2035384892.json</pre><ul><li>Create two model class: PushNotificationRequest and PushNotificationResponse under model folder. This basically represents a POJO class carrying data with getter and setter methods implemented.</li><li>Create a FCMInitializer class under service folder and add @Service annotation on it. Here firebaseConfigPath variable gets a value from app.firebase-configuration-file environment variable that we defined on application.properties. Then we need to first initialize the firebase app in spring boot application. For that, we have to call <em>initializeApp() method with FirebaseOptions for initialization. This actually takes all the configuration variable from the json file and build it using </em>FirebaseOptions.Builder(). After built, we need to pass that variable to <em>initializeApp() method.[2]</em></li></ul><pre>FirebaseOptions options = new FirebaseOptions.Builder()<br>                    .setCredentials(GoogleCredentials.<em>fromStream</em>(new ClassPathResource(firebaseConfigPath).getInputStream())).build();<br>            if (FirebaseApp.<em>getApps</em>().isEmpty()) {<br>                FirebaseApp.<em>initializeApp</em>(options);</pre><ul><li>Create a NotificationService class and add @Service annotation on it. In this class, we have to implement all the logic and configuration related stuff here.</li><li>AndroidConfig and ApnsConfig is used for configuration of android and iOS push notification service. We need to build this configuration with title and message using Message.builder(). Then it communicates with FCM service and send the notification to android/iOS based on the token. But here we use android only.</li></ul><p>Android Configuration →(For Android)</p><pre>private AndroidConfig getAndroidConfig(String topic) { <br>return AndroidConfig.builder() .setTtl(Duration.ofMinutes(2).toMillis()).setCollapseKey(topic) .setPriority(AndroidConfig.Priority.HIGH) .setNotification(AndroidNotification.builder() .setTag(topic).build()).build(); }</pre><p>Apple push notification service Configuration→(For iOS )</p><pre>private ApnsConfig getApnsConfig(String topic) { <br>return ApnsConfig.builder() .setAps(Aps.builder().setCategory(topic).setThreadId(topic).build()).build(); }</pre><p>Message Builder →</p><pre>private Message.Builder   getPreconfiguredMessageBuilder(PushNotificationRequest request) <br>{        <br>AndroidConfig androidConfig = getAndroidConfig(request.getTopic());        ApnsConfig apnsConfig = getApnsConfig(request.getTopic());        return Message.builder()                .setApnsConfig(apnsConfig).setAndroidConfig(androidConfig).setNotification(                        <br>     new Notification(request.getTitle(), request.getMessage()));  <br> }</pre><ul><li>Create a FCMPushNotificationController class and add @RestController<br>@CrossOrigin these annotation on it. @RestController for creating REST API endpoint and @CrossOrigin for cross origin resource sharing because we need to call this api from react app. Then create a sendTokenNotification() method that takes a request model object and add @PostMapping(“/send/notification”) on it. This represents the POST method with url path: “/send/notification” . This sendTokenNotification() method basically creates a post endpoint.</li></ul><p>FCMPushNotificationController.java</p><pre>@RestController<br>@CrossOrigin<br>public class FCMPushNotificationController {<br><br>    private NotificationService notificationService;<br><br>    public FCMPushNotificationController(NotificationService notificationService) {<br>        this.notificationService = notificationService;<br>    }<br><br>    @PostMapping(&quot;/send/notification&quot;)<br>    public ResponseEntity sendTokenNotification(@RequestBody PushNotificationRequest request) {<br>        notificationService.sendPushNotificationToToken(request);<br>        return new ResponseEntity&lt;&gt;(new PushNotificationResponse(HttpStatus.<em>OK</em>.value(), &quot;Notification has been sent.&quot;), HttpStatus.<em>OK</em>);<br>    }<br>}</pre><ul><li>Run the application and you can check it from the postman also. But we will make a react app that actually hits this api with some form data.</li></ul><h3>Building a React Application:</h3><ul><li>Install Node.js first then hit following command in terminal by navigating the destination folder you want place on your app.[3]<br>“npx create-react-app my-app”</li><li>This command creates the package.json file and all other required files and folder by default.</li><li>Then hit the following command for installing axios. Axios is a HTTP networking client for the browser and node.js.<br>“npm install axios”</li><li>Under components folder, create a SendNotificationForm.js class. In this class, we will make a form for title, message, topic and token and send notification submit button using jsx syntax. When we clicks on send notification button we have to call <a href="http://localhost:8081/send/notification">http://localhost:8081/send/notification</a> this api for sending form data to server with the help of axios. For this purpose, I will do all these stuff like api call, making forms in this SendNotificationForm.js class only.</li></ul><p>API Call →</p><pre>submitHandler = (e) =&gt; {<br>  e.preventDefault()<br>  console.log(this.state)<br>  axios.post(‘http://localhost:8081/send/notification&#39;, this.state,      this.config).then(reponse =&gt; {<br>   console.log(reponse)<br>}).catch(error =&gt; {<br>  console.log(error)<br>})</pre><p>Form →</p><pre>render() {<br>const {title, message, topic, token} = this.state<br>return (<br>&lt;div&gt;<br>  &lt;form onSubmit={this.submitHandler}&gt;</pre><pre>&lt;div style={{float : ‘center’, marginTop : ‘50px’}}&gt;<br>  &lt;label&gt;&lt;b&gt;Notification Admin Dashboard&lt;/b&gt;&lt;/label&gt;<br>&lt;/div&gt;</pre><pre>&lt;div style={{float : ‘center’, marginTop : ‘50px’}}&gt;<br>  &lt;label&gt;Enter Title:&lt;/label&gt;<br>&lt;/div&gt;</pre><pre>&lt;div style={{float : ‘center’, marginTop : ‘15px’}}&gt;<br>&lt;input<br>  type=”text”<br>  name=”title”<br>  value={title}<br>  onChange={this.changeHandler}<br>/&gt;<br>&lt;/div&gt;</pre><pre>&lt;div style={{float : ‘center’, marginTop : ‘30px’}}&gt;<br>   &lt;label&gt;Enter Message:&lt;/label&gt;<br>&lt;/div&gt;</pre><pre>&lt;div style={{float : ‘center’, marginTop : ‘15px’}}&gt;<br>&lt;input<br>  type=”text”<br>  name=”message”<br>  value={message}<br>  onChange={this.changeHandler}<br>/&gt;<br>&lt;/div&gt;</pre><pre>&lt;div style={{float : ‘center’, marginTop : ‘30px’}}&gt;<br>   &lt;label&gt;Enter Topic:&lt;/label&gt;<br>&lt;/div&gt;</pre><pre>&lt;div style={{float : ‘center’, marginTop : ‘15px’}}&gt;<br>&lt;input<br>  type=”text”<br>  name=”topic”<br>  value={topic}<br>  onChange={this.changeHandler}<br>/&gt;<br>&lt;/div&gt;</pre><pre>&lt;div style={{float : ‘center’, marginTop : ‘30px’}}&gt;<br>   &lt;label&gt;Enter Token:&lt;/label&gt;<br>&lt;/div&gt;</pre><pre>&lt;div style={{float : ‘center’, marginTop : ‘15px’}}&gt;<br>&lt;input<br>  type=”text”<br>  name=”token”<br>  value={token}<br>  onChange={this.changeHandler}<br>/&gt;<br>&lt;/div&gt;</pre><pre>&lt;button<br>  type=”submit”<br>  style={{float : ‘center’, marginTop : ‘30px’}}&gt;<br>  Send Notification<br>&lt;/button&gt;<br>&lt;/form&gt;<br>&lt;/div&gt;<br>)<br>}</pre><ul><li>Then render this SendNotificationForm.js in App.js. It’s an entry point for react app.</li></ul><pre>render() {<br>return (<br>&lt;div className=”App”&gt;<br>  &lt;SendNotificationForm/&gt;<br>&lt;/div&gt;<br>)<br>}</pre><ul><li>That’s it. Then hit command “npm start” for start the application. By default, development server runs on port:3000.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6lzAErmyHOenI9AMrhJCWQ.png" /></figure><ul><li>For testing, run all three application and clicks on Send Notification button with title, message, topic and token, then Spring Boot communicates with the FCM service and send the notification to the android device.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*sM1WxEjZ9av1yrkd7AJmFg.png" /><figcaption>fig: push notification in android screenshot</figcaption></figure><h3>How You Can Improve?</h3><p>Here we are sending token from the react form that will not applicable for the real application. Instead of this, you can make one api that takes a registration token from android and store it on database. You can call this api when the android app launched. After this api hits, it will store all the registration token in database of our server. Then you don’t need to send token from the react app form. But you need to change the previous api “/send/notification”. When react app calls an api you need to configure the android/iOS push notification service based on the stored tokens in database. This will sends the push notification for all registered devices.</p><p>→ Introduce new api for storing registration tokens from android app.<br> → Modified existing api i.e. “/send/notification” . This will only takes a title, message, image link etc. as a request parameter and fetch all the registered tokens from database and send to the FCM service. Based on the registration token, notification will be display in android devices.</p><h3>Conclusion:</h3><p>In this article, we built full fledged, end to end push notification service demo application using React, Spring Boot and Android tech stacks. Basically this article helps you to implement the push notification feature from frontend, android to backend and helps to know about how actually push notification is display in android device that are sent from the server. If you are stuck or confused on any point feel free to ask below. You can checkout the following GitHub code also.</p><ul><li><a href="https://github.com/mikalshrestha/FCMPushNotificationDemo-Admin">GitHub - mikalshrestha/FCMPushNotificationDemo-Admin: Admin Panel for FCM Push notification using React.js.</a></li><li><a href="https://github.com/mikalshrestha/FCMPushNotificationDemo-Backend">GitHub - mikalshrestha/FCMPushNotificationDemo-Backend: Implemented REST Endpoint for FCM Push notification using Spring Boot.</a></li><li><a href="https://github.com/mikalshrestha/FCMPushNotificationDemo-Android">GitHub - mikalshrestha/FCMPushNotificationDemo-Android: Implementation of firebase push notification in android.</a></li></ul><h3>References:</h3><p>[1] FCM Android Documentation. “Set up a FCM client app on Android”<br><a href="https://firebase.google.com/docs/cloud-messaging/android/client">https://firebase.google.com/docs/cloud-messaging/android/client</a></p><p>[2] Firebase Admin SDK in Java. “Build app server send requests”<br><a href="https://firebase.google.com/docs/cloud-messaging/send-message#java">https://firebase.google.com/docs/cloud-messaging/send-message#java</a></p><p>[3] React Documentation. “Create React App”<br><a href="https://reactjs.org/docs/create-a-new-react-app.html">https://reactjs.org/docs/create-a-new-react-app.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a4bde40d62f1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building, Containerize and Deploying Node.Js APIs into AWS Part-II]]></title>
            <link>https://mikalshrestha.medium.com/building-containerize-and-deploying-node-js-apis-into-aws-part-ii-2dd8879f87?source=rss-4aaab36b00a8------2</link>
            <guid isPermaLink="false">https://medium.com/p/2dd8879f87</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[docker-compose]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[aws-ec2]]></category>
            <dc:creator><![CDATA[Mikal Shrestha]]></dc:creator>
            <pubDate>Fri, 09 Jul 2021 11:10:10 GMT</pubDate>
            <atom:updated>2021-07-09T11:10:10.093Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>#2. Containerize Node App Into Docker and Deploy Into AWS:</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qZNzmn88IO_-3nKKlwaEVA.png" /></figure><h3>Table of contents</h3><ol><li>Introduction</li><li>Containerizing Into Docker</li><li>Deploying into AWS<br>I. Creating EC2 Instance<br>II. Connecting With SSH Client<br>III. Build and Run Container<br>IV. API Testing on Postman<br>V. Accessing Mongo Container</li><li>Conclusion</li><li>References</li></ol><h4>Introduction:</h4><p>In this story, I will share step by step guide to containerizing the node app(that I already built on part-I) into Docker and deploying and hosting into AWS EC2 Instance.<br><strong>Containerization</strong> is a form of operating system virtualization, through which it runs applications in separate user spaces called containers, all using the same shared operating system (OS).<br><strong>Docker </strong>is an open source platform for containerizing or packaging the application which enables to separate your application from the infrastructure so that we can deliver the application quickly without any hassle. It helps for packaging all the dependencies that you used in app into one container. It basically provides the ability to package and run an application in loosely isolated environment called container. Loosely isolated environment means, multiple deployment application run independently in a single server without any conflict between the applications. After you containerize into Docker you can deploy into any production environment you want. Here I am going to deploy into AWS.[1]<br><strong>AWS</strong>(Amazon web services) is a cloud platform provides variety of cloud computing services like Amazon EC2(Elastic compute cloud), S3, Lamda, DynamoDB, Elastic Beanstalk, RDS, VPC etc. AWS is a large cloud service provider on the globe now and occupy half of the market share of overall cloud providers. I am using EC2 service which provides the virtual server for hosting applications.[3]</p><h4>Containerizing Into Docker:</h4><p><em>First a fall you need to install docker on your machine, yo can go official website of docker </em><a href="http://docker.com/"><em>here</em></a><em> and install according to your operating system. Then you need to sign up into docker hub </em><a href="https://hub.docker.com/"><em>here</em></a><em> . And login into docker-desktop that you installed before by using docker hub credential.<br>If you are not followed part-I then please go there and continue here or you can just clone the GitHub repo </em><a href="https://github.com/mikalshrestha/crudnodejsapp"><em>here</em></a><em> and continue.<br>Create a Dockerfile under a root project folder. You should use same name as “Dockerfile” otherwise it won’t work. We write some commands in this file step by step to dockerize the application.<br>Command-1: “</em>FROM node:14” -&gt; This commamnds basically fetch the official docker node image from docker hub[2]. 14 means node version that I used.<br><em>Command-2: “</em>WORKDIR /usr/src/app” -&gt; Creates a working directory where our application placed in a container.<br><em>Command-3: “</em>COPY package*.json ./” -&gt; Copy the package.json and package-lock.json in a container. Means it move the package.json file into the docker container where we put all the dependencies required.<br><em>Command-4: “</em>RUN npm install” -&gt; It installed all the dependencies in a container.<br><em>Command-5: “</em>COPY . .” -&gt; Copied everything in container whatever it required.<br><em>Command-6: “</em>EXPOSE 5000” -&gt; This commands exposes the port number that you defined on an application and runs on that. Here 5000 is port number I used to run the application. You can checkout server.js file that I defined port number as a 5000.<br><em>Command-7: “</em>CMD [“npm”, “start”]” -&gt; This commands run the application according to the start scripts that you defined on a server.js file.<br>Dockerfile:</p><pre>FROM node:14 </pre><pre>WORKDIR /usr/src/app </pre><pre>COPY package*.json ./ </pre><pre>RUN npm install </pre><pre>COPY . . </pre><pre>EXPOSE 5000 </pre><pre>CMD [“npm”, “start”]</pre><p>Now, we need to create a docker image of our app and also pull the official mongodb docker image from the docker hub and we should link our application to the mongodb. For this, here comes the concept of docker-compose. <br>In part-I, I used mongodb cloud version but here I am using mongodb desktop on a container instead of mongodb cloud. We don’t need to install mongodb on our machine we just pull the mongodb image in a container and link our application image to the mongodb image. Reason behind the using mongodb desktop instead of cloud version is : It’s a best practices to use and we don’t need to install mongodb on our machine. Now, we need to change the mongoURI that we defined by cloud version to new one. That’s it.<br>Docker-compose helps for defining and running the multi-container docker applications. <a href="https://docs.docker.com/compose/">here</a> you can read more. Now,</p><p>Create a docker-compose.yml file under a root project folder. We write some of the commands over here for creating docker image of our node app and also need to define a mongodb image that we need to link in our app.</p><p><em>docker-compose.yml</em></p><pre>version: ‘3’</pre><pre>services: <br>     app: <br>        container_name: crud-node-app <br>        restart: always <br>        build: . <br>        ports: <br>           — ‘88:5000’ <br>        external_links: <br>           — mongo <br>     mongo: <br>        container_name: mongo <br>        image: mongo <br>        ports:<br>            — ‘27017:27017’</pre><p>First we need to define a version which represents a supporting version of docker compose. Now we need to defined services, app and mongo are two services here. app creates the docker image of our app by specifying container_name, defining exposed port number and linking with the mongo image. In mongo service we need to defined the container_name, image and port number that it runs.<br>We need to change mongoURI from default.json file because here we use mongodb in docker container instead of cloud version.<br>“mongoURI”: “mongodb://mongo:27017/crud-node-app”,</p><p>New deafult.json file:</p><pre>{ “mongoURI”: “mongodb://mongo:27017/crud-node-app”, <br>  “jwtSecret”: “secret”<br>}</pre><p>Alright that’s it for containerization. If you want to check on your localhost then just hit command “docker-compose up” by navigating on your root folder. Basically this commands creates the “crud-node-app” image on your docker hub and install all the dependencies required for the application and also linked with the mongodb. It takes some time to download mongo image from docker hub and packaging all the dependencies of our app. After success there you can see printing message on terminal that we written on a server.js file. If anything went wrong then please follow the steps again. Then we can hit the rest api call from postman by following part-I. Eg. hit: <a href="http://localhost:5000/api/users">http://localhost:5000/api/users</a> <br>All the data that you post are stored on a mondb database of docker container.</p><h4>Deploying into AWS:</h4><p>First you need to sign up into the AWS[3], go there and sign up first. AWS gives you a 12 months free tier subscription so you can choose free tier plan for practice. Then AWS reviews your account and might activate within 24 hours. After activation, sign in into aws console.<br><strong><em>I. Creating EC2 Instance<br></em></strong>Now, goto services and click on EC2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C68V97L3tG0IPlyvu16QxA.png" /></figure><p>Click on launch instance button and select one server. Here I am using Ubuntu 20.04 LTS.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gDCsvnVI3vENRgyOGGWbDQ.png" /></figure><p>Then choose free tier instance type.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KjC8_HePKXDieYZtAITR4Q.png" /></figure><p>Click Review and Launch and similarly click on Review and Launch for Configure Instance, Add Storage, Add Tags steps. Already AWS provides and select all default configuration. Now step-6 Configure Security Group is an important step that you need to specify the security groups and port number for your application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1oD8dKXJPxGKUtiUoEGUIQ.png" /></figure><p>Here you need to define the Inbound and outbound rules. Basically inbound rule controls the incoming traffic to your instance and outbound rule controls the outgoing traffic from your instance. You need to defined the both rules according to the your need. I want to access this from anywhere so I defined type as All Traffic and source as anywhere for both inbound and outbound . SSH type for remote access. You can also defined HTTP, HTTPS and some other type according to the need. There are multiple types you can explore on that.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EW2WDh4aX1ppME3F8fYSGA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*--PhzWBoBa-3WzNy58ZQNw.png" /></figure><p>After that click on Review and Launch and in final step, review once throughly and process for create. Then you will get private key (.pem file), download that file. This .pem file is very important for accessing the instance remotely.<br>Here I created ec2 instance name as ubuntuec2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sTanOft1oo982E7gcs1orA.png" /></figure><p>Select your EC2 instance and explore all the components that you configured. Below instance summary there you can see that Public IPv4 address and DNS that assign for your instance. If ping of that IP is reachable then everything is ok till now. <br><strong><em>II. Connecting With SSH Client<br></em></strong>After instance created, you need to connect your instance through following methods. You can use anyone method to connect. I will showing you how to connect your EC2 instance remotely using SSH client method. SSH Client method is a best way to connect your instance remotely. Or simply you can use EC2 Instance Connect method that opens virtual terminal right on your browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p64vKYuTgZ9exjn_Fj3ZWw.png" /><figcaption>Different methods for accessing EC2 instance</figcaption></figure><p>Click on SSH client tab and follows the steps.<br>- Open SSH client on your desktop. On mac or linux you can run on terminal and in windows you can use putty. Download Putty <a href="https://www.putty.org/">Here</a>.<br>- On terminal, locate your private key file i.e. pem file that you got when instance was launched.<br>- Run command: “chmod 400 my-private-key.pem”. Here my-private-key.pem is a private key name. This commands ensure that your key isnot publicly viewable.<br>- Run command: “ ssh -i “my-private-key.pem” ubuntu@ec2–100–26–252–19.compute-1.amazonaws.com” . Then you can connect your EC2 instance on your terminal like you see on below image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*hXpMilySKDv8Qdton5hW7w.png" /></figure><p><strong><em>III. Build and Run Container<br></em></strong>Now, first you need install node.js, mongodb and docker on this virtual ubuntu server same as you installed on your desktop machine. Then make a folder name as NodeProjects you can give any name as you want. I am creating this folder for placing all the node projects into it. Then navigate to NodeProjects folder then clone the git repository. <br>git clone <a href="https://github.com/mikalshrestha/crudnodejsapp.git">https://github.com/mikalshrestha/crudnodejsapp.git</a><br>Then navigate to root project folder(crudnodejsapp) and hit command “docker-compose up”. It creates and build the docker container on your virtual machine and start your node.js application.<br>You can see all docker images using command: “docker images”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/354/1*2JRz1RvxeR1F2_YEh0nSFg.png" /></figure><p><strong><em>IV. API Testing on Postman<br>1. </em></strong>Registration api(POST method): (Port number is 88 here because we map 5000 to 88 in docker-compose.yml file. If you don’t want to change then removed this command from this file.)<br><a href="http://ec2-54-84-193-65.compute-1.amazonaws.com:88/api/users">http://ec2-54-84-193-65.compute-1.amazonaws.com:88/api/users</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8AIMv4yMUCE93vY8oSFYeQ.png" /></figure><p><strong><em>2.</em></strong>Create post api(POST Method): <br><a href="http://ec2-54-84-193-65.compute-1.amazonaws.com:88/api/posts">http://ec2-54-84-193-65.compute-1.amazonaws.com:88/api/posts</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vGfVAiCIuS3DQVSNfC_zzw.png" /></figure><p><strong><em>3.</em></strong>Get post api(GET Method):<br><a href="http://ec2-54-84-193-65.compute-1.amazonaws.com:88/api/posts">http://ec2-54-84-193-65.compute-1.amazonaws.com:88/api/posts</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q8zeztlBmQSoj4rCOuLu6A.png" /></figure><p><strong><em>V. Accessing Mongo Container<br>- </em></strong>Connecting with mongodb shell:<br> command: “mongo”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ch3UhuW_jghAWxtk3LZLoQ.png" /></figure><p>-Displaying all databases on container:<br>command: show dbs</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/354/1*LCLQzCzdRi5RABrabZyQhg.png" /></figure><p>There you can see crud-node-app database.<br>- Navigate to crud-node-app database: “use crud-node-app”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/424/1*F95rLJrEjpOsmPZeS-_RiA.png" /></figure><p>-Finding created datas on crud-node-app database: “db.tablename.find()”<br>eg. db.users.find()</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JALXCulOhL7i2s9tFI8XDg.png" /></figure><h4>Conclusion:</h4><p>Now, you can build and deploy the node.js application following this article. But one thing when I every-time pushed the changes then I need to build the container every-time. So we can automate this manual process using CI/CD techniques. I will share you in another article about how to build automatically using CI/CD. That’s it for now, If you have any queries please shared on comment section. And if you like the story then hit the clap. Happy Learning 👏​.</p><p>Part-I link: <a href="https://mikalshrestha.medium.com/building-containerize-and-deploying-node-js-apis-into-aws-part-i-e274fa161cb6">https://mikalshrestha.medium.com/building-containerize-and-deploying-node-js-apis-into-aws-part-i-e274fa161cb6</a></p><p>Github link: <a href="https://github.com/mikalshrestha/crudnodejsapp">https://github.com/mikalshrestha/crudnodejsapp</a></p><h4>References:</h4><p>[1] Official Docker Website. “Docker Overview”<br><a href="https://docs.docker.com/get-started/overview/">https://docs.docker.com/get-started/overview/</a></p><p>[2] Docker Hub. “Docker Container Repo Source”<br><a href="https://hub.docker.com/">https://hub.docker.com/</a></p><p>[3] Official AWS Website. “What is AWS?”<br><a href="https://aws.amazon.com/">https://aws.amazon.com/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2dd8879f87" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building, Containerize and Deploying Node.Js APIs into AWS Part-I]]></title>
            <link>https://mikalshrestha.medium.com/building-containerize-and-deploying-node-js-apis-into-aws-part-i-e274fa161cb6?source=rss-4aaab36b00a8------2</link>
            <guid isPermaLink="false">https://medium.com/p/e274fa161cb6</guid>
            <category><![CDATA[rest-api-testing]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[expressjs]]></category>
            <dc:creator><![CDATA[Mikal Shrestha]]></dc:creator>
            <pubDate>Sat, 26 Jun 2021 04:14:56 GMT</pubDate>
            <atom:updated>2021-06-26T11:33:33.406Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>1. Building and Testing Node.js APIS<em><br>Introduction</em><br></strong>Node.js is an open source and backend JavaScript runtime environment that runs on a chrome’s V8 engine and executes the JavaScript code on a server. Node.js is oneof the market leading framework for developing backend apis because of it’s asynchronous(single threaded concept) nature, lightweight and easier to build apis. By the way Node.js is not actually a framework it’s a runtime environment. <br>For more info: <a href="https://nodejs.org/en/">https://nodejs.org/en/</a></p><p><strong><em>Technology Used</em><br></strong>Leaving more about theoretical concept let’s dive into the practical way to build apis. Here I am using MongoDB for database operations like create, read, update, delete etc. and Express as a server. Express is a backend web applications framework for node.js. <br>For More info: <a href="https://www.mongodb.com/">https://www.mongodb.com/</a> , <a href="https://expressjs.com/">https://expressjs.com/</a></p><p><strong><em>Libraries Used and it’s Applications:<br></em>1. Mongoose:</strong> Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node. js. It manages relationships between data, provides schema validation, and is used to translate between objects in code and the representation of those objects in MongoDB.<br><strong>2. Express: </strong>Backend web application framework for node.js.<br><strong>3. Express-Validator</strong>: Server side validation.<br><strong>4. JsonWebToken: </strong>Secure communication between the APIs and token based authentication.<br><strong>5. Bcryptjs: </strong>Generating hash password.<br><strong>6. Config:</strong> Manage different configuration variables in node application.</p><p><strong><em>Development Tools Used<br></em>VsCode: </strong>For code editor.<br><strong>Postman: </strong>API testing.</p><p><strong><em>Application Architecture:</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jsPjSaG93-nz4KMTOIIqNA.png" /></figure><p><strong><em>Async/Await : </em></strong><em>Used to deal with p</em>romises and function chaining. The functions need not to be chained one after another, simply await the function that returns the promise. But the function async needs to be declared before awaiting a function returning a promise. Async function always return a promise, even if you don’t explicitly write them to do so and await function always defined inside the async function. In an async function, you can await any promise or catch its rejection cause as an exception.<br><a href="https://blog.risingstack.com/mastering-async-await-in-nodejs/">https://blog.risingstack.com/mastering-async-await-in-nodejs/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DEW4V0y9W07TH_P5QqZIuQ.png" /></figure><p><strong><em>Steps For Creating APIs:<br></em></strong>Before jumping into the code you must install <strong>Node.js</strong> on your machine first, for that you can go official website of node.js and install it according to your operating system. And also install <strong>VsCode</strong> and <strong>Postman</strong> for development and testing. If you are done then you are ready to go.<br>1. Navigate to the root project folder and run command: “npm init”. You have to answer the some questions that describes your project. That creates a package.json file under root project folder. (don’t forgot to add entry point as server.js while answering the questions). This commands creates a package.json file where we put all the dependencies and scripts required for our application.<br>2. Create a server.js file under root folder.(Describes below)<br>3. Then let’s install all required libraries. Under root folder run command: “npm i mongoose express express-validator config bcryptjs jsonwebtoken ”<br>and let’s also install nodemon that constantly watch our server so we don’t need to refreshed everytime when we make a change. Under root folder run command: “npm i -D nodemon” .<br>4. Here I am using mongodb cloud version you can also install on your machine and create a schemas but for this purpose I am using cloud version it’s free for development purpose. You can create an account and easy to create your cluster on a mongodb cloud.<br>Create and login cloud mongodb atlas -&gt;create and configure cluster . Then go to connect option in cluster and click on connect to your application. You can get a string snippet code there.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*ZD4MN_FoaZ09t-6TJR8_7g.png" /></figure><p>5. Create a config package under root project folder. Under config package create default.json file where we put mongodb url and some other configuration variables. With the help of config library we can directly used these variables wherever we need in our application by referencing it’s key name.<br><em>default.json:</em></p><pre>{<br> “mongoURI”: “mongodb+srv://mikal:<a href="/service/mailto:mikal12@cluster0.yynn5.mongodb.net">mikal12@cluster0.yynn5.mongodb.net</a>/myFirstDatabase?retryWrites=true&amp;w=majority”,<br> “jwtSecret”: “secret”<br>}</pre><p>And create dbconnection.js file under config package that connects our app to mongodb database.<br><em>dbconnection.js: This basically helps for connecting our node app to mongodb database.</em></p><pre>const mongoose = require(‘mongoose’);<br>const config = require(‘config’);<br>const db = config.get(‘mongoURI’);</pre><pre>const connectDB = async () =&gt; {<br> try {<br> await mongoose.connect(db, {<br> useNewUrlParser: true,<br> useCreateIndex: true,<br> useFindAndModify: false,<br> useUnifiedTopology: true<br> });</pre><pre>console.log(‘MongoDB Connected…’);<br> } catch (err) {<br> console.error(err.message);<br> // Exit process with failure<br> process.exit(1);<br> }<br>};</pre><pre>module.exports = connectDB;</pre><p>6. Create a models package. And create a User and Post class under models package which models the users and posts data in a mongodb database.<br><em>User.js:</em></p><pre><em><br></em>const mongoose = require(‘mongoose’);</pre><pre>const UserSchema = new mongoose.Schema({<br> name: {<br> type: String,<br> required: true<br> },<br> email: {<br> type: String,<br> required: true,<br> unique: true<br> },<br> password: {<br> type: String,<br> required: true<br> },<br> date: {<br> type: Date,<br> default: Date.now<br> }<br>});</pre><pre>module.exports = mongoose.model(‘user’, UserSchema);</pre><p><em>Post.js:</em></p><pre>const mongoose = require(‘mongoose’);<br>const Schema = mongoose.Schema;</pre><pre>const PostSchema = new Schema({<br> user: {<br> type: Schema.Types.ObjectId<br> },<br> text: {<br> type: String,<br> required: true<br> },<br> name: {<br> type: String<br> },<br> <br> date: {<br> type: Date,<br> default: Date.now<br> }<br>});</pre><pre>module.exports = mongoose.model(‘post’, PostSchema);</pre><p>7. Here I am using jsonwebtoken for token based communication between the apis. Now create middleware package under root folder. Under middleware package create auth.js and checkObjectId.js. <br><em>auth.js: It helps for getting token from header that we defined, check and verify the token.</em></p><pre>const jwt = require(‘jsonwebtoken’);<br>const config = require(‘config’);</pre><pre>module.exports = function (req, res, next) {<br> // Get token from header<br> const token = req.header(‘x-auth-token’);</pre><pre>// Check if not token<br> if (!token) {<br> return res.status(401).json({ msg: ‘No token, authorization denied’ });<br> }</pre><pre>// token verification<br> try {<br> jwt.verify(token, config.get(‘jwtSecret’), (error, decoded) =&gt; {<br> if (error) {<br> return res.status(401).json({ msg: ‘Token is not valid’ });<br> } else {<br> req.user = decoded.user;<br> next();<br> }<br> });<br> } catch (err) {<br> console.error(‘something wrong with auth middleware’);<br> res.status(500).json({ msg: ‘Server Error’ });<br> }<br>};</pre><p><em>checkObjectId.js: Checks the object id valid or not.</em></p><pre>const mongoose = require(‘mongoose’);<br>//object id validation<br>const checkObjectId = (idToCheck) =&gt; (req, res, next) =&gt; {<br> if (!mongoose.Types.ObjectId.isValid(req.params[idToCheck]))<br> return res.status(400).json({ msg: ‘Invalid ID’ });<br> next();<br>};</pre><pre>module.exports = checkObjectId;</pre><p>8. create routes package and under routes create api package. Under api create users.js, auth.js and posts.js. This creates a public and private endpoints. Here I am going to create a some endpoints for login, get token ,registration of users, create posts, get posts, delete posts.<br><em>users.js:</em></p><pre>const express = require(‘express’);<br>const router = express.Router();<br>const bcrypt = require(‘bcryptjs’);<br>const jwt = require(‘jsonwebtoken’);<br>const config = require(‘config’);<br>const { check, validationResult } = require(‘express-validator’);<br>const normalize = require(‘normalize-url’);</pre><pre>const User = require(‘../../models/User’);</pre><pre>// user registration public api<br>router.post(<br> ‘/’,<br> check(‘name’, ‘Name is required’).notEmpty(),<br> check(‘email’, ‘Please include a valid email’).isEmail(),<br> check(<br> ‘password’,<br> ‘Please enter a password with 6 or more characters’<br> ).isLength({ min: 6 }),<br> async (req, res) =&gt; {<br> const errors = validationResult(req);<br> if (!errors.isEmpty()) {<br> return res.status(400).json({ errors: errors.array() });<br> }</pre><pre>const { name, email, password } = req.body;</pre><pre>try {<br> let user = await User.findOne({ email });</pre><pre>if (user) {<br> return res<br> .status(400)<br> .json({ errors: [{ msg: ‘User already exists’ }] });<br> }</pre><pre>user = new User({<br> name,<br> email,<br> password<br> });</pre><pre>const salt = await bcrypt.genSalt(10);</pre><pre>user.password = await bcrypt.hash(password, salt);</pre><pre>await user.save();</pre><pre>const payload = {<br> user: {<br> id: user.id<br> }<br> };</pre><pre>jwt.sign(<br> payload,<br> config.get(‘jwtSecret’),<br> { expiresIn: ‘5 days’ },<br> (err, token) =&gt; {<br> if (err) throw err;<br> res.json({ token });<br> }<br> );<br> } catch (err) {<br> console.error(err.message);<br> res.status(500).send(‘Server error’);<br> }<br> }<br>);</pre><pre>module.exports = router;</pre><p><em>auth.js:</em></p><pre>const express = require(‘express’);<br>const router = express.Router();<br>const bcrypt = require(‘bcryptjs’);<br>const auth = require(‘../../middleware/auth’);<br>const jwt = require(‘jsonwebtoken’);<br>const config = require(‘config’);<br>const { check, validationResult } = require(‘express-validator’);</pre><pre>const User = require(‘../../models/User’);</pre><pre>// Get users token(private api)</pre><pre>router.get(‘/’, auth, async (req, res) =&gt; {<br> try {<br> const user = await User.findById(req.user.id).select(‘-password’);<br> res.json(user);<br> } catch (err) {<br> console.error(err.message);<br> res.status(500).send(‘Server Error’);<br> }<br>});</pre><pre>// Login and get token api<br>router.post(<br> ‘/’,<br> check(‘email’, ‘Please include a valid email’).isEmail(),<br> check(‘password’, ‘Password is required’).exists(),<br> async (req, res) =&gt; {<br> const errors = validationResult(req);<br> if (!errors.isEmpty()) {<br> return res.status(400).json({ errors: errors.array() });<br> }</pre><pre>const { email, password } = req.body;</pre><pre>try {<br> let user = await User.findOne({ email });</pre><pre>if (!user) {<br> return res<br> .status(400)<br> .json({ errors: [{ msg: ‘Invalid Credentials’ }] });<br> }</pre><pre>const isMatch = await bcrypt.compare(password, user.password);</pre><pre>if (!isMatch) {<br> return res<br> .status(400)<br> .json({ errors: [{ msg: ‘Invalid Credentials’ }] });<br> }</pre><pre>const payload = {<br> user: {<br> id: user.id<br> }<br> };</pre><pre>jwt.sign(<br> payload,<br> config.get(‘jwtSecret’),<br> { expiresIn: ‘5 days’ },<br> (err, token) =&gt; {<br> if (err) throw err;<br> res.json({ token });<br> }<br> );<br> } catch (err) {<br> console.error(err.message);<br> res.status(500).send(‘Server error’);<br> }<br> }<br>);</pre><pre>module.exports = router;</pre><p><em>posts.js:</em></p><pre>const express = require(‘express’);<br>const router = express.Router();<br>const { check, validationResult } = require(‘express-validator’);<br>const auth = require(‘../../middleware/auth’);</pre><pre>const Post = require(‘../../models/Post’);<br>const User = require(‘../../models/User’);<br>const checkObjectId = require(‘../../middleware/checkObjectId’);</pre><pre>// POST api/posts (Private API)<br><br>router.post(<br> ‘/’,<br> auth,<br> check(‘text’, ‘Text is required’).notEmpty(),<br> async (req, res) =&gt; {<br> const errors = validationResult(req);<br> if (!errors.isEmpty()) {<br> return res.status(400).json({ errors: errors.array() });<br> }</pre><pre>try {<br> const user = await User.findById(req.user.id).select(‘-password’);</pre><pre>const newPost = new Post({<br> text: req.body.text,<br> name: user.name,<br> user: req.user.id<br> });</pre><pre>const post = await newPost.save();</pre><pre>res.json(post);<br> } catch (err) {<br> console.error(err.message);<br> res.status(500).send(‘Server Error’);<br> }<br> }<br>);</pre><pre>// GET api/posts (Private API)</pre><pre>router.get(‘/’, auth, async (req, res) =&gt; {<br> try {<br> const posts = await Post.find().sort({ date: -1 });<br> res.json(posts);<br> } catch (err) {<br> console.error(err.message);<br> res.status(500).send(‘Server Error’);<br> }<br>});</pre><pre>// GET api/posts/:id (Private API)</pre><pre>router.get(‘/:id’, auth, checkObjectId(‘id’), async (req, res) =&gt; {<br> try {<br> const post = await Post.findById(req.params.id);</pre><pre>if (!post) {<br> return res.status(404).json({ msg: ‘Post not found’ });<br> }</pre><pre>res.json(post);<br> } catch (err) {<br> console.error(err.message);</pre><pre>res.status(500).send(‘Server Error’);<br> }<br>});</pre><pre>// DELETE api/posts/:id (Private API)</pre><pre>router.delete(‘/:id’, [auth, checkObjectId(‘id’)], async (req, res) =&gt; {<br> try {<br> const post = await Post.findById(req.params.id);</pre><pre>if (!post) {<br> return res.status(404).json({ msg: ‘Post not found’ });<br> }</pre><pre>// Check user authorized<br> if (post.user.toString() !== req.user.id) {<br> return res.status(401).json({ msg: ‘User not authorized’ });<br> }</pre><pre>await post.remove();</pre><pre>res.json({ msg: ‘Post removed’ });<br> } catch (err) {<br> console.error(err.message);</pre><pre>res.status(500).send(‘Server Error’);<br> }<br>});</pre><pre>module.exports = router;</pre><p>9. server.js creates an express server which helps for connecting to database, initializing middleware, defining routes. We also need to define a port number that the express app server listens on it.<br><em>server.js:</em></p><pre>const express = require(‘express’);<br>const connectDB = require(‘./config/dbconnection’);</pre><pre>const app = express();</pre><pre>// Database connection<br>connectDB();</pre><pre>app.use(express.json());</pre><pre>// API Routing<br>app.use(‘/api/users’, require(‘./routes/api/users’));<br>app.use(‘/api/auth’, require(‘./routes/api/auth’));<br>app.use(&#39;/api/posts&#39;, require(&#39;./routes/api/posts&#39;));</pre><pre>//process.env.PORT --&gt; takes deployment port number<br>//5000 --&gt; locally defined port</pre><pre>const PORT = process.env.PORT || 5000;</pre><pre>app.listen(PORT, () =&gt; console.log(`Server started on port ${PORT}`));</pre><p>After all steps completed, then run command “npm start” on a terminal. Then it starts your local server that runs on a port number which you defined on a server.js.</p><p><em>API Testing on Postman:</em></p><ol><li>Registration api(POST method): <a href="http://localhost:5000/api/users">http://localhost:5000/api/users</a></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nOd5U0bIVjAFotY4M-ALgw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7TxbALh6qtF3ZaAjjP3AbQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-viu0HNnw0wYqsv4yQYIOg.png" /></figure><p>2. Login api(POST method): <a href="http://localhost:5000/api/auth">http://localhost:5000/api/auth</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*60YQGYBI-fTGv4V4mUM3yg.png" /></figure><p>3. Create post api(POST method):http://localhost:5000/api/posts</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pwSeOhrAIisZ712qXPMROg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_db_D4rW267GOZ3GPb_iCA.png" /></figure><p>4. Get all posts and get post by id(GET method):<br>http://localhost:5000/api/posts<br>http://localhost:5000/api/posts/{id}</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GjImrIBmKrk0524elJhhQA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9zXvLzOPK9FO4dGpTKbqeg.png" /></figure><p>5. Delete post by id(DELETE method):http://localhost:5000/api/posts/{id}</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W3QlADe4wPrs3cBVvl59Cg.png" /></figure><p>→In MongoDB: Goto collection section of your database in a cluster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G-i_b2IaZVYhL0jfb4AoHA.png" /></figure><p>If you have any queries please feel free to share your thoughts below. And if you need, checkout the code:<br><a href="https://github.com/mikalshrestha/crudnodejsapp">https://github.com/mikalshrestha/crudnodejsapp</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e274fa161cb6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>