<?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 Rahul Thai Valappil on Medium]]></title>
        <description><![CDATA[Stories by Rahul Thai Valappil on Medium]]></description>
        <link>https://medium.com/@rahulthaivalappil?source=rss-e8e905826057------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*a52GM_Pgc6_Q4fWz</url>
            <title>Stories by Rahul Thai Valappil on Medium</title>
            <link>https://medium.com/@rahulthaivalappil?source=rss-e8e905826057------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 13:34:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rahulthaivalappil/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[Deploy and Serve AI Models (Part 2 — TensorFlow Serving)]]></title>
            <link>https://medium.com/codex/deploy-and-serve-ai-models-part2-tensorflow-serving-f144c4cf5ea7?source=rss-e8e905826057------2</link>
            <guid isPermaLink="false">https://medium.com/p/f144c4cf5ea7</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[tensorflow-serving]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[deployment]]></category>
            <dc:creator><![CDATA[Rahul Thai Valappil]]></dc:creator>
            <pubDate>Fri, 30 Jul 2021 15:21:19 GMT</pubDate>
            <atom:updated>2021-07-30T16:42:33.149Z</atom:updated>
            <content:encoded><![CDATA[<h3>Deploy and Serve AI Models (Part 2 — TensorFlow Serving)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*50sGQftZ4MwUcWvX" /><figcaption>Photo by <a href="https://unsplash.com/@sortino?utm_source=medium&amp;utm_medium=referral">Joshua Sortino</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This is a continuation of my series about the deployment of AI models in production scenarios(<a href="https://medium.com/codex/deploy-and-server-ai-models-part-1-bf309dc41f4b">Part-1</a>). TensorFlow serving allows developers to integrate ML model prediction, detection, or classification in a cloud or on-premise server independently of the client system configuration. So that application users don&#39;t need to bother about the heavy computing capacity needed for running DNN models. AI application client-side can make inferences on data without actually having to install TensorFlow or even have any contact with the actual model, and the ability to serve multiple clients with one instance of a model.</p><p><strong>How to Setup TensorFlow Serving</strong></p><p>First and foremost you need a model to serve the inference. I have taken a single TensorFlow model implemented the <a href="https://github.com/blaueck/tf-mtcnn">MTCNN</a> face detector. Before setting up the serving environment, needs to convert the model from frozen format to SavedModel format in order to serve with <a href="https://www.tensorflow.org/tfx/serving/tutorials/Serving_REST_simple">TensorFlow Serving</a>.</p><p><em>Environment used</em></p><pre>Tensorflow 2.3.1<br>tensorflow-serving-api 2.3.0</pre><p><em>Python code for frozen MTCNN to SavedModel conversion</em></p><pre>from os.path import join<br>import tensorflow.compat.v1 as tf</pre><pre>tf.disable_v2_behavior()<br>tf.compat.v1.disable_eager_execution()<br>from tensorflow.python.saved_model import signature_constants</pre><pre>def read_pb_model(pb_model_path):<br>    with tf.gfile.GFile(pb_model_path, &quot;rb&quot;) as f:<br>        graph_def = tf.GraphDef()<br>        graph_def.ParseFromString(f.read())<br>        return graph_def</pre><pre>graph_def = read_pb_model(join(&#39;models&#39;, &#39;mtcnn.pb&#39;))<br>builder = tf.saved_model.builder.SavedModelBuilder(&#39;./mtcnn/1&#39;)</pre><pre>sigs = {}<br>with tf.Session(graph=tf.Graph()) as sess:<br>    tf.import_graph_def(graph_def, name=&quot;&quot;)<br>    graph_model = tf.get_default_graph()<br>    tf.initialize_all_variables().run()<br>    input_image_tensor = graph_model.get_tensor_by_name(&#39;input:0&#39;)<br>    input_min_size_tensor = graph_model.get_tensor_by_name(&#39;min_size:0&#39;)<br>    input_thresholds_tensor = graph_model.get_tensor_by_name(&#39;thresholds:0&#39;)<br>    input_factor_tensor = graph_model.get_tensor_by_name(&#39;factor:0&#39;)</pre><pre>output_prob_tensor = graph_model.get_tensor_by_name(&#39;prob:0&#39;)<br>    output_landmarks_tensor = graph_model.get_tensor_by_name(&#39;landmarks:0&#39;)<br>    output_box_tensor = graph_model.get_tensor_by_name(&#39;box:0&#39;)</pre><pre>sigs[signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY] = \<br>        tf.saved_model.signature_def_utils.predict_signature_def(<br>            {&#39;input&#39;: input_image_tensor, &#39;min_size&#39;: input_min_size_tensor,<br>                    &#39;thresholds&#39;: input_thresholds_tensor,<br>                    &#39;factor&#39;: input_factor_tensor},<br>            {&#39;prob&#39;: output_prob_tensor, &#39;landmarks&#39;: output_landmarks_tensor,<br>                     &#39;box&#39;: output_box_tensor})<br>    builder.add_meta_graph_and_variables(<br>        sess=sess,<br>        tags=[tf.saved_model.tag_constants.SERVING],<br>        signature_def_map=sigs)<br>    builder.save()</pre><p><em>Model Repository Structure</em></p><pre>mtcnn<br>  |<br>  |__ 1<br>  |     |saved_model.pb<br>  |     |__variables</pre><p><em>Set Up TensorFlow Serving</em></p><pre>echo &quot;deb http://storage.googleapis.com/tensorflow-serving-apt stable tensorflow-model-server tensorflow-model-server-universal&quot; | sudo tee /etc/apt/sources.list.d/tensorflow-serving.list</pre><pre>curl https://storage.googleapis.com/tensorflow-serving-apt/tensorflow-serving.release.pub.gpg | apt-key add -</pre><pre>apt update</pre><pre>apt-get install tensorflow-model-server</pre><p><em>Start TensorFlow Serving</em></p><pre>tensorflow_model_server --rest_api_port=8504 --model_name=mtcnn --model_base_path=&quot;/tmp/mtcnn&quot;</pre><pre>rest_api_port: The port that you&#39;ll use for REST requests</pre><pre>model_name: You&#39;ll use this in the URL of REST requests. It can be anything.</pre><pre>model_base_path: This is the path to the directory where you&#39;ve saved your model</pre><p>Once Tensorflow serving started you can check the model metadata</p><pre>import grpc<br>from tensorflow_serving.apis import prediction_service_pb2_grpc<br>from tensorflow_serving.apis import get_model_metadata_pb2</pre><pre>request = get_model_metadata_pb2.GetModelMetadataRequest()<br>request.model_spec.name = &#39;mtcnn&#39;<br>request.metadata_field.append(&#39;signature_def&#39;)<br>channel = grpc.insecure_channel(target=&#39;0.0.0.0:8500&#39;)<br>stub = prediction_service_pb2_grpc.PredictionServiceStub(channel)<br>result = stub.GetModelMetadata(request, 5.0)<br># Verify response<br>print(result)</pre><p>response of MTCNN metadata, this can be used to prepare the input request for original model inference</p><pre>model_spec {<br>  name: &quot;mtcnn&quot;<br>  version {<br>    value: 1<br>  }<br>}<br>metadata {<br>  key: &quot;signature_def&quot;<br>  value {<br>    type_url: &quot;type.googleapis.com/tensorflow.serving.SignatureDefMap&quot;<br>    value: &quot;\n\262\002\n\017serving_default\022\236\002\n$\n\nthresholds\022\026\n\014thresholds:0\020\001\032\004\022\002\010\003\n4\n\005input\022+\n\007input:0\020\001\032\036\022\013\010\377\377\377\377\377\377\377\377\377\001\022\013\010\377\377\377\377\377\377\377\377\377\001\022\002\010\003\n\036\n\010min_size\022\022\n\nmin_size:0\020\001\032\002\030\001\n\032\n\006factor\022\020\n\010factor:0\020\001\032\002\030\001\022\024\n\003box\022\r\n\005box:0\020\001\032\002\030\001\022!\n\004prob\022\031\n\006prob:0\020\001\032\r\022\013\010\377\377\377\377\377\377\377\377\377\001\022/\n\tlandmarks\022\&quot;\n\013landmarks:0\020\001\032\021\022\013\010\377\377\377\377\377\377\377\377\377\001\022\002\010\n\032\032tensorflow/serving/predict&quot;<br>  }<br>}</pre><h4>Run Face Detection with TensorFlow serving</h4><ul><li>Start the TensorFlow serving</li><li>Create a python file mtcnn_detection.py and import all necessary modules</li></ul><pre>import json<br><br>import grpc<br>import requests<br>import cv2<br>import tensorflow as tf<br>from tensorflow_serving.apis import predict_pb2<br>from tensorflow_serving.apis import prediction_service_pb2_grpc<br>from tensorflow_serving.apis import get_model_metadata_pb2</pre><ul><li>read image from the test file</li></ul><pre>image = cv2.imread(image_file)</pre><ul><li>prepare input requests for the serving. TensorFlow serving exposed ports ‘8500’ and 8504 for gRPC and HTTP rest API requests respectively. In this sample, we use the gRPC protocol to communicate from the client application to the TensorFlow server. Expected input and output names will be get from the model metadata which is executed earlier.</li></ul><pre>channel = grpc.insecure_channel(target=&#39;localhost:8500&#39;)<br>stub = prediction_service_pb2_grpc.PredictionServiceStub(channel)<br>request = predict_pb2.PredictRequest()<br>equest.model_spec.name = &#39;mtcnn&#39;<br><br>request.model_spec.signature_name = &#39;serving_default&#39;</pre><pre>input = tf.make_tensor_proto(image, dtype=tf.float32, shape=image.shape)<br>min_size = tf.make_tensor_proto(40, dtype=tf.float32, shape=())<br>factor = tf.make_tensor_proto(0.7, dtype=tf.float32, shape=())<br>thresholds = tf.make_tensor_proto([0.6, 0.7, 0.8], dtype=tf.float32, shape=[3])</pre><pre>request.inputs[&#39;input&#39;].CopyFrom(input)<br>request.inputs[&#39;min_size&#39;].CopyFrom(min_size)<br>request.inputs[&#39;factor&#39;].CopyFrom(factor)<br>request.inputs[&#39;thresholds&#39;].CopyFrom(thresholds)</pre><ul><li>Request the face detection</li></ul><pre>result = stub.Predict(request,10.0)</pre><ul><li>Convert the results to an array and draw the bounding boxes for the detected faces</li></ul><pre>bbox_data_list = tf.make_ndarray(result.outputs[&#39;box&#39;])<br>for bbox_data in bbox_data_list:<br>    box = bbox_data.astype(&#39;int32&#39;)<br>    img = cv2.rectangle(img, (box[1], box[0]), (box[3], box[2]), (0, 255    , 0), 3)</pre><ul><li>save the image</li></ul><pre>cv2.imwrite(&#39;test1.png&#39;, image)</pre><p><em>Result</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TuljgYn9RVxzQ-xvX89q8g.png" /></figure><h4>Conclusion</h4><p>Using TensorFlow serving for inference makes the process of taking a model into production easier and faster. It is ideal for running multiple models, at a large scale and facilitate the deployment of new models and <a href="https://tensorflow.github.io/serving/serving_advanced">run experiments</a> while keeping the same server architecture and APIs. However, it supports only the TensorFlow SavedModel format and needs to convert this format before using it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f144c4cf5ea7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/deploy-and-serve-ai-models-part2-tensorflow-serving-f144c4cf5ea7">Deploy and Serve AI Models (Part 2 — TensorFlow Serving)</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploy and Serve AI Models (Part-1)]]></title>
            <link>https://medium.com/codex/deploy-and-server-ai-models-part-1-bf309dc41f4b?source=rss-e8e905826057------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf309dc41f4b</guid>
            <category><![CDATA[nvidia]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deployment]]></category>
            <dc:creator><![CDATA[Rahul Thai Valappil]]></dc:creator>
            <pubDate>Wed, 28 Jul 2021 15:13:56 GMT</pubDate>
            <atom:updated>2021-07-30T10:28:23.969Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/625/0*DJpXJbVYrhNQjrCk.png" /><figcaption>Source Nvidia</figcaption></figure><p>Model creation is just a step towards creating real-world AI solutions. Moreover, AI models need to deploy, host, and serve in order to run the predictions, detections, and classifications of the input(generally running the model inference ) in real-world scenarios. Most of the AI applications has the following workflows</p><ul><li>Capture the input data based on the model. For example frames from a video source for object detection.</li><li>Perform the pre-processing on the input data. Most of the models expecting the input data in specific format or dimensions. example crop the image into a specific size, apply normalization or permute the dimension of the data, etc.</li><li>Run the model inference using the input data for the object detection, prediction, recognition, or classification</li><li>Perform the post-processing of the inference results. Sometimes needs to discards the data from the output based on the threshold or needs to choose the most appropriate bounding box(Non-Max Suppression) for the object detection results.</li></ul><h4>Inference of AI model</h4><p>Deep learning inference is the process of running a trained DNN model to make detection, prediction, or classification against previously unseen data. So that deploying a trained DNN model to the proper platform is important in AI applications for inference as it demands more computing and memory power. AI application performance and latency ( response time from when you input data to the DNN until you receive a result) depends on the computing capacity of the deployed system. So most of the time AI trained models should be optimized(pruning and quantization) to reduce computing power and latency.</p><p>Model Inference can be done on-premise or in the cloud using either CPU or GPU. So that these can be accessed from desktop, mobile, or web applications or cloud services.</p><p>Furthermore, we will focus on the model Deployment/Inferencing. The deployment strategy should depend on the application type(desktop, web app, etc), mode(offline or online), or real-time and latency.</p><h4>Offline Deployment of AI models</h4><p>This approach is better if your application has limited access to the internet or network communication time is crucial in your application decision-making process. For example, a fire detection system should generate an alarm in real-time with low latency from a camera. In this case, AI models need to be shipped along with the application and run the inference on-premise.</p><p>The standalone application which can be run on, user PC or a single-board computer like nano jetson or raspberry pi is more suitable for this type. The main drawback of this approach is, the host machine should have a high computing capacity like GPU in order to speed up by parallelizing the deep learning execution.</p><p>QT or Python is a suitable framework for building these kinds of applications if you are planning to target cross platforms. QT is a powerful framework to build cross-platform standalone applications in c++ and also provide python bindings to build an application in a python environment. QT c++ is an apt choice if your application is performance-critical. Most of the ML frameworks like TensorFlow, PyTorch provides API in both python and c++ environments.</p><h4>Online Deployment of AI models</h4><p>A trained AI model can be deployed in the cloud or on-premise server and can be accessed from the client application for the model inference through a network connection. This approach is suitable for all types of applications but you need to consider network latency as compared to the offline application. This provides remote inferencing capability to the client applications by using HTTP/REST and GRPC protocol. So that users do not need to equip with heavy computing capacity like GPU and reduce the cost. There are a lot of service providers like AWS, Azure, GCP, etc provide cloud facilities to deploy and host your ML models. But I am focusing more on inference servers.</p><p><a href="https://www.tensorflow.org/tfx/guide/serving">Tensorflow serving</a> and <a href="https://github.com/triton-inference-server/server">Nvidia Triton Inference server</a> are most popular inference server which allows hosting your models. However, the Triton server supports multiple frameworks like TensorFlow, TensorRT, PyTorch, ONNX Runtime, and even custom framework backends. Moreover, It supports the creation of customized python backends for inference serving. It provides flexibility to choose a framework for the projects. Triton high-performance inference allows to run models concurrently on GPUs to maximize utilization, supports CPU-based inferencing, and offers advanced features like model ensemble and streaming inferencing.</p><figure><img alt="https://developer.nvidia.com/sites/default/files/akamai/ai-for-enterprise-print-update-to-triton-diagram-1339418-final-r3.jpg" src="https://cdn-images-1.medium.com/max/691/0*OaybJ-ooiFmIs-68.jpg" /><figcaption>Source <a href="https://developer.nvidia.com/sites/default/files/akamai/ai-for-enterprise-print-update-to-triton-diagram-1339418-final-r3.jpg">Nvidia</a></figcaption></figure><p><strong>Triton server Advantages</strong></p><ol><li>Load models from local storage or cloud platforms</li><li>Easily update models without restarting the server</li><li>Run multiple models from the same or different frameworks</li><li>Supports real-time inferencing and batch inferencing</li><li>Supports model ensemble</li></ol><h4>Conclusion</h4><p>This topic just covered the basic deployment strategy of ML models to build the application for end-users. In the coming series, I will focus more on how to server ML model with inference servers such as <a href="https://www.tensorflow.org/tfx/guide/serving">Tensorflow serving</a> and <a href="https://github.com/triton-inference-server/server">Nvidia Triton Inference server</a> and how to accommodate post and pre-processing logic without a separate server(ensemble model).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf309dc41f4b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/deploy-and-server-ai-models-part-1-bf309dc41f4b">Deploy and Serve AI Models (Part-1)</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create Standalone Linux Installer for your Python GUI Application]]></title>
            <link>https://medium.com/codex/create-standalone-linux-installer-for-your-python-ai-application-5a31d99f9094?source=rss-e8e905826057------2</link>
            <guid isPermaLink="false">https://medium.com/p/5a31d99f9094</guid>
            <category><![CDATA[application]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[installation]]></category>
            <category><![CDATA[pyinstaller]]></category>
            <category><![CDATA[unix]]></category>
            <dc:creator><![CDATA[Rahul Thai Valappil]]></dc:creator>
            <pubDate>Thu, 15 Jul 2021 15:12:10 GMT</pubDate>
            <atom:updated>2021-07-16T09:27:27.436Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*esllsUtx1jqAR76b.jpg" /></figure><p>Sometimes you may need to develop your application&#39;s graphical user interface in python as it provides a fast and easy way to create GUI applications. In addition, creating python GUI provides easy integration of Machine learning (ML) inference of trained models. As a consequence, this saves time for putting an ML model into production.</p><p>There are lots of options available for developing GUI applications in python and Tkinter is one of the most popular libraries for developing desktop applications. However, it is difficult to distribute Python applications to end-users as we do not want to distribute our source code along with the application because of protecting intellectual property or possible conflict between python development and end-user environments.</p><p>Setting up a python environment is not easy, especially for non-developers. The typical workflow of setting up a Python environment looks like below.</p><ul><li>Installing a specific version of Python</li><li>Set up pip</li><li>Set up a virtual environment</li><li>Setup application source code</li><li>Install dependencies</li></ul><p>The possible option is to use compiled bytecode, but generated <strong>.pyc</strong> files are not portable between different versions of python and you still can decompile the <strong>pyc</strong> file to reverse engineering. Using a combination of options like <a href="http://www.pyinstaller.org/">PyInstaller</a> and <a href="https://wiki.python.org/moin/Pyarmor">Pyarmor</a> will help us to protect our code to an extent.</p><h3>PyInstaller</h3><p>Provides the flexibility to distribute python applications as a normal package installer. It Bundles a Python application and all its dependencies into a single package. The user can run the packaged app without installing a Python interpreter or any modules. PyInstaller inspects your Python code and finds out the dependencies, and then packaging them into a suitable format based on the Operating System. Please check <a href="https://pyinstaller.readthedocs.io/en/stable/usage.html">https://pyinstaller.readthedocs.io/en/stable/usage.html</a> for more details about options available in the PyInstaller command line.</p><h3>Pyarmor</h3><p>Helps to obfuscate python scripts using the command-line tool. A detailed explanation will be available in <a href="https://wiki.python.org/moin/Pyarmor">https://wiki.python.org/moin/Pyarmor</a></p><h3>Makeself</h3><p>Allows creating a self-extracting distribution package in Unix systems. <a href="https://makeself.io/">Makeself</a> is an easy way to create self-extracting archives.</p><h3>How to Create Distribution package for Python Application</h3><h4>Application Structure</h4><pre>myapp<br>  |<br>  |-- __init__.py<br>  |-- myapp.py<br>  |-- anothermod.py<br>  |-- python files and other resources<br>  |__ <strong>dist<br>  |     |myapp<br>  |__ makeself_stage<br>  |     |installer.sh<br>  |__ build.sh</strong><br>  | ..</pre><p>The application folder contains all the necessary python files and resources needed for the application. As a best practice, all the script needed for the package creation logic is separated to <strong>build.sh</strong> file. Following are the stepwise contents of the build.sh</p><ul><li>Declare Pyarmor path in bash script. This can be passed as an argument to the script. Pyarmor auto-detect the PyInstaller if it is installed in your system.</li></ul><p>PYARMOR=&quot;$HOME/.local/bin/pyarmor&quot;</p><ul><li>You can build and prepare your dependent modules in this pre-processing step. This includes copying the binaries and libraries to a proper folder</li><li>Now generate distribution packages with pyarmor. Pyarmor provides the option “pack” to pack obfuscated scripts into the bundle. This option uses pyinstaller for creating the package bundle. Also, you can use the option “-e” to pass extra options to pyinstaller</li></ul><p>${PYARMOR} pack --clean -e &#39;--paths=&#39;path_to_search_imports:.&#39; --hidden-import=&#39;PIL._tkinter_finder&#39; --add-binary=&#39;path_to_lib.so:.&#39; --exclude-module=modules_not_needed --add-data=&#39;./Config:Config&#39; --add-data=&#39;./*.png:.&#39;&#39; <strong>myapp.py</strong></p><p>Pyarmor creates by default bundled package in /dist you can change this by passing output path using “-O or — output” option</p><ul><li>The final step is to create self-extracting archives using the makeself from the package folder created by the pyarmor from /dist folder</li></ul><ol><li>Setup makeself</li></ol><p>sudo apt-get install makeself</p><p>2. Create payload or archive file of the /dist folder in order to create self-extracting run file</p><p>cd dist</p><p>tar -cvf myapp_1_0_0.tar -C myapp/ .</p><p>3. Create Install script</p><p>This install script will extract the myapp_1_0_0.tar into the target’s home directory. Depending on the use case, this script can be modified to fit the needs. It can be a python script, but for simplicity, it is written as the bash script.</p><pre><strong>makeself_stage/installer.sh</strong></pre><pre>This script should contains following main function </pre><pre>install_file <br><br>install_menu # to create short cut in system application menu<br>create_desktop_shortcut # desktop shortcut<br>create_uninstaller # finally uninstaller file in /usr/local/ directory</pre><pre>I am not writing all the logic for the creating menu shortcuts. Simple installation function should be like</pre><pre>function install_file() <br>{ <br>   echo &quot;Extracting the application package&quot;<br>   if [ -d $HOME/myapp] <br>   then<br>     echo &quot;Application already installed.&quot; <br>     exit 1<br>   else<br>     mkdir $HOME/myapp<br>   fi<br>   <br>   <strong>tar -xvf ./</strong><strong>myapp_1_0_0.tar.tar -C </strong><strong>$HOME/myapp</strong><br>}</pre><p>4. Run makeself by copying the archive file to the staged directory</p><p>cd ..</p><p>cp dist/myapp_1_0_0.tar makeself_stage/</p><p>makeself ./makeself_stage/ myapp_1_0_0.run &quot;sample package&quot; ./installer.sh</p><p>The syntax of makeself is the following:</p><p>makeself [args] archive_dir file_name label startup_script [script_args]</p><ul><li>archive_dir is the name of the directory that contains the files to be archived</li><li>file_name is the name of the archive to be created</li><li>label is an arbitrary text string describing the package. It will be displayed while extracting the files.</li><li>startup_script is the command to be executed <em>from within</em> the directory of extracted files.</li></ul><p>Details of each argument will be available in <a href="https://makeself.io/">https://makeself.io/</a></p><h3>Conclusion</h3><p>This solution may not be adapted to everyone but tried to be generic as possible. It allows Python developers to create and distribute a graphical application like the C++ program in Linux. The same can be achievable in Windows but needs to adapt the script based on the windows environment. You may need to use software like <a href="http://www.jrsoftware.org/isinfo.php">Inno Setup</a> instead of makeself to build an installer for windows. AI applications can be easily distributed like this by bundling pycuda packages along with the application.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a31d99f9094" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/create-standalone-linux-installer-for-your-python-ai-application-5a31d99f9094">Create Standalone Linux Installer for your Python GUI Application</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integrate LibTorch library to QT for GPU Inference]]></title>
            <link>https://medium.com/codex/integrate-libtorch-library-to-qt-for-gpu-inference-8c523d682e51?source=rss-e8e905826057------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c523d682e51</guid>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[libtorch]]></category>
            <category><![CDATA[cplusplus]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[qt]]></category>
            <dc:creator><![CDATA[Rahul Thai Valappil]]></dc:creator>
            <pubDate>Sun, 04 Jul 2021 15:16:35 GMT</pubDate>
            <atom:updated>2021-07-16T09:15:18.944Z</atom:updated>
            <content:encoded><![CDATA[<p>Qt is a powerful framework to build cross-platform GUI applications. For production deployment scenarios, you need to integrate your models developed in the PyTorch machine learning framework to your c++ QT. In order to load the PyTorch model in c++, you need to convert your model to torch script format. You can find detailed steps for how to convert Pytorch models to torch script <a href="https://pytorch.org/tutorials/advanced/cpp_export.html">here</a>.</p><h3>Download libtorch library</h3><p>Go to the PyTorch official website <a href="https://pytorch.org/">link</a> and select the appropriate libtorch version based on the OS and Cuda version installed</p><p>Windows</p><pre><a href="https://download.pytorch.org/libtorch/cu111/libtorch-win-shared-with-deps-1.8.1%2Bcu111.zip">https://download.pytorch.org/libtorch/cu111/libtorch-win-shared-with-deps-1.8.1%2Bcu111.zip</a></pre><p>Linux</p><pre>Download here (Pre-cxx11 ABI):<br><a href="https://download.pytorch.org/libtorch/cu111/libtorch-shared-with-deps-1.8.1%2Bcu111.zip">https://download.pytorch.org/libtorch/cu111/libtorch-shared-with-deps-1.8.1%2Bcu111.zip</a><br><br>Download here (cxx11 ABI):<br><a href="https://download.pytorch.org/libtorch/cu111/libtorch-cxx11-abi-shared-with-deps-1.8.1%2Bcu111.zip">https://download.pytorch.org/libtorch/cu111/libtorch-cxx11-abi-shared-with-deps-1.8.1%2Bcu111.zip</a></pre><h3>Add libtorch to the qt project</h3><p>This is the most important, but also more troublesome. Firstly, open the QT project “.pro” file and add the libtorch header file directory (include) and library file directory (lib). You need to add compiler and linking flags based on the OS platform, otherwise libtorch will not link against torch_cuda and end up with “torch::cuda::is_available()” returns 0. Libtorch recommends using CMAKE as a building tool but you can achieve the same with QMAKE for QT but should be careful with the flags.</p><pre>CONFIG += c++11<br>#Include the headers<br>INCLUDEPATH += $$PYTORCH_DIR/include/torch/csrc/api/include \<br>               $$quote($$CUDA_DIR/include)<br>#compiler and linker flags<br>unix {<br><strong>QMAKE_LFLAGS += -Wl,--no-as-needed</strong><br>}<br>win32 {<br><strong>QMAKE_LFLAGS += -INCLUDE:?warp_size@cuda@at@@YAHXZ<br>QMAKE_LFLAGS += -INCLUDE:?searchsorted_cuda@native@at@@YA?AVTensor@2@AEBV32@0_N1@Z<br>QMAKE_LFLAGS += /machine:x64</strong><br>}</pre><pre># linking with libs<br>win32 {<br>LIBS += $$quote($$PYTORCH_DIR\lib\*.lib)<br>LIBS +=  -L$$quote($$PYTORCH_DIR\lib)</pre><pre>LIBS += $$quote($$CUDA_DIR\lib\x64\*.lib)<br>LIBS += -L$$quote($$CUDA_DIR\v11.1\bin)<br>}<br>unix {<br>LIBS += -L$$PYTORCH_DIR/lib  -ltorch_cpu -ltorch  -lc10 -ltorch_cuda  -lc10_cuda -lcaffe2_observers  \<br>-lcaffe2_nvrtc -lcaffe2_detectron_ops_gpu  \<br>-lnvrtc-builtins -lprocess_group_agent -lshm  \<br>-ltensorpipe_agent -ltorch -ltorch_cuda_cpp -ltorch_cuda_cu -ltorch_global_deps</pre><pre>}</pre><h3>Build QT application with LibTorch</h3><p>The next step is to build the QT project source and you will get errors regarding the slots conflicts compilation error if your application is based on QT widgets. This is due to the conflicts of slots keyword between QT and libtorch libraries and you can avoid this by adding libtorch headers files at the start of the source code as below</p><pre>#undef slots<br>#include &quot;torch/torch.h&quot;<br>#include &quot;torch/jit.h&quot;<br>#include &quot;torch/nn.h&quot;<br>#include &quot;torch/script.h&quot;<br>#define slots Q_SLOTS</pre><pre>#include &quot;mainwindow.h&quot;<br>#include &quot;ui_mainwindow.h&quot;<br>#include &lt;QList&gt;</pre><p>Check Libtorch loaded with Cuda capability and its configuration</p><pre>qDebug() &lt;&lt; &quot;Cuda Device Count&quot; &lt;&lt; torch::cuda::device_count();</pre><pre>qDebug() &lt;&lt; &quot;cudnn_is_available&quot; &lt;&lt; torch::cuda::cudnn_is_available();</pre><pre>qDebug() &lt;&lt; &quot;cuda::is_available&quot; &lt;&lt; torch::cuda::is_available();</pre><pre>qDebug() &lt;&lt; &quot;cuda::show_config&quot; &lt;&lt; torch::show_config().c_str();</pre><p>Once the application executed you will get logs as below if there is any GPU exists</p><pre>Cuda Device Count 1<br>cudnn_is_available true<br>cuda::is_available true<br>cuda::show_config PyTorch built with:<br> - C++ Version: 199711<br>  - MSVC 192829913<br>  - Intel(R) Math Kernel Library Version 2020.0.2 Product Build 20200624 for Intel(R) 64 architecture applications<br>  - Intel(R) MKL-DNN v1.7.0 (Git Hash 7aed236906b1f7a05c0917e5257a1af05e9ff683)<br>  - OpenMP 2019<br>  - CPU capability usage: AVX2<br>  - CUDA Runtime 11.1<br>  - NVCC architecture flags: -gencode;arch=compute_37,code=sm_37;-gencode;arch=compute_50,code=sm_50;-gencode;arch=compute_60,code=sm_60;-gencode;arch=compute_61,code=sm_61;-gencode;arch=compute_70,code=sm_70;-gencode;arch=compute_75,code=sm_75;-gencode;arch=compute_80,code=sm_80;-gencode;arch=compute_86,code=sm_86;-gencode;arch=compute_37,code=compute_37<br>  - CuDNN 8.0.5<br>  - Magma 2.5.4<br>  - Build settings: BLAS_INFO=mkl, BUILD_TYPE=Release, CUDA_VERSION=11.1, CUDNN_VERSION=8.0.5, CXX_COMPILER=C:/w/b/windows/tmp_bin/sccache-cl.exe, CXX_FLAGS=/DWIN32 /D_WINDOWS /GR /EHsc /w /bigobj -DUSE_PTHREADPOOL -openmp:experimental -DNDEBUG -DUSE_FBGEMM -DUSE_XNNPACK, LAPACK_INFO=mkl, PERF_WITH_AVX=1, PERF_WITH_AVX2=1, PERF_WITH_AVX512=1, TORCH_VERSION=1.8.1, USE_CUDA=ON, USE_CUDNN=ON, USE_EXCEPTION_PTR=1, USE_GFLAGS=OFF, USE_GLOG=OFF, USE_MKL=ON, USE_MKLDNN=ON, USE_MPI=OFF, USE_NCCL=OFF, USE_NNPACK=OFF, USE_OPENMP=ON,</pre><p>Note: Needs to build the QT application with MSVC as libtorch does not support MinGW on windows.</p><h3>Load the torchscript model and run the Inference</h3><p>Load the torch script model in the lib torch module</p><pre>torch::jit::script::Module aLibTorchModule = torch::jit::load(&quot;torch script model path&quot;);</pre><p>Select GPU device if it is available and otherwise choose CPU device</p><pre>torch::DeviceType aDeviceType;<br>if (torch::cuda::is_available())<br>{<br>aDeviceType= torch::kCUDA;<br>}<br>else <br>{<br>aDeviceType= torch::kCPU;<br>}<br>torch::Device aTorchDevice = torch::Device(aDeviceType);</pre><p>Move the loaded module to the selected device, in our case it is GPU</p><pre>aLibTorchModule.to(aTorchDevice);</pre><p>You can now execute the inference in the libtorch module bypassing proper input to the model. Lib torch provides a function for converting to input tensor if you have an open cv::Mat image object.</p><pre>auto input_tensor = torch::from_blob(</pre><pre><em>data</em>, {1, Height, Width, 3}); // here data should opencv CV::MAT</pre><p>Sometimes you may need to preprocess the input based on the model expectation and following the lib torch function allows you to change the order of the input tenor dimension and normalize the input before proceeding with the actual inference.</p><pre>input_tensor = input_tensor.permute({0, 3, 1, 2});<br>std::vector&lt;double&gt; norm_mean = {0.485, 0.456, 0.406};<br>std::vector&lt;double&gt; norm_std = {0.229, 0.224, 0.225};<br>input_tensor = torch::data::transforms::Normalize&lt;&gt;(norm_mean, norm_std)(input_tensor);</pre><p>Finally, execute the inference in the libtorch module where the model is loaded at the start. Libtorch Forward method returns the results as tensor objects and you can retrieve the results and manipulate the results based on your needs. Make sure that you should move your input tensor to GPU before processing the inference if your model is loaded in GPU, otherwise you will get an error.</p><pre>input_tensor = input_tensor.to(aTorchDevice);<br>torch::Tensor out_tensor = aLibTorchModule.forward({input_tensor}).toTensor();</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c523d682e51" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/integrate-libtorch-library-to-qt-for-gpu-inference-8c523d682e51">Integrate LibTorch library to QT for GPU Inference</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sending SMS and Email using AWS C++]]></title>
            <link>https://rahulthaivalappil.medium.com/sending-sms-and-email-using-aws-c-c85819d74c4c?source=rss-e8e905826057------2</link>
            <guid isPermaLink="false">https://medium.com/p/c85819d74c4c</guid>
            <category><![CDATA[cplusplus]]></category>
            <category><![CDATA[aws-sns]]></category>
            <category><![CDATA[qt]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Rahul Thai Valappil]]></dc:creator>
            <pubDate>Fri, 09 Apr 2021 15:45:19 GMT</pubDate>
            <atom:updated>2021-07-16T08:22:32.909Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/272/0*whPlFKsbtHDSj01E" /></figure><p>This is a continuation of my previous <a href="https://rahulthaivalappil.medium.com/sms-and-email-sending-in-python-using-aws-a81df27fc210">article</a>, where I have used AWS python SDK for sending SMS and email. To set up the AWS SDK for C++, you can either build the SDK yourself directly from the source or download the libraries using a package manager.</p><h4>Building the SDK from Source in Linux</h4><ol><li>Download the source code for the version you want.</li></ol><pre>git clone https://github.com/aws/aws-sdk-cpp.git</pre><p>2. Go to the AWS-SDK folder and create a build folder</p><pre>mkdir sdk_build</pre><p>3. Navigate to the newly created build folder. Generate the build files by running CMake</p><pre>cmake ../aws-sdk-cpp -DCMAKE_BUILD_TYPE=Release -DBUILD_ONLY=&quot;core;email;sns;sesv2&quot; -DCMAKE_INSTALL_PREFIX=&quot;/install/path&quot;</pre><p>You can specify the CMake command to build in debug or release. Building the entire SDK is time-consuming, so you can customize the build by using the DBUILD_ONLY of CMake. This allows building only needed modules. In our case, we only needed SES and SNS modules. In addition, we included AWS core and email modules for authentication and building the email message.</p><p>4. Build the SDK binaries</p><pre>make</pre><p>5. Install the SDK</p><p>I have provided a custom install path to CMake (DCMAKE_INSTALL_PREFIX = ” / install /path&quot;) since I do not want to install the library to the system path</p><pre>make install</pre><h4>Configure AWS SDK in QT C++ application</h4><p>You need to configure AWS SDK ‘include’ and ‘library’ paths in your application build system like CMake or QMake. I will explain with QMake as my project is a QT application. You can check here for <a href="https://docs.aws.amazon.com/code-samples/latest/catalog/cpp-ses-CMakeLists.txt.html">CMake</a>. Add the following line to the .pro file of your QT project</p><pre>unix: LIBS += -L/path_to_aws_sdk_lib/lib/ -laws-c-common</pre><pre>unix: LIBS += -L/path_to_aws_sdk_lib/lib/ -laws-cpp-sdk-core</pre><pre>unix: LIBS += -L/path_to_aws_sdk_lib/lib/ -laws-c-event-stream</pre><pre>unix: LIBS += -L/path_to_aws_sdk_lib/lib/ -laws-cpp-sdk-email</pre><pre>unix: LIBS += -L/path_to_aws_sdk_lib/lib/ -laws-cpp-sdk-sesv2</pre><pre>unix: LIBS += -L/path_to_aws_sdk_lib/lib/ -laws-cpp-sdk-sns</pre><pre>INCLUDEPATH += /path_to_aws_sdk_lib/include</pre><pre>DEPENDPATH += /path_to_aws_sdk_lib/include</pre><h4>Code for Sending SMS</h4><pre>#include &lt;aws/core/Aws.h&gt;<br>#include &lt;aws/core/auth/AWSCredentials.h&gt;<br>#include &lt;aws/sns/SNSClient.h&gt;<br>#include &lt;aws/sns/model/PublishRequest.h&gt;<br>#include &lt;aws/sns/model/PublishResult.h&gt;</pre><pre>int main(int argc, char *argv[])<br>{<br>QCoreApplication a(<em>argc</em>, argv);<br>Aws::SDKOptions options;<br>Aws::InitAPI(options);<br>{<br>const Aws::Auth::AWSCredentials aAwsSesCred(&quot;awskeyid&quot;, &quot;aws scretkey&quot;);<br>Aws::Client::ClientConfiguration aAwsClientConf;<br>aAwsClientConf.region = &quot;eu-west-3&quot;;<br>Aws::SNS::SNSClient sns(aAwsSesCred, aAwsClientConf);<br>Aws::String message = &quot;XXXXXXXXXXXX&quot;;<br>Aws::String phone_number = &quot;+XXXXX&quot;;<br>Aws::SNS::Model::PublishRequest psms_req;<br>psms_req.SetMessage(message);<br>psms_req.SetPhoneNumber(phone_number);<br>auto psms_out = sns.Publish(psms_req);<br>if (psms_out.IsSuccess())<br>{<br>std::cout &lt;&lt; &quot;Message published successfully &quot; &lt;&lt; psms_out.GetResult().GetMessageId()&lt;&lt; std::endl;<br>}<br>else<br>{<br>std::cout &lt;&lt; &quot;Error while publishing message &quot; &lt;&lt; psms_out.GetError().GetMessage()&lt;&lt; std::endl;<br>}<br>}<br>Aws::ShutdownAPI(options);<br>return a.exec();<br>}</pre><h4>Code for Sending Email</h4><pre>#include &lt;aws/core/Aws.h&gt;<br>#include &lt;aws/core/auth/AWSCredentials.h&gt;<br>#include &lt;aws/email/SESClient.h&gt;<br>#include &lt;aws/email/model/SendEmailRequest.h&gt;<br>#include &lt;aws/email/model/SendEmailResult.h&gt;<br>#include &lt;aws/email/model/Destination.h&gt;<br>#include &lt;aws/email/model/Message.h&gt;<br>#include &lt;aws/email/model/Body.h&gt;<br>#include &lt;aws/email/model/Content.h&gt;<br>#include &lt;aws/sns/SNSClient.h&gt;<br>#include &lt;aws/sns/model/PublishRequest.h&gt;<br>#include &lt;aws/sns/model/PublishResult.h&gt;</pre><pre>int main(int argc, char *argv[])<br>{<br>QCoreApplication a(<em>argc</em>, argv);<br>Aws::SDKOptions options;<br>Aws::InitAPI(options);<br>{</pre><pre>Aws::String message_body_html_data(&quot;Test html Email&quot;);<br>Aws::String message_body_text_data(&quot;Test text Email&quot;);<br>Aws::String message_subject_data(&quot;Test&quot;);<br>Aws::String sender_email_address(&quot;sender_email_address&quot;);<br>Aws::String cc_address(&quot;cc_email_address&quot;);<br>Aws::String reply_to_address(&quot;to_email_address&quot;);</pre><pre>const Aws::Auth::AWSCredentials aAwsSesCred(&quot;awskeyid&quot;, &quot;awssecretkey&quot;);<br>Aws::Client::ClientConfiguration aAwsClientConf;<br>aAwsClientConf.region = &quot;eu-west-3&quot;;<br>Aws::SES::SESClient ses(aAwsSesCred, aAwsClientConf);</pre><pre>Aws::SES::Model::SendEmailRequest se_req;<br>Aws::SES::Model::Destination destination;<br>Aws::SES::Model::Message message;<br>Aws::SES::Model::Body message_body;<br>Aws::SES::Model::Content message_body_text;<br>Aws::SES::Model::Content message_body_html;<br>Aws::SES::Model::Content message_subject;</pre><pre>destination.AddCcAddresses(cc_address);<br>destination.AddToAddresses(reply_to_address);<br>message_body_html.SetData(message_body_html_data);<br>message_body_html.SetCharset(&quot;UTF-8&quot;);<br>message_body_text.SetData(message_body_text_data);<br>message_body_text.SetCharset(&quot;UTF-8&quot;);<br>message_subject.SetData(message_subject_data);<br>message_subject.SetCharset(&quot;UTF-8&quot;);<br>message_body.SetText(message_body_text);<br>message_body.SetHtml(message_body_html);<br>message.SetBody(message_body);<br>message.SetSubject(message_subject);</pre><pre>se_req.SetDestination(destination);<br>se_req.SetMessage(message);<br>se_req.SetSource(sender_email_address);<br>se_req.AddReplyToAddresses(reply_to_address);</pre><pre>auto se_out = ses.SendEmail(se_req);<br>if (se_out.IsSuccess())<br>{<br>std::cout &lt;&lt; &quot;Successfully sent GetMessage &quot; &lt;&lt; se_out.GetResult().GetMessageId()&lt;&lt; std::endl;<br>}<br>else<br>{<br>std::cout &lt;&lt; &quot;Error creating receipt filter &quot; &lt;&lt; se_out.GetError().GetMessage()&lt;&lt; std::endl;<br>}<br>}</pre><pre>Aws::ShutdownAPI(options);<br>return a.exec();<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c85819d74c4c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SMS and Email sending in python Using AWS]]></title>
            <link>https://medium.com/codex/sms-and-email-sending-in-python-using-aws-a81df27fc210?source=rss-e8e905826057------2</link>
            <guid isPermaLink="false">https://medium.com/p/a81df27fc210</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[email]]></category>
            <category><![CDATA[sms]]></category>
            <category><![CDATA[aws-sns]]></category>
            <dc:creator><![CDATA[Rahul Thai Valappil]]></dc:creator>
            <pubDate>Tue, 16 Mar 2021 11:07:35 GMT</pubDate>
            <atom:updated>2021-07-16T08:58:47.913Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7ehEa3P2h6sZtGIW.jpg" /></figure><p>Sometimes you want to send SMS and email as a consequence of the trigger of an action or event from your python application. In the normal case, we can send emails using a Gmail account with the python <a href="https://docs.python.org/3/library/smtplib.html">smtplib</a> module but it has a limitation of sending emails per day. There are many services out there that will let you programmatically send SMS and Emails. One of the more popular is <a href="https://www.twilio.com/">Twilio</a>, and they have a great API and a python client that’s easy to use.</p><p>Another option is to use Amazon’s <a href="https://aws.amazon.com/sns/">Simple Notification Service</a> (SNS) and <a href="http://aws.amazon.com/ses/">Simple Email Service</a>(SES) for sending SMS and EMail respectively. You can also use SNS for sending email but the way SNS works resembles mailing groups that you subscribe to in order to receive the contents which are relevant to the users.</p><h4>Prerequisites</h4><p>The first and foremost requirement is an AWS account and a verified email address for sending emails. Also Download the AWS access key and secret key from the amazon account in order to authenticate the transactions.</p><p>The second part of this is <a href="https://aws.amazon.com/sdk-for-python/">boto3</a>, amazon’s python SDK, which helps to integrate your Python application, library, or script with AWS services including Amazon S3, Amazon EC2, Amazon DynamoDB, and more.</p><pre>pip install boto3</pre><p><strong>Send SMS</strong></p><pre>import boto3<br># Create an SNS client<br>client = boto3.client(<br>    &quot;sns&quot;,<br>    aws_access_key_id=&quot;YOUR ACCES KEY&quot;,<br>    aws_secret_access_key=&quot;YOUR SECRET KEY&quot;,<br>    region_name=&quot;us-east-1&quot;<br>)<br># Send your sms message.<br>client.publish(<br>    PhoneNumber=&quot;+12223334444&quot;,<br>    Message=&quot;Hello World!&quot;<br>)</pre><p><strong>Send Email</strong></p><pre>email_ses_client = boto3.client(<br>            &quot;ses&quot;,<br>            aws_access_key_id=&quot;YOUR ACCES KEY&quot;,<br>            aws_secret_access_key=&quot;YOUR SECRET KEY&quot;,<br>           region_name=&quot;us-east-1&quot;<br>           )<br># The email body for recipients with non-HTML email clients.<br>email_body_text = &quot;email body text here&quot;</pre><pre># The HTML body of the email.<br>email_body_html = &quot;email html contents&quot;<br>            </pre><pre># The character encoding for the email.<br>email_charset = &quot;UTF-8&quot;<br>email_msg = MIMEMultipart(&#39;mixed&#39;)<br># Add subject, from and to lines.<br>email_msg[&#39;Subject&#39;] = &quot;subject&quot;<br>email_msg[&#39;From&#39;] = &quot;AWS verified sender email id&quot;<br>email_msg[&#39;To&#39;] = &#39;, &#39;.join(email to list)<br>email_msg[&#39;Cc&#39;] = &#39;, &#39;.join(email Cc list)<br>email_msg[&#39;Bcc&#39;] = &#39;, &#39;.join(email bcc list)</pre><pre>email_msg_body = MIMEMultipart(&#39;alternative&#39;)<br>textpart = MIMEText(email_body_text.encode(email_charset), &#39;plain&#39;, email_charset)<br>htmlpart = MIMEText(email_body_html.encode(email_charset), &#39;html&#39;, email_charset)<br># Add the text and HTML parts to the child container.<br>email_msg_body.attach(textpart)<br>email_msg_body.attach(htmlpart)</pre><pre># Attach the multipart/alternative child container to the multipart/mixed<br># parent container.<br>email_msg.attach(email_msg_body)</pre><pre>if not os.path.exists(Attachment file):<br>     print(&quot;Attachment file does not exists&quot;)<br> else:<br>     # Define the attachment part and encode it using<br>     MIMEApplication.email_attachment = IMEApplication(open(Attachment file path, &#39;rb&#39;).read())   <br>     file_name = Path(Attachment file path).name<br>                email_attachment.add_header(&#39;Content-Disposition&#39;,          &#39;attachment&#39;, filename=file_name)<br>     # Add the attachment to the parent container.<br>     email_msg.attach(email_attachment)</pre><pre>try:<br>    # Provide the contents of the email.<br>    response = email_ses_client.send_raw_email(<br>                    Source=email_msg[&#39;From&#39;],<br>                    Destinations= email to list + emaom cc list + email bcc list,<br>                    RawMessage={<br>                        &#39;Data&#39;: email_msg.as_string(),<br>                    }<br>                )<br>            # Display an error if something goes wrong.<br>            except ClientError as e:<br>                print(e.response[&#39;Error&#39;][&#39;Message&#39;])<br>            except EndpointConnectionError as exp:<br>                print(exp)<br>            except ConnectionError as exp:<br>                print(exp)<br>            except:<br>                print(&quot;Unknown Exception(AWS SES) while sending Email&quot;)<br>            else:<br>                print(response[&#39;MessageId&#39;])</pre><p>You need to move the AWS SES account out of the sandbox in order to send emails without verifying. All new AWS SES accounts first comes under a test environment (sandbox) so you can only send emails <strong>to</strong> verified email addresses and domains and can send a maximum of 200 messages in a 24 hour period.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a81df27fc210" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/sms-and-email-sending-in-python-using-aws-a81df27fc210">SMS and Email sending in python Using AWS</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>