<?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 Shahbaz Gondal on Medium]]></title>
        <description><![CDATA[Stories by Shahbaz Gondal on Medium]]></description>
        <link>https://medium.com/@shahbaz.gondal588?source=rss-8f76f4132ebc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*c9mWrRA0zG7TTQfjwd8bTg.png</url>
            <title>Stories by Shahbaz Gondal on Medium</title>
            <link>https://medium.com/@shahbaz.gondal588?source=rss-8f76f4132ebc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 17:52:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shahbaz.gondal588/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[How to Publish an App on the Play Store If Your Account Was Created After November 2023]]></title>
            <link>https://medium.com/@shahbaz.gondal588/how-to-publish-an-app-on-the-play-store-if-your-account-was-created-after-november-2023-0a2c954ad8d2?source=rss-8f76f4132ebc------2</link>
            <guid isPermaLink="false">https://medium.com/p/0a2c954ad8d2</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[play-store]]></category>
            <category><![CDATA[close-testing]]></category>
            <dc:creator><![CDATA[Shahbaz Gondal]]></dc:creator>
            <pubDate>Thu, 20 Feb 2025 09:13:35 GMT</pubDate>
            <atom:updated>2025-02-20T09:13:35.613Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*twRwLz3-vjjNhusjDSU07w.png" /></figure><p>Publishing an application on the Google Play Store has undergone some changes for developers who created their accounts after November 2023. Google has introduced additional verification steps and policy updates to enhance security and app quality. In this article, we will walk you through publishing an app under the new guidelines.</p><h3>1. Setting Up Your Developer Account</h3><p>Before publishing an app, you must have a Google Play Developer account. If you created your account after November 2023, you need to:</p><ul><li>Pay a <strong>one-time registration fee</strong> of $25.</li><li>Complete the <strong>identity verification</strong> process using a government-issued ID.</li><li>Provide <strong>business details</strong> (if applicable).</li><li>Ensure your <strong>developer name and email address</strong> are accurate, as they will be publicly displayed.</li><li>The <strong>payment profile</strong> used for Play Console payments should have the exact information as your identity card or passport.</li><li>Before creating the account, make sure your <strong>privacy policy page</strong> is live.</li></ul><h3>2. App Content and Compliance Requirements</h3><p>To comply with Google Play’s policies, make sure your app meets the following requirements:</p><ul><li><strong>Data Safety Section:</strong> Disclose how your app collects and handles user data.</li><li><strong>Target API Level:</strong> Your app must target the latest Android API levels as per Google’s deadlines.</li><li><strong>App Permissions:</strong> Request only the necessary permissions for app functionality.</li><li><strong>Content Rating:</strong> Complete the content rating questionnaire to ensure appropriate audience targeting.</li><li><strong>Store Listing:</strong> Provide a detailed app description, screenshots, and a feature graphic.</li><li><strong>Package Name:</strong> Should not be <strong>com.example.</strong> or any placeholder name.</li><li><strong>Button Text:</strong> Avoid naming any button <strong>‘Test’</strong> in your app.</li><li><strong>Under Construction Features:</strong> Clearly indicate or disable any under-construction features.</li><li><strong>App Versioning:</strong> Each version should have an updated app version number.</li></ul><h3>3. Signing Your AAB File</h3><p>Before uploading your app, you need to sign your <strong>Android App Bundle (AAB)</strong> to ensure its authenticity. Follow these steps:</p><ol><li><strong>Generate a Keystore File:</strong> If you don’t have one, create a keystore file using Android Studio or the command line.</li><li><strong>Sign Your AAB:</strong> Use the following Gradle command:</li></ol><ul><li>./gradlew bundleRelease --keystore &lt;keystore-path&gt; --storePassword &lt;password&gt; --keyAlias &lt;alias&gt; --keyPassword &lt;password&gt;</li><li><strong>Enroll in Play App Signing:</strong> Google Play now requires developers to opt into Play App Signing, which securely manages and signs your app releases.</li><li><strong>Upload the Signed AAB:</strong> Once signed, upload the AAB file to the Play Console.</li></ul><h3>4. Developer Verification and App Review Process</h3><p>After November 2023, Google has <strong>enhanced the review process</strong> to prevent policy violations and malware distribution. The steps include:</p><ul><li><strong>Mandatory Testing Period:</strong> New developers may experience a <strong>waiting period</strong> before their first app is approved.</li><li><strong>Live-Operations Verification:</strong> Google may require a live demo or video demonstration of the app’s core functionality.</li><li><strong>Policy Compliance Review:</strong> Ensure that your app follows Google’s Developer Program Policies.</li><li>Before publishing, your app <strong>goes into review</strong> during the <strong>Closed Testing</strong> phase, which may take up to <strong>4–5 days</strong>.</li><li><strong>Closed Testing Requirements:</strong> Testing must be completed within <strong>12 days with at least 14 testers</strong>.</li><li>The tester should use the application for 12 days daily, otherwise, google will not provide production access.</li><li><strong>No Paid Services in Closed Testing:</strong> Google may flag your account if paid services are used during closed testing.</li></ul><h3>5. Uploading Your App to Google Play Console</h3><p>Once your app is ready, follow these steps:</p><ol><li>Sign in to <strong>Google Play Console</strong>.</li><li>Click <strong>Create App</strong> and provide the required details (app name, language, and category).</li><li>Complete the <strong>Store Listing</strong> (title, description, screenshots, and videos).</li><li>Configure the <strong>App Content</strong> section to comply with policy requirements.</li><li>Upload your <strong>APK/AAB file</strong> (Android App Bundle is recommended for better optimization).</li><li>Set up <strong>Pricing &amp; Distribution</strong> (free or paid app, and target countries).</li><li>Submit your app for <strong>review and approval</strong>.</li></ol><h3>6. Handling App Review Feedback and Approval</h3><p>Once submitted, Google will review your app. The review process can take <strong>a few hours to several days</strong>. If your app is rejected:</p><ul><li><strong>Check the policy violation message</strong> and fix the issue.</li><li><strong>Revise and resubmit your app</strong> after making necessary changes.</li><li><strong>Use Google Play Console’s appeal option</strong> if you believe the rejection was incorrect.</li><li><strong>Fix any errors before re-submitting</strong>, as Play Console provides issues that must be resolved first.</li><li>Ensure that if your app uses <strong>third-party APIs</strong>, you have permission to use them in <strong>release mode</strong>, not just debug mode.</li></ul><h3>7. Post-Launch Best Practices</h3><p>After your app is live, ensure its success with these best practices:</p><ul><li><strong>Monitor User Feedback:</strong> Respond to reviews and improve user experience.</li><li><strong>Regular Updates:</strong> Keep your app updated to maintain compliance with Google’s policies.</li><li><strong>Performance Monitoring:</strong> Use Google Play Console analytics to track performance and crashes.</li><li><strong>Marketing and ASO:</strong> Optimize your app store listing to improve visibility and downloads.</li></ul><h3>Conclusion</h3><p>Publishing an app on the Google Play Store after November 2023 requires <strong>enhanced verification, stricter policy compliance, and a more detailed review process</strong>. By following the steps outlined above, you can ensure a smooth publishing experience and avoid unnecessary rejections. Stay updated with Google’s policies to maintain a successful app on the Play Store.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0a2c954ad8d2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Stripe Payment Gateway with Google Cloud Run and Flutter]]></title>
            <link>https://medium.com/@shahbaz.gondal588/building-a-stripe-payment-gateway-with-google-cloud-run-and-flutter-aff0f74a730e?source=rss-8f76f4132ebc------2</link>
            <guid isPermaLink="false">https://medium.com/p/aff0f74a730e</guid>
            <category><![CDATA[stripe]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[firebase]]></category>
            <dc:creator><![CDATA[Shahbaz Gondal]]></dc:creator>
            <pubDate>Wed, 27 Nov 2024 07:44:07 GMT</pubDate>
            <atom:updated>2024-11-27T07:44:07.942Z</atom:updated>
            <content:encoded><![CDATA[<p>Integrating Stripe for seamless payment processing is essential for modern applications. In this tutorial, we’ll guide you through integrating Stripe’s payment gateway using <strong>Google Cloud Run</strong> as a backend and a <strong>Flutter</strong> application for client-side implementation.</p><p><strong>Requirement:</strong></p><p><strong><em>Stripe secret and publishing key, Blaze Plane for Firebase</em></strong></p><p><strong><em>We can not implement the Stripe payment gateway only with Flutter code, server-side implementation is required</em></strong></p><h3>Step 1: Setting Up the Backend with Google Cloud Run</h3><p>We’ll use Python, Flask, and the Firebase Admin SDK to process payments. The backend generates a <strong>Stripe Payment Intent</strong> and returns the client_secret to the client for finalizing the payment.</p><h4>Backend Code:</h4><pre>import stripe<br>import firebase_admin<br>from firebase_admin import firestore, credentials<br>from flask import jsonify, request</pre><pre># Initialize Firebase Admin SDK<br>cred = credentials.ApplicationDefault()<br>firebase_admin.initialize_app(cred)</pre><pre># Initialize Firestore<br>db = firestore.client()</pre><pre># Set your Stripe secret key<br>stripe.api_key = &#39;sk_live_XXXXXX&#39;  # Replace with your Stripe Secret Key</pre><pre># Google Cloud Function entry point<br>def process_payment(request):<br>    if request.method != &#39;POST&#39;:<br>        return jsonify({&#39;error&#39;: &#39;Invalid method. Only POST requests are accepted.&#39;}), 405<br>    <br>    try:<br>        # Extract parameters from the request<br>        data = request.get_json()<br>        order_id = data.get(&quot;orderId&quot;)<br>        price_in_aed = data.get(&quot;priceInAED&quot;)<br>        uid = data.get(&quot;uid&quot;)</pre><pre>        # Validate input data<br>        if not order_id or not price_in_aed or not uid:<br>            return jsonify({&#39;error&#39;: &#39;Missing required parameters&#39;}), 400</pre><pre>        # Create a Stripe Payment Intent<br>        payment_intent = stripe.PaymentIntent.create(<br>            amount=int(price_in_aed * 100),  # Convert AED to cents<br>            currency=&quot;aed&quot;,<br>            metadata={<br>                &quot;orderId&quot;: order_id,<br>                &quot;uid&quot;: uid<br>            }<br>        )</pre><pre>        # Return the client secret<br>        return jsonify({&quot;client_secret&quot;: payment_intent.client_secret})<br>    <br>    except Exception as e:<br>        return jsonify({&#39;error&#39;: str(e)}), 500</pre><h3>Step 2: Flutter Client Integration</h3><p>The Flutter app communicates with the backend to fetch the client_secret and completes the payment using Stripe&#39;s SDK.</p><h4>Flutter Code:</h4><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:stripe_sdk/stripe_sdk.dart&#39;;<br>import &#39;package:http/http.dart&#39; as http;<br>import &#39;dart:convert&#39;;</pre><pre>class PerformPayment extends StatefulWidget {<br>  final String orderId;<br>  final String userId;<br>  final double totalPrice;</pre><pre>  PerformPayment({<br>    required this.orderId,<br>    required this.userId,<br>    required this.totalPrice,<br>  });</pre><pre>  @override<br>  _PerformPaymentState createState() =&gt; _PerformPaymentState();<br>}</pre><pre>class _PerformPaymentState extends State&lt;PerformPayment&gt; {<br>  bool _isLoading = false;<br>  String? _clientSecret;<br>  late final Stripe _stripe;</pre><pre>  @override<br>  void initState() {<br>    super.initState();<br>    _stripe = Stripe(&#39;pk_live_XXXXXX&#39;); // Replace with your Stripe Publishable Key<br>    _initiatePayment();<br>  }</pre><pre>  Future&lt;void&gt; _initiatePayment() async {<br>    setState(() {<br>      _isLoading = true;<br>    });</pre><pre>    try {<br>      final String url =<br>          &#39;https://YOUR_CLOUD_RUN_URL/process-payment&#39;; // Replace with your Cloud Run URL<br>      final Map&lt;String, dynamic&gt; paymentData = {<br>        &#39;orderId&#39;: widget.orderId,<br>        &#39;priceInAED&#39;: widget.totalPrice,<br>        &#39;uid&#39;: widget.userId,<br>      };</pre><pre>      final response = await http.post(<br>        Uri.parse(url),<br>        headers: {&#39;Content-Type&#39;: &#39;application/json&#39;},<br>        body: json.encode(paymentData),<br>      );</pre><pre>      if (response.statusCode == 200) {<br>        final responseData = json.decode(response.body);<br>        _clientSecret = responseData[&#39;client_secret&#39;];<br>        if (_clientSecret == null) throw Exception(&#39;Failed to retrieve client secret&#39;);<br>      } else {<br>        throw Exception(&#39;Payment initiation failed: ${response.body}&#39;);<br>      }<br>    } catch (e) {<br>      print(&#39;Payment initiation failed: $e&#39;);<br>    } finally {<br>      setState(() {<br>        _isLoading = false;<br>      });<br>    }<br>  }</pre><pre>  Future&lt;void&gt; _processPayment() async {<br>    if (_clientSecret == null) return;</pre><pre>    try {<br>      setState(() {<br>        _isLoading = true;<br>      });</pre><pre>      final paymentMethod = await _stripe.api.createPaymentMethod({<br>        &#39;type&#39;: &#39;card&#39;,<br>        &#39;card&#39;: {<br>          &#39;number&#39;: &#39;4242424242424242&#39;,<br>          &#39;exp_month&#39;: 12,<br>          &#39;exp_year&#39;: 2024,<br>          &#39;cvc&#39;: &#39;123&#39;,<br>        },<br>      });//use your actual card here</pre><pre>      await _stripe.api.confirmPaymentIntent(<br>        _clientSecret!,<br>        data: {&#39;payment_method&#39;: paymentMethod[&#39;id&#39;]},<br>      );</pre><pre>      ScaffoldMessenger.of(context).showSnackBar(<br>        SnackBar(content: Text(&#39;Payment successful!&#39;)),<br>      );<br>    } catch (e) {<br>      ScaffoldMessenger.of(context).showSnackBar(<br>        SnackBar(content: Text(&#39;Payment failed: $e&#39;)),<br>      );<br>    } finally {<br>      setState(() {<br>        _isLoading = false;<br>      });<br>    }<br>  }</pre><pre>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(title: Text(&#39;Complete Payment&#39;)),<br>      body: _isLoading<br>          ? Center(child: CircularProgressIndicator())<br>          : ElevatedButton(<br>              onPressed: _processPayment,<br>              child: Text(&#39;Pay Now&#39;),<br>            ),<br>    );<br>  }<br>}</pre><h3>Deployment</h3><ol><li><strong>Deploy Backend</strong>: Use the Google Cloud SDK to deploy the Python script to <strong>Google Cloud Run</strong>.</li></ol><pre>gcloud run deploy --source </pre><p><strong>Flutter Setup</strong>:</p><ul><li>Add the <strong>Stripe SDK</strong> to your pubspec.yaml:</li></ul><pre>dependencies:   stripe_sdk: ^3.0.0</pre><ul><li>Ensure your app communicates with the backend and completes payments.</li></ul><h3>Conclusion</h3><p>With this setup, you now have a working Stripe payment gateway powered by <strong>Google Cloud Run</strong> and a Flutter app. You can customize this implementation for various use cases, such as subscriptions, donations, or e-commerce. This integration ensures secure and scalable payment processing.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aff0f74a730e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Simple Retrieval-Augmented Generation (RAG) System with LangChain and OpenAI]]></title>
            <link>https://medium.com/@shahbaz.gondal588/building-a-simple-retrieval-augmented-generation-rag-system-with-langchain-and-openai-83bcdd073dfb?source=rss-8f76f4132ebc------2</link>
            <guid isPermaLink="false">https://medium.com/p/83bcdd073dfb</guid>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Shahbaz Gondal]]></dc:creator>
            <pubDate>Thu, 18 Jul 2024 11:16:47 GMT</pubDate>
            <atom:updated>2024-07-18T11:16:47.332Z</atom:updated>
            <content:encoded><![CDATA[<p>In the world of natural language processing, combining the power of retrieval-based and generative models can significantly enhance the quality of responses. This tutorial will guide you through building a simple Retrieval-Augmented Generation (RAG) system using LangChain and OpenAI. We’ll break down the process into clear steps, separating configuration from the main code for better maintainability and security.</p><h3>Prerequisites</h3><p>Ensure you have the following installed:</p><ul><li>Python 3.6 or later</li><li>Required Python libraries (faiss, numpy, langchain-openai, and langchain-community)</li></ul><p>Install the required libraries using:</p><pre>pip install faiss-cpu numpy langchain-openai langchain-community</pre><h3>Step 1: Setting Up the Configuration</h3><p>First, let’s create a configuration file to store the OpenAI API key.</p><h3>Create config.py</h3><p>This file will hold your OpenAI API key.</p><pre># config.py<br><br>OPENAI_API_KEY = &quot;your_openai_api_key&quot;</pre><p>Replace &quot;your_openai_api_key&quot; with your actual OpenAI API key.</p><h3>Step 2: Building the RAG System</h3><p>Now, let’s create the main script that will implement the RAG system.</p><h3>Create rag.py</h3><p>This script will perform the following tasks:</p><ol><li>Import necessary libraries and the API key from config.py.</li><li>Initialize the embeddings model.</li><li>Define example documents.</li><li>Convert documents to embeddings and add them to a FAISS index.</li><li>Implement a simple retriever class.</li><li>Implement the RAG class combining retrieval and generation.</li><li>Run an example query.</li></ol><pre>import os<br>import faiss<br>import numpy as np<br>from langchain_openai import OpenAIEmbeddings, OpenAI<br>from langchain_community.vectorstores import FAISS<br>import config  # Importing the config file<br><br># Set your OpenAI API key<br>os.environ[&quot;OPENAI_API_KEY&quot;] = config.OPENAI_API_KEY<br><br># Initialize the embeddings model<br>embeddings = OpenAIEmbeddings(openai_api_key=os.environ[&quot;OPENAI_API_KEY&quot;])<br><br># Example documents <br># Provide any information in the form of text on which you want to train<br>documents = [ <br>    &quot;shahbaz is from faisalabad, he is graduated from FAST university&quot;,<br>]<br><br># Convert documents to embeddings<br>document_embeddings = embeddings.embed_documents(documents)<br>document_embeddings = np.array(document_embeddings).astype(&#39;float32&#39;)<br><br># Initialize FAISS index and add document embeddings<br>dimension = document_embeddings.shape[1]<br>index = faiss.IndexFlatL2(dimension)<br>index.add(document_embeddings)<br><br># Define a retriever class<br>class SimpleRetriever:<br>    def __init__(self, index, documents):<br>        self.index = index<br>        self.documents = documents<br><br>    def retrieve(self, query, top_k=1):<br>        query_embedding = np.array([embeddings.embed_query(query)]).astype(&#39;float32&#39;)<br>        _, indices = self.index.search(query_embedding, top_k)<br>        return [self.documents[i] for i in indices[0]]<br><br>retriever = SimpleRetriever(index, documents)<br><br># Combine the retriever with the generator<br>class SimpleRAG:<br>    def __init__(self, llm, retriever):<br>        self.llm = llm<br>        self.retriever = retriever<br><br>    def generate(self, query):<br>        retrieved_docs = self.retriever.retrieve(query)<br>        augmented_query = f&quot;Context: {&#39; &#39;.join(retrieved_docs)} Query: {query}&quot;<br>        response = self.llm.invoke(augmented_query)<br>        return response<br><br>llm = OpenAI(api_key=os.environ[&quot;OPENAI_API_KEY&quot;])<br>rag = SimpleRAG(llm, retriever)<br><br># Example usage<br>query = &quot;who is shahbaz?&quot;<br>response = rag.generate(query)<br>print(response)</pre><h3>Explanation</h3><p><strong>Imports and Configuration</strong>:</p><ul><li>Import necessary libraries and the config module to access the API key.</li><li>Set the OpenAI API key from the config.py file.</li></ul><p><strong>Initialize Embeddings Model</strong>:</p><ul><li>Create an instance of OpenAIEmbeddings to convert text into embeddings.</li></ul><p><strong>Define Example Documents</strong>:</p><ul><li>List example documents to be used for retrieval.</li></ul><p><strong>Convert Documents to Embeddings</strong>:</p><ul><li>Convert the documents into embeddings and prepare them for indexing.</li></ul><p><strong>Initialize FAISS Index</strong>:</p><ul><li>Set up a FAISS index to facilitate efficient similarity search.</li></ul><p><strong>Implement Retriever Class</strong>:</p><ul><li>Define a class to handle retrieval of relevant documents based on query embeddings.</li></ul><p><strong>Implement RAG Class</strong>:</p><ul><li>Combine the retriever and a language model (LLM) to generate context-aware responses.</li></ul><p><strong>Example Usage</strong>:</p><ul><li>Demonstrate the functionality by querying the system and printing the response.</li></ul><h3>Running the Code</h3><p>With both config.py and rag.py in the same directory, you can run the script using:</p><pre>python rag.py</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83bcdd073dfb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integrating OpenAI’s GPT-3 API to Generate Content in a Flutter App]]></title>
            <link>https://medium.com/@shahbaz.gondal588/integrating-openais-gpt-3-api-to-generate-questions-in-a-flutter-app-05b23ed21cfd?source=rss-8f76f4132ebc------2</link>
            <guid isPermaLink="false">https://medium.com/p/05b23ed21cfd</guid>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[dart]]></category>
            <dc:creator><![CDATA[Shahbaz Gondal]]></dc:creator>
            <pubDate>Fri, 10 May 2024 14:20:11 GMT</pubDate>
            <atom:updated>2024-05-10T14:25:01.820Z</atom:updated>
            <content:encoded><![CDATA[<h3>Prerequisites:</h3><p><strong><em>Note: You have to add credits of a minimum 5$</em></strong></p><h3>Setting Up the Flutter Project:</h3><ul><li>You can implement an already flutter project or make new project on the base of your requirements.</li><li>Add necessary dependencies, including http, path_provider, and pdf.</li></ul><pre>// Add dependencies to pubspec.yaml<br>dependencies:<br>  flutter:<br>    sdk: flutter<br>  http: ^0.13.3<br>  path_provider: ^2.0.2<br>  pdf: ^3.4.1</pre><p><strong>Creating the </strong><strong>CreatedQuestion Widget:</strong></p><p>Implement of the CreatedQuestion widget, you can show this list of question generated according to your requirements</p><pre>class CreatedQuestion extends StatefulWidget {<br>  final String topic;<br>  final int numQuestions;<br>  final String questionType;<br><br>  CreatedQuestion({<br>    required this.topic,<br>    required this.numQuestions,<br>    required this.questionType,<br>  });<br><br>  @override<br>  _CreatedQuestionState createState() =&gt; _CreatedQuestionState();<br>}<br><br>class _CreatedQuestionState extends State&lt;CreatedQuestion&gt; {<br>  List&lt;String&gt; _questions = [];<br>  bool _isLoading = true;<br>  final String _apiKey = &#39;YOUR_API_KEY&#39;; // Replace with your OpenAI API key<br><br>  @override<br>  void initState() {<br>    super.initState();<br>    _generateQuestions();<br>  }<br><br>  // Add _generateQuestions and _saveAsPdf methods here<br>}</pre><h3>Integrating OpenAI’s GPT-3 API:</h3><p>In the code provided below, the `temperature` parameter is used when making a request to the GPT-3 API. This parameter is a crucial aspect of controlling the creativity and randomness of the responses generated by the model.</p><ul><li>The `temperature` parameter controls the randomness of the output text. It essentially represents the level of diversity or randomness in the model’s predictions. A higher temperature value results in more randomness and creativity in the generated text, while a lower temperature value leads to more conservative and predictable responses.</li><li><strong>Low Temperature (Close to 0):</strong> When the temperature is low, the model tends to produce more deterministic and conservative responses. It is less likely to introduce new ideas or variations and is more likely to generate text that closely resembles the training data.</li><li><strong>High Temperature (Close to 1):</strong> On the other hand, when the temperature is high, the model becomes more creative and exploratory. It is more likely to produce diverse and unpredictable responses, including novel ideas and unconventional language.</li><li>In the provided code, the `<strong>temperature</strong>` value is set to `0.7`. This value strikes a balance between creativity and coherence in the generated questions. It allows for some degree of randomness and creativity while still ensuring that the questions are relevant and coherent within the context of the given topic and question type.</li><li>Adjusting the `temperature` parameter allows developers to fine-tune the output of the model based on their specific use case and preferences. Experimenting with different temperature values can help find the right balance between creativity and relevance for generating text with the GPT-3 API.</li></ul><ol><li><strong>model: </strong>This specifies the version of the GPT model being used. In this case, it&#39;s set to &quot;<strong>gpt-3.5-turbo</strong>&quot;. The <strong>gpt-3.5-turbo</strong> model is a specific version of the GPT-3 model provided by OpenAI. It&#39;s optimized for speed and efficiency, making it suitable for real-time applications like chatbots.</li><li><strong>messages:</strong> This is an array containing one or more message objects. Each message object represents a conversation turn or input given to the model.</li></ol><ul><li><strong>role:</strong> This indicates the role of the message. In this case, it&#39;s set to &quot;user&quot;, indicating that the message is coming from the user or client application.</li><li>content: This contains the actual text content of the message. It&#39;s a string template where variables ${widget.numQuestions}, ${widget.questionType}, and ${widget.topic} are used insert values from the last screen.</li></ul><pre>Future&lt;void&gt; _generateQuestions() async {<br>  final url = Uri.parse(&#39;https://api.openai.com/v1/chat/completions&#39;);<br>  final headers = {<br>    &#39;Content-Type&#39;: &#39;application/json&#39;,<br>    &#39;Authorization&#39;: &#39;Bearer $_apiKey&#39;,<br>  };<br>  final data = {<br>    &#39;model&#39;: &#39;gpt-3.5-turbo&#39;,<br>    &#39;messages&#39;: [<br>      {<br>        &#39;role&#39;: &#39;user&#39;,<br>        &#39;content&#39;:<br>            &#39;Generate ${widget.numQuestions} ${widget.questionType} questions about ${widget.topic}.&#39;<br>      }<br>    ],<br>    &#39;temperature&#39;: 0.7,<br>  };<br><br>  try {<br>    final response = await http.post(url, headers: headers, body: jsonEncode(data));<br>    if (response.statusCode == 200) {<br>      final jsonData = jsonDecode(response.body);<br>      final List&lt;dynamic&gt; choices = jsonData[&#39;choices&#39;];<br>      List&lt;String&gt; questions = [];<br>      for (var choice in choices) {<br>        questions.add(choice[&#39;message&#39;][&#39;content&#39;]);<br>      }<br>      setState(() {<br>        _questions = questions;<br>        _isLoading = false;<br>      });<br>    } else {<br>      setState(() {<br>        _isLoading = false;<br>      });<br>      print(&#39;Failed to generate questions. Status code: ${response.statusCode}&#39;);<br>    }<br>  } catch (e) {<br>    setState(() {<br>      _isLoading = false;<br>    });<br>    print(&#39;Error: $e&#39;);<br>  }<br>}</pre><h3>Displaying Generated Questions:</h3><ul><li><strong>body:</strong> This is a property of the Scaffold widget, which represents the main content area of the screen.</li><li><strong>_isLoading:</strong> This is a boolean variable that indicates whether data is currently being loaded. If <strong>_isLoading</strong> is <strong>true</strong>, which means that the app is in the process of fetching data from the API.</li></ul><p><strong>Conditional Rendering:</strong></p><ul><li>If <strong>_isLoading</strong> is <strong>true</strong>, the app displays a CircularProgressIndicator at the center of the screen to indicate to the user that data is being loaded. This is done using a ternary operator (<strong>?</strong>).</li><li>If <strong>_isLoading</strong> is <strong>false</strong>, the app displays the list of questions fetched from the API. This is done using a ListView.builder widget.</li><li><strong>ListView.builder:</strong> This widget is used to efficiently create a scrollable list of items. It generates list items dynamically based on the length of the <strong>_questions</strong> list.</li><li><strong>itemCount:</strong> This property specifies the number of items in the list, which is equal to the length of the <strong>_questions</strong> list.</li><li><strong>itemBuilder:</strong> This property is a callback function that returns a widget for each item in the list. It is called once for each item in the list, and it constructs a ListTile widget for displaying each question.</li><li><strong>context:</strong> This parameter is the BuildContext, which provides information about the location in the widget tree.</li><li><strong>index:</strong> This parameter represents the position of the item in the list.</li><li><strong>return ListTile: </strong>This statement constructs a ListTile widget for each question in the <strong>_questions</strong> list. The title of the ListTile is set to display the text of the question at the corresponding index in the <strong>_questions</strong> list.</li></ul><pre>body: _isLoading<br>  ? Center(child: CircularProgressIndicator())<br>  : ListView.builder(<br>      itemCount: _questions.length,<br>      itemBuilder: (context, index) {<br>        return ListTile(<br>          title: Text(_questions[index]),<br>        );<br>      },<br>    ),</pre><h3>Saving Questions as a PDF:</h3><p><strong>Creating a PDF Document:</strong></p><ul><li>A new PDF document is created using the <strong>pw.Document()</strong> constructor from the pdf package.</li><li>A single page is added to the document using <strong>pdf.addPage()</strong>. The page content is built using a <strong>pw.Column</strong> widget, which contains a list of <strong>pw.Text</strong> widgets representing the generated questions.</li></ul><p><strong>Getting the Directory for File Storage:</strong></p><ul><li>The <strong>getApplicationSupportDirectory()</strong> function from the <strong>path_provider</strong> package is used to get the directory where the app can store files.</li><li>A new directory named “paper” is created within the obtained directory path if it doesn’t already exist.</li></ul><p><strong>Writing the PDF to File:</strong></p><ul><li>A <strong>File</strong> object is created representing the PDF file to be saved. The file path is constructed by appending the file name &quot;created_questions.pdf&quot; to the &quot;paper&quot; directory path.</li><li>The <strong>pdf.save()</strong> method is called to generate the PDF file as a byte array, which is then written to the file using <strong>file.writeAsBytes()</strong>.</li></ul><h3>References</h3><ul><li><a href="https://firebase.google.com/docs/">Firebase Documentation</a></li><li><a href="https://docs.flutter.dev/">Flutter documentation</a></li></ul><p><a href="https://platform.openai.com/">https://platform.openai.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=05b23ed21cfd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fine-tuning LLaMA: Preparing Custom pdf Data for Style Mimicry]]></title>
            <link>https://medium.com/@shahbaz.gondal588/fine-tuning-llama-preparing-custom-pdf-data-for-style-mimicry-193af210c0d5?source=rss-8f76f4132ebc------2</link>
            <guid isPermaLink="false">https://medium.com/p/193af210c0d5</guid>
            <category><![CDATA[google-colab]]></category>
            <category><![CDATA[training]]></category>
            <category><![CDATA[pdf]]></category>
            <category><![CDATA[llma2-chat-model]]></category>
            <dc:creator><![CDATA[Shahbaz Gondal]]></dc:creator>
            <pubDate>Thu, 09 May 2024 18:40:13 GMT</pubDate>
            <atom:updated>2024-05-09T18:40:13.680Z</atom:updated>
            <content:encoded><![CDATA[<p>Fine-tuning large language models (LLMs) like LLaMA for specific tasks often requires customized datasets. In this blog, we explore various approaches to preprocess data for fine-tuning LLaMA, focusing on the goal of mimicking writing style.</p><h3>Approaches for Data Preparation:</h3><h3>Question-Answer Format:</h3><ul><li><strong>Description: </strong>Convert raw text of research papers into question-answer format using LLMs. This approach involves utilizing tools like augmentoolkit or platforms like Together.xyz to generate Q/A pairs.</li><li><strong>Pros:</strong> Provides structured data for fine-tuning, suitable for question answering tasks.</li><li><strong>Cons: </strong>May not capture the writing style accurately as Q/As are generated by LLMs based on text knowledge.</li></ul><h3>Question Generation:</h3><ul><li><strong>Description: </strong>Split the raw text into paragraphs and generate questions for each paragraph using LLMs. The original text remains as the answer, preserving the author’s writing style.</li><li><strong>Pros:</strong> Allows the fine-tuned model to learn how to answer questions in the author’s writing style.</li><li><strong>Cons:</strong> Requires careful handling of generated questions for quality and relevance.</li></ul><h3>Neutral Text Generation:</h3><ul><li><strong>Description:</strong> Split documents into chunks and generate neutral text for each chunk using LLMs. Then, fine-tune LLMs to convert neutral text to the original text.</li><li><strong>Pros:</strong> Enables the fine-tuned model to learn how to mimic the author’s writing style from neutral text.</li><li><strong>Cons:</strong> Complexity in managing neutral text generation and training sequences.</li></ul><h3>Discussion and Decision:</h3><p>Choosing the appropriate approach depends on the specific requirements of the task and the desired outcome. Each approach has its advantages and challenges. To decide the best approach:</p><ul><li>Evaluate the nature of the task and the importance of writing style mimicry.</li><li>Consider the availability and quality of data for each approach.</li><li>Experiment with different approaches to assess performance and suitability.</li></ul><h3>Implementation and Example:</h3><p>We provide a code snippet demonstrating the extraction of raw text from PDFs and processing it into the desired format for fine-tuning LLaMA. This includes converting PDFs to text files and organizing them for further preprocessing.</p><pre>import PyPDF2<br>import requests<br>from io import BytesIO<br>import os<br>def pdf_to_text(pdf_content):<br>    pdf_reader = PyPDF2.PdfReader(pdf_content)<br>    num_pages = len(pdf_reader.pages)<br>    text = &quot;&quot;<br>    for page_num in range(num_pages):<br>        page = pdf_reader.pages[page_num]<br>        text += page.extract_text()<br>    return text<br><br>def process_pdf_links(pdf_links,output_folder):<br>    if not os.path.exists(output_folder):<br>        os.makedirs(output_folder)<br>    for idx, pdf_link in enumerate(pdf_links):<br>        response = requests.get(pdf_link)<br>        if response.status_code == 200:<br>            pdf_content = BytesIO(response.content)<br>            text = pdf_to_text(pdf_content)<br>            txt_filename = f&quot;Research_Paper{idx+1}.txt&quot;<br>            txt_path = os.path.join(output_folder, txt_filename)<br>            with open(txt_path, &#39;w&#39;, encoding=&#39;utf-8&#39;) as txt_file:<br>                txt_file.write(text)<br>            print(f&quot;Text extracted from PDF {idx+1}&quot;)<br><br># Example usage:<br>pdf_links = [<br>    &#39;https://arxiv.org/pdf/2307.06090&#39;,<br>    # Add more PDF links as needed<br>]<br>output_folder = &#39;./raw_txt_input/&#39;<br>process_pdf_links(pdf_links,output_folder)</pre><p>Converting txt file int json</p><pre>import os<br>import json<br><br># Function to read and process each JSON file<br>def process_json_file(file_path):<br>    with open(file_path, &#39;r&#39;) as f:<br>        data = json.load(f)<br>        source = data[3].replace(&quot;./raw_txt_input/&quot;, &quot;&quot;)  # Remove &#39;raw_txt_input&#39; from source<br>        metadata = os.path.splitext(os.path.basename(file_path))[0]  # Remove file extension from metadata<br>        return {<br>            &quot;query&quot;: data[0],<br>            &quot;response&quot;: data[1],<br>            &quot;context&quot;: data[2],<br>            &quot;source&quot;: source,<br>            &quot;metadata&quot;: metadata<br>        }<br><br># Function to read all JSON files in a directory and consolidate the data<br>def read_json_files_in_directory(directory):<br>    consolidated_data = []<br>    for file_name in sorted(os.listdir(directory)):  # Sort files by name<br>        if file_name.endswith(&#39;.json&#39;):<br>            file_path = os.path.join(directory, file_name)<br>            consolidated_data.append(process_json_file(file_path))<br>    return consolidated_data<br><br># Directory containing the JSON files<br>input_directory_path = &#39;./output/qatuples_raw&#39;<br><br># Create the &#39;extracted_data&#39; folder if it doesn&#39;t exist<br>output_directory_path = &#39;./extracted_data&#39;<br>if not os.path.exists(output_directory_path):<br>    os.makedirs(output_directory_path)<br><br># Read and consolidate the data from all JSON files in the directory<br>consolidated_data = read_json_files_in_directory(input_directory_path)<br><br># Write the consolidated data to a single JSON file in the &#39;extracted_data&#39; folder<br>output_file_path = os.path.join(output_directory_path, &#39;consolidated_data.json&#39;)<br>with open(output_file_path, &#39;w&#39;) as f:<br>    json.dump(consolidated_data, f, indent=4)<br><br>print(&quot;Consolidated data has been written to:&quot;, output_file_path)</pre><h3>Finetune Llama-3 with LLaMA Factory</h3><h4>Install Dependencies</h4><pre>%cd /content/<br>%rm -rf LLaMA-Factory<br>!git clone https://github.com/hiyouga/LLaMA-Factory.git<br>%cd LLaMA-Factory<br>%ls<br>!pip install &quot;unsloth[colab-new] @ git+https://github.com/unslothai/unsloth.git&quot;<br>!pip install --no-deps xformers==0.0.25<br>!pip install .[bitsandbytes]</pre><p>Fine-tune model via LLaMA Board</p><pre>%cd /content/LLaMA-Factory/<br>!GRADIO_SHARE=1 llamafactory-cli webui</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ybgt6odr_ivKpR7kqiScXw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=193af210c0d5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating an Interactive Shapefile Dashboard with Streamlit]]></title>
            <link>https://medium.com/@shahbaz.gondal588/creating-an-interactive-shapefile-dashboard-with-streamlit-cff58cffd460?source=rss-8f76f4132ebc------2</link>
            <guid isPermaLink="false">https://medium.com/p/cff58cffd460</guid>
            <category><![CDATA[gis]]></category>
            <category><![CDATA[shapefile]]></category>
            <category><![CDATA[streamlit]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Shahbaz Gondal]]></dc:creator>
            <pubDate>Thu, 09 May 2024 12:47:52 GMT</pubDate>
            <atom:updated>2024-05-09T12:47:52.116Z</atom:updated>
            <content:encoded><![CDATA[<p>In this blog post, we’ll explore how to create an interactive dashboard for visualizing shapefile data using Streamlit, a popular Python library for building web applications, and GeoPandas, a library for working with geospatial data.</p><h3>Tools and Libraries Used:</h3><p>For this project, we’ll be using the following Python libraries:</p><ul><li><strong>Streamlit:</strong> for creating the web application.</li><li><strong>GeoPandas:</strong> for handling geospatial data and shapefiles.</li><li><strong>Matplotlib:</strong> for creating visualizations.</li></ul><pre>import streamlit as st<br>import geopandas as gpd<br>import matplotlib.pyplot as plt<br>import os</pre><h3>Understanding the Code:</h3><ol><li>Loading Data: The load_data function loads the shapefile data using GeoPandas. It is decorated with @st.cache to cache the data, improving performance by avoiding unnecessary reloading.</li><li>Creating the Dashboard: The Streamlit app consists of sections for displaying the shapefile data and visualizing it on a map.</li><li>Shapefile Data Display: The shapefile data is displayed in a Streamlit section using st.write.</li><li>Map Visualization: A map visualization of the shapefile data is created using Matplotlib and displayed using st.pyplot.</li></ol><h3>Explaining the Dashboard:</h3><p>The dashboard allows users to:</p><ul><li>View the shapefile data, including geometry and attributes.</li><li>Visualize the shapefile data on an interactive map.</li></ul><h3>Conclusion:</h3><p>Creating an interactive shapefile dashboard with Streamlit provides a user-friendly way to explore and visualize geospatial data. By leveraging Streamlit’s simplicity and GeoPandas’ capabilities for handling shapefiles, developers can build powerful applications for geospatial analysis and visualization.</p><h3>References:</h3><ul><li><strong>Streamlit Documentation:</strong> <a href="https://docs.streamlit.io/">https://docs.streamlit.io/</a></li><li><strong>GeoPandas Documentation: </strong><a href="https://geopandas.org/">https://geopandas.org/</a></li><li><strong>Matplotlib Documentation:</strong> <a href="https://matplotlib.org/stable/contents.html">https://matplotlib.org/stable/contents.html</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cff58cffd460" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring Web Scraping with Python]]></title>
            <link>https://medium.com/@shahbaz.gondal588/exploring-web-scraping-with-python-b88f28058333?source=rss-8f76f4132ebc------2</link>
            <guid isPermaLink="false">https://medium.com/p/b88f28058333</guid>
            <category><![CDATA[data-scraping]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[beautifulsoup]]></category>
            <category><![CDATA[request]]></category>
            <dc:creator><![CDATA[Shahbaz Gondal]]></dc:creator>
            <pubDate>Thu, 09 May 2024 12:38:52 GMT</pubDate>
            <atom:updated>2024-05-09T12:38:52.762Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eZLwEk2udFTf-bET" /><figcaption>Photo by <a href="https://unsplash.com/@markusspiske?utm_source=medium&amp;utm_medium=referral">Markus Spiske</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction:</h3><p>Web scraping is a powerful technique used to extract data from websites. In this blog post, we’ll delve into a Python script that demonstrates how to scrape data from web pages using the requests library and Beautiful Soup, and then save it to CSV files. Let’s dive in!</p><h3>Tools and Libraries Used:</h3><p>For this web scraping task, we’ll be using the following Python libraries:</p><ul><li><strong>requests</strong>: for making HTTP requests to retrieve web pages.</li><li><strong>Beautiful Soup</strong>: for parsing HTML and extracting data from web pages.</li><li><strong>pandas</strong>: for organizing and saving the scraped data to CSV files.</li></ul><pre>import requests<br>from bs4 import BeautifulSoup<br>import pandas as pd</pre><h3>Understanding the Code:</h3><ol><li>Scraping and Saving Data: The scrape_and_save function takes a URL and a CSV filename as input. It retrieves the webpage content using the requests library, parses it with Beautiful Soup, extracts relevant elements (such as images, videos, paragraphs, headings, links, etc.), and saves the data to a CSV file using the save_to_csv function.</li><li>Saving Data to CSV: The save_to_csv function takes the scraped data and a filename as input, converts it to a pandas DataFrame, and saves it to a CSV file.</li></ol><h3>Explaining the Scraping Process:</h3><p>Web scraping involves several steps:</p><ul><li><strong>HTTP Request</strong>: The script makes an HTTP GET request to the specified URL to retrieve the webpage content.</li><li><strong>HTML Parsing</strong>: Beautiful Soup parses the HTML content of the webpage and provides a navigable tree-like structure for easy extraction of data.</li><li><strong>Data Extraction</strong>: Relevant elements such as images, videos, text paragraphs, headings, links, etc., are extracted based on their HTML tags and attributes.</li><li><strong>Data Storage</strong>: The extracted data is organized into a structured format (in this case, a pandas DataFrame) and saved to a CSV file for further analysis.</li></ul><h3>Conclusion:</h3><p>Web scraping is a valuable technique for extracting data from websites and automating the process of data collection. By leveraging Python libraries such as requests and Beautiful Soup, developers can scrape web pages efficiently and extract useful information for various purposes, including data analysis, research, and reporting.</p><p><strong><em>Note: It’s essential to respect website policies and terms of service when scraping data from websites to ensure compliance with legal and ethical guidelines.</em></strong></p><h3>References:</h3><ul><li><strong>requests Documentation</strong>: <a href="https://docs.python-requests.org/en/master/">https://docs.python-requests.org/en/master/</a></li><li><strong>Beautiful Soup Documentation:</strong> <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/">https://www.crummy.com/software/BeautifulSoup/bs4/doc/</a></li><li><strong>pandas Documentation</strong>: <a href="https://pandas.pydata.org/docs/">https://pandas.pydata.org/docs/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b88f28058333" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding ECG Signal Processing with Python]]></title>
            <link>https://medium.com/@shahbaz.gondal588/understanding-ecg-signal-processing-with-python-b9dd4ea68682?source=rss-8f76f4132ebc------2</link>
            <guid isPermaLink="false">https://medium.com/p/b9dd4ea68682</guid>
            <category><![CDATA[biomedical]]></category>
            <category><![CDATA[bioinformatics]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[medical]]></category>
            <category><![CDATA[ecg]]></category>
            <dc:creator><![CDATA[Shahbaz Gondal]]></dc:creator>
            <pubDate>Thu, 09 May 2024 12:11:03 GMT</pubDate>
            <atom:updated>2024-05-09T12:11:03.368Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vpEN9mIN0pe-L9ax" /><figcaption>Photo by <a href="https://unsplash.com/@joshua_chehov?utm_source=medium&amp;utm_medium=referral">Joshua Chehov</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction:</h3><p>Electrocardiogram (ECG) signals are vital for diagnosing various heart conditions. Processing and analyzing ECG signals can provide valuable insights into cardiac health. In this blog post, we’ll explore a Python script that preprocesses ECG signals, detects QRS complexes, and calculates RR intervals.</p><h3>Tools and Libraries Used:</h3><p>For this ECG signal processing task, we’ll be using Python along with the following libraries:</p><ul><li>NumPy: for numerical computations and array operations.</li><li>SciPy: for signal processing functions such as filtering.</li><li>BioSPPy: a biosignal processing library that provides tools for ECG analysis.</li><li>Matplotlib: for visualization of ECG signals.</li></ul><pre>import os<br>import scipy.io<br>import numpy as np<br>from scipy.signal import butter, filtfilt<br>import biosppy.signals.ecg as ecg<br>import matplotlib.pyplot as plt</pre><h3>Understanding the Code:</h3><pre>def preprocess_signal(signal):<br><br><br>   b, a = butter(4, 40 / (500 / 10), btype=&#39;low&#39;)<br>   filtered_signal = filtfilt(b, a, signal, axis=-1)<br><br><br><br><br>   downsampled_signal = filtered_signal[:, ::10] <br><br><br>   return downsampled_signal<br><br><br>def plot_ecg(signal, sampling_rate, title=&quot;ECG Signal&quot;):<br>   time = np.arange(0, len(signal)) / sampling_rate<br>   plt.figure(figsize=(12, 6))<br>   plt.plot(time, signal)<br>   plt.title(title)<br>   plt.xlabel(&quot;Time (seconds)&quot;)<br>   plt.ylabel(&quot;Amplitude&quot;)<br>   plt.grid(True)<br>   plt.show()<br><br><br>def detect_qrs_complex(signal, sampling_rate):<br><br><br>   qrs_indices = ecg.ecg(signal=signal, sampling_rate=sampling_rate, show=False)[&#39;rpeaks&#39;]<br>   return qrs_indices<br><br><br>def calculate_rr_intervals(qrs_indices, sampling_rate):<br><br><br>   rr_intervals = np.diff(qrs_indices) / sampling_rate<br>   return rr_intervals<br><br><br><br><br>data_root_dir = &quot;a-large-scale-12-lead-electrocardiogram-database-for-arrhythmia-study-1.0.0/WFDBRecords/&quot;<br><br><br><br><br>def process_all_ecg_files(root_dir):<br>   for root, dirs, files in os.walk(root_dir):<br>       for file in files:<br>           if file.endswith(&quot;.mat&quot;):<br>               file_path = os.path.join(root, file)<br>               try:<br>                   mat_data = scipy.io.loadmat(file_path)<br>                   ecg_signal = mat_data[&#39;val&#39;]<br>                   processed_signal = preprocess_signal(ecg_signal)<br>                   plot_ecg(processed_signal[0], sampling_rate=500, title=file)<br>                   qrs_indices = detect_qrs_complex(processed_signal[0], sampling_rate=500)<br>                   rr_intervals = calculate_rr_intervals(qrs_indices, sampling_rate=500)<br>                   print(f&quot;Insights for ECG signal {file}:&quot;)<br>                   print(f&quot;Number of QRS complexes detected: {len(qrs_indices)}&quot;)<br>                   print(f&quot;Average RR interval: {np.mean(rr_intervals)} seconds&quot;)<br>                   print(f&quot;Minimum RR interval: {np.min(rr_intervals)} seconds&quot;)<br>                   print(f&quot;Maximum RR interval: {np.max(rr_intervals)} seconds&quot;)<br>                   print(&quot;------------------------------------------------------&quot;)<br>               except Exception as e:<br>                   print(f&quot;Error processing file {file}: {e}&quot;)<br><br><br><br><br>process_all_ecg_files(data_root_dir)</pre><ol><li>Preprocessing ECG Signal: The preprocess_signal function filters and downsamples the raw ECG signal to remove noise and reduce computational complexity.</li><li>Plotting ECG Signal: The plot_ecg function visualizes the processed ECG signal using Matplotlib, showing amplitude against time.</li><li>Detecting QRS Complexes: The detect_qrs_complex function uses BioSPPy to detect QRS complexes in the ECG signal, identifying heartbeats.</li><li>Calculating RR Intervals: The calculate_rr_intervals function computes RR intervals (the time between successive heartbeats) from the detected QRS complexes.</li><li>Processing ECG Files: The process_all_ecg_files function iterates through all ECG files in a specified directory, processes each file using the aforementioned functions, and prints insights about each ECG signal.</li></ol><h3>Explaining ECG Signal Processing:</h3><ul><li>Filtering: Raw ECG signals often contain noise from various sources. Filtering techniques, such as Butterworth filters, are applied to remove noise and artifacts.</li><li>QRS Detection: QRS complexes represent the electrical activity associated with ventricular depolarization. Detecting QRS complexes is essential for identifying heartbeats in the ECG signal.</li><li>RR Interval Calculation: RR intervals are the time durations between successive QRS complexes. These intervals provide valuable information about heart rate variability and cardiac health.</li></ul><h3>Conclusion:</h3><p>The Python script presented in this blog post demonstrates the process of ECG signal processing, including preprocessing, QRS detection, and RR interval calculation. By leveraging Python libraries and signal processing techniques, researchers and healthcare professionals can analyze ECG signals to gain insights into cardiac function and diagnose heart conditions.</p><h3>References:</h3><ul><li>NumPy Documentation: <a href="https://numpy.org/doc/">https://numpy.org/doc/</a></li><li>SciPy Documentation: <a href="https://docs.scipy.org/doc/">https://docs.scipy.org/doc/</a></li><li>BioSPPy Documentation: <a href="https://biosppy.readthedocs.io/en/stable/">https://biosppy.readthedocs.io/en/stable/</a></li><li>Matplotlib Documentation: <a href="https://matplotlib.org/stable/contents.html">https://matplotlib.org/stable/contents.html</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b9dd4ea68682" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Sentiment Analysis with Python and NLTK]]></title>
            <link>https://medium.com/@shahbaz.gondal588/understanding-sentiment-analysis-with-python-and-nltk-761add853f8d?source=rss-8f76f4132ebc------2</link>
            <guid isPermaLink="false">https://medium.com/p/761add853f8d</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[twitter]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Shahbaz Gondal]]></dc:creator>
            <pubDate>Thu, 09 May 2024 11:28:29 GMT</pubDate>
            <atom:updated>2024-05-09T11:28:29.540Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CIDUoi1CRcNDp98i" /><figcaption>Photo by <a href="https://unsplash.com/@shutter_speed_?utm_source=medium&amp;utm_medium=referral">Bastian Riccardi</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction:</h3><p>In today’s digital age, social media platforms are flooded with vast amounts of textual data, including tweets, reviews, and comments. Understanding the sentiment behind this text data is crucial for businesses, marketers, and researchers to gain insights into public opinion and make informed decisions. Sentiment analysis, a subfield of natural language processing (NLP), offers a way to automatically classify text as positive, negative, or neutral based on its sentiment.</p><h3>Tools and Libraries Used:</h3><p>For this sentiment analysis task, we’ll be using Python, a popular programming language, and the Natural Language Toolkit (NLTK), a powerful library for NLP tasks. NLTK provides various tools and resources for text processing and analysis, including a pre-trained sentiment intensity analyzer.</p><pre>import nltk<br>nltk.download(&#39;vader_lexicon&#39;)<br>from nltk.sentiment import SentimentIntensityAnalyzer</pre><h3>Understanding the Code:</h3><p>Let’s break down the code snippet provided and understand each component:</p><pre>import pandas as pd<br><br># Load the training data<br>train_df = pd.read_csv(&quot;Corona_NLP_train.csv&quot;, encoding=&#39;latin1&#39;)<br>train_original_tweets = train_df[&#39;OriginalTweet&#39;]<br><br># Initialize the SentimentIntensityAnalyzer<br>sia = SentimentIntensityAnalyzer()<br><br># Perform sentiment analysis on each tweet<br>train_annotations = []<br>for index, tweet in enumerate(train_original_tweets):<br>    sentiment_score = sia.polarity_scores(tweet)[&#39;compound&#39;]<br>    if sentiment_score &gt;= 0.05:<br>        sentiment_label = &quot;Positive&quot;<br>    elif sentiment_score &lt;= -0.05:<br>        sentiment_label = &quot;Negative&quot;<br>    else:<br>        sentiment_label = &quot;Neutral&quot;<br>    train_annotations.append({<br>        &quot;No.&quot;: index + 1,<br>        &quot;OriginalTweet&quot;: tweet,<br>        &quot;SentimentLabel&quot;: sentiment_label,<br>        &quot;SentimentScore&quot;: sentiment_score,<br>        &quot;Explanation&quot;: &quot;on the base of score&quot;<br>    })<br><br># Save the annotated data to a CSV file<br>train_annotations_df = pd.DataFrame(train_annotations)<br>train_annotations_df.to_csv(&quot;f180297_shahbaz.csv&quot;, index=False)</pre><h3>Explaining Sentiment Analysis Process:</h3><h4>Sentiment analysis involves several steps:</h4><ol><li>Text Preprocessing: Before analyzing sentiment, text data often undergoes preprocessing steps such as tokenization, removing stop words, and stemming to clean and normalize the text.</li><li>Sentiment Lexicons: Sentiment analysis tools like NLTK rely on sentiment lexicons or dictionaries containing words annotated with their sentiment polarity. These lexicons assign sentiment scores to words, which are aggregated to determine the overall sentiment of the text.</li><li>Sentiment Intensity Analysis: NLTK’s SentimentIntensityAnalyzer employs a lexicon-based approach to analyze sentiment intensity. It calculates a compound sentiment score ranging from -1 (extremely negative) to 1 (extremely positive), with values close to 0 indicating neutrality.</li><li>Thresholding: Based on the sentiment score, we apply threshold values to classify the text into positive, negative, or neutral categories. These thresholds may vary based on the application and domain.</li></ol><h3>Conclusion:</h3><p>Sentiment analysis is a powerful technique for extracting insights from textual data and understanding public opinion. By leveraging tools like NLTK, businesses, and researchers can analyze vast amounts of text data efficiently and gain valuable insights into customer sentiment, brand perception, and market trends.</p><p>References:</p><ul><li>NLTK Documentation: <a href="https://www.nltk.org/">https://www.nltk.org/</a></li><li>Python Programming Language: <a href="https://www.python.org/">https://www.python.org/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=761add853f8d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>