<?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 Daniel Zerihun Geda on Medium]]></title>
        <description><![CDATA[Stories by Daniel Zerihun Geda on Medium]]></description>
        <link>https://medium.com/@lenjisa48?source=rss-e69ed341b7b7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*V_oC-6YhZUwpLaiCU3D4GA.jpeg</url>
            <title>Stories by Daniel Zerihun Geda on Medium</title>
            <link>https://medium.com/@lenjisa48?source=rss-e69ed341b7b7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 10:07:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@lenjisa48/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[Contract Advisor RAG: Towards Building A High-Precision Legal Expert LLM APP]]></title>
            <link>https://medium.com/@lenjisa48/contract-advisor-rag-towards-building-a-high-precision-legal-expert-llm-app-3bd078fbc6e0?source=rss-e69ed341b7b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/3bd078fbc6e0</guid>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[rags]]></category>
            <dc:creator><![CDATA[Daniel Zerihun Geda]]></dc:creator>
            <pubDate>Mon, 19 Feb 2024 11:24:19 GMT</pubDate>
            <atom:updated>2024-03-22T07:21:20.992Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IGm-h_scr44lq_lt" /><figcaption>RAG (Retrieval Augmented Generation)</figcaption></figure><h3><strong>Introduction</strong></h3><p>Recent advances in large language models (LLMs) like GPT-4, Mistral and Llama have demonstrated powerful few-shot learning abilities — the capacity to adapt to new tasks and domains with just a handful of human annotated examples.</p><p>This ability is enabling a new paradigm of system design centered around the Retrieval Augmented Generation (RAG) framework. RAG leverages LLMs to generate more accurate and informative responses by retrieving relevant information from external resources(Markdown text, docs , databases(sql), and so on) using vector database store which is rather than lookup manually over the data set we can search them based on their semantic relationship i.e cosine similarity, RAG models can provide more accurate and contextually relevant responses compared to traditional generative models. RAG can leverage a variety of natural language processing tasks such as Q&amp;A over the data-source as well as the LLM, Content Generation, summarization, Machine Translation, and Code Generation. This blogs focuses on RAG pipeline to build a high precision legal expert that has the capabilities of generating genuine contract clause based on clients input and Q&amp;A sessions with contract clauses.</p><h3><strong>Background</strong></h3><p>when it comes to RAG the main bottleneck in designing a retrieval-augmented generation (RAG) pipeline is typically the retrieval component, which involves efficiently searching and filtering large corpus of documents to retrieve the most relevant information for a given input prompt; Specially documents like legal contract clauses demands higher level of accuracy in retrieving important components as well as the generated out; to achieve certain level of accuracy both the retrieval and the generation components must be efficient enough to reduce both latency and inaccuracy.</p><h3><strong>Retrieval</strong></h3><p>In short the main target of retrieval component is to retrieve the most relevant piece of information from large data corpus. As the size of the data corpus increases exponentially the complexity of retrieving important piece of information is the impediment for retrieval components, practically to achieve certain level of accuracy particularly in legal contract clauses data-corpus, the retrieval component must retrieve the most important piece of information during queries, in order to leverage latency the retrieval component retrieves from chunks rather than the whole dataset at every query, how every if the chunks with the closer contextual meaning dispersed widely all over the given chunks we may lose contextual meaning absolute to the whole dataset.</p><p>The contents inside most contractual legal clauses contain data that have long range dependencies which mostly are references or citations, the other problem is most LLMs have limited number of context windows so the size of each chunks must not exceed certain points.</p><p>This project leverages LangChain framework to orchestrate end-to-end RAG pipeline. The main objective is to fine-tune different components of RAG pipeline to achieve maximum precision, to foster the capabilities of drafting, reviewing, and negotiating contracts.</p><p><strong>Chunking</strong></p><p>Chunks typically refer to smaller, manageable pieces of text that are extracted from a larger document during the Retrieval stage. In langchain framework there are a number of chunking methods</p><ol><li>split by character : This is the simplest method. This splits based on characters (by default “”) and measure chunk length by number of characters.</li><li>Recursively split by character : This text splitter is the recommended one for generic text. It is parameterized by a list of characters. It tries to split on them in order until the chunks are small enough.</li></ol><pre>&quot;&quot;&quot;splitter based on character&quot;&quot;&quot;<br>from langchain.text_splitter import CharacterTextSplitter<br><br>text_splitter = CharacterTextSplitter(<br>    separator=&quot;\n\n&quot;,<br>    chunk_size=1000,<br>    chunk_overlap=200,<br>    length_function=len,<br>    is_separator_regex=False,<br>)</pre><pre>#split them recursively<br>text_splitter = RecursiveCharacterTextSplitter(<br>    # Set a really small chunk size, just to show.<br>    chunk_size=100,<br>    chunk_overlap=20,<br>    length_function=len,<br>    is_separator_regex=False,<br>)</pre><p>The above two Technics are very generic, and they are impractical specially where there is long dependencies with in the data corpus. Now in order to meet the precision we are looking for we will demonstrate advanced chunking technics</p><p><strong>Semantic Chunking</strong></p><p>As opposed to chunking iteratively and randomly semantic chunking employs chunking based on the cosine similarity between two splits and chunk them together if they have closer cosine distance. so let’s go through steps involves to chunk semantically.</p><ol><li><strong>Splitting the text: </strong>the raw text file needs to be split into list of sentences based on punctuation marks:</li></ol><pre>sentences = re.split(r&#39;(?&lt;=[.?!])\s+&#39;, text)</pre><p>2. <strong>Combining Sentences : </strong>This steps involves concatenating individual ‘single_sentences_list’ based on their buffer-sizes; this step is also crucial steps because the combine sentences encompasses more contexts per list than single sentence lists</p><pre>def combine_sentences(sentences, buffer_size=2):<br>    # Go through each sentence dict<br>    for i in range(len(sentences)):<br><br>        # Create a string that will hold the sentences which are joined<br>        combined_sentence = &#39;&#39;<br><br>        # Add sentences before the current one, based on the buffer size.<br>        for j in range(i - buffer_size, i):<br>            # Check if the index j is not negative (to avoid index out of range like on the first one)<br>            if j &gt;= 0:<br>                # Add the sentence at index j to the combined_sentence string<br>                combined_sentence += sentences[j][&#39;sentence&#39;] + &#39; &#39;<br><br>        # Add the current sentence<br>        combined_sentence += sentences[i][&#39;sentence&#39;]<br><br>        # Add sentences after the current one, based on the buffer size<br>        for j in range(i + 1, i + 1 + buffer_size):<br>            # Check if the index j is within the range of the sentences list<br>            if j &lt; len(sentences):<br>                # Add the sentence at index j to the combined_sentence string<br>                combined_sentence += &#39; &#39; + sentences[j][&#39;sentence&#39;]<br><br>        # Then add the whole thing to your dict<br>        # Store the combined sentence in the current sentence dict<br>        sentences[i][&#39;combined_sentence&#39;] = combined_sentence<br><br>    return sentences<br><br></pre><p><strong>3. Embedding Combind sentences : </strong>this steps stages the combined sentence for cosine similarity between pair embedding, at this step the comparison of each embedding can be between consecutive sentences and chunks them dynamically based on the calculated distance from the embedded combined sentences. we used Scapy for the embedding the embedding can also influence the over all performace while we embed at each step</p><pre>import spacy<br><br># Load the spaCy embedder<br>nlp = spacy.load(&#39;en_core_web_sm&#39;)<br><br># Create embedding vectors for the input sentences using the spaCy embedder<br>embeddings = [nlp(sentence).vector for sentence in [x[&#39;combined_sentence&#39;] for x in sentences]]<br>for i, sentence in enumerate(sentences):<br>    sentence[&#39;combined_sentence_embedding&#39;] = embeddings[i]</pre><p><strong>4. Calculating cosine distance : </strong>cosine similarity calculates the angle between two vector is closer to 0 it means they are closer to each and if the angle is closer to 180 degree we deduce that they are farther appart semantically</p><blockquote>cos(θ) = (u . v) / (||u|| ||v||)</blockquote><blockquote>Where:</blockquote><blockquote>u . v is the dot product of u and v,</blockquote><blockquote>||u|| is the Euclidean length (or magnitude) of u,</blockquote><blockquote>||v|| is the Euclidean length (or magnitude) of v,</blockquote><blockquote>and θ is the angle between u and v.</blockquote><pre>from sklearn.metrics.pairwise import cosine_similarity<br><br>def calculate_cosine_distances(sentences):<br>    distances = []<br>    for i in range(len(sentences) - 1):<br>        embedding_current = sentences[i][&#39;combined_sentence_embedding&#39;]<br>        embedding_next = sentences[i + 1][&#39;combined_sentence_embedding&#39;]<br>        <br>        # Calculate cosine similarity<br>        similarity = cosine_similarity([embedding_current], [embedding_next])[0][0]<br>        <br>        # Convert to cosine distance<br>        distance = 1 - similarity<br><br>        # Append cosine distance to the list<br>        distances.append(distance)<br><br>        # Store distance in the dictionary<br>        sentences[i][&#39;distance_to_next&#39;] = distance<br><br>    # Optionally handle the last sentence<br>    # sentences[-1][&#39;distance_to_next&#39;] = None  # or a default value<br><br>    return distances, sentences</pre><p>In a sense of semantic chunking fundamentally we will chunk them based on their semantic similarity in the sequence of the given data set so we can create chunks dynamically based on their threshold similarity</p><p>The next step is to create chunks based on the distance and we assign breakpoints percentage which will be used to assign breakpoints where there is large dissimilarity:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/1*1TJQza0gIbfb8yehkgEsWg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*rHwZ8a9011Hq4M8j_7VybQ.png" /><figcaption>chunks summary</figcaption></figure><p>using By optimizing the size of threshold frequency we can control optimal size of each chunk to halt potential surpassing of the LLM as threshold percentage = 95</p><p>Checking for empty chunks and drop them to avoid confusion for the rag, the next step is embed them for our rag retriever :</p><pre>from langchain_community.embeddings.spacy_embeddings import SpacyEmbeddings<br>from langchain_community.vectorstores import FAISS<br>from langchain_core.prompts import ChatPromptTemplate<br>vectorstore = FAISS.from_texts(<br>    chunks, embedding=embeddings<br>)</pre><blockquote>It is important to store the chunks in meaningful manner using formats like dictionaries in json file or other text format, so that we can retrieve the chunks later locally</blockquote><p>using FAISS-GPU we can store the indexes of the chunk embeddings for future retrieval.</p><blockquote>FAISS (Facebook AI Similarity Search) is a library developed by Facebook’s AI Research lab (FAIR) for efficient similarity search and clustering of dense vectors. It allows users to search for vectors that are similar to a given query vector, and it is particularly well-suited for large-scale, high-dimensional vector search tasks.</blockquote><pre>vectorstore.save_local(&quot;final_optimized_indexes&quot;)</pre><pre>#load indexes locally<br>from langchain_community.vectorstores import FAISS<br>vectorstore_local = FAISS.load_local(&quot;final_optimized_indexes&quot;, embeddings)</pre><p><strong>ChatPromptTemplate : </strong>It is ground prompt template to augument between user query and given context by retriever components. let’s look at the prompt template :</p><pre>from langchain_core.prompts import ChatPromptTemplate<br>template = &quot;&quot;&quot;&lt;human&gt;: As a legal contract advisor, your role is pivotal in navigating the complexities of the contract clause agreement. Your responsibility extends beyond mere interpretation; it encompasses a meticulous analysis and strategic elucidation of the user&#39;s query based on the given {context}. To accomplish this effectively, consider the following steps:<br><br>1. Contextual Understanding: Begin by immersing yourself in the provided contract clause or {context}, grasping the intricacies of the terms, conditions, and potential implications involved. Pay particular attention to any ambiguous language or clauses that may pose risks to your client.<br><br>2. User Query Analysis: Carefully dissect the user&#39;s question within the {context} or the contract clause. Identify any specific clauses or provisions that the question pertains to and analyze their impact on your client&#39;s interests or question.<br><br>3. Comprehensive Response: Craft a response that addresses the user&#39;s query comprehensively, taking into account the nuances of the contract clause. Provide detailed explanations and recommendations, ensuring that your client is fully informed of their rights and obligations under the agreement.<br><br>4. Risk Mitigation: As you formulate your response, prioritize the mitigation of risks inherent in the contract clause. Identify potential pitfalls or areas of concern and propose proactive measures to safeguard your client&#39;s interests and minimize their exposure to liability.<br><br>5. Strategic Communication: Ensure that your response is conveyed in a clear, concise, and persuasive manner. Articulate your points effectively, citing relevant legal precedents, industry standards, and best practices to support your arguments and strengthen your client&#39;s position.<br><br>By following these steps diligently, you can provide informed, strategic guidance that empowers your client and ensures the integrity of the contract clause agreement.<br><br>NB: If the provided {context} is not sufficient enough to answer the user question please avoid any assumption.<br>Question: {question}<br><br>\n<br><br>&lt;bot&gt;:<br>&quot;&quot;&quot;<br><br>ANSWER_PROMPT = ChatPromptTemplate.from_template(template</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*jPnmcEiKy4E3bSWjPzhnrA.png" /><figcaption>Results from query</figcaption></figure><p>The provided prompt template tried to augment the user query with the context, it provides the context’s contents for the LLM and how it assists client based on user query and also it tried to add how it should handle user query. but we can even expand the query using Technics such as chain of thoughts to handle user query independently using more than one chain, or we can even expand users query for the retriever and for the llm itself.</p><p>since the model supposed to provide Q&amp;A we will run the chain using get_buffer_string method from LangChain_core.messages class so we can cache the chat history for future use.</p><p>NB. to determine the size chunks to accommodate optimal size of chunk there are also other considerations it’s better to take into account the statistical aspect of and find ground rule to apply for, for instance let us look at the our splits statistical data :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*0cuTwaD0V6bgyOjfqE31kA.png" /><figcaption>Statistics</figcaption></figure><p>so our average sentence length is 350+, the skewness of the sentence is positive indicates skewed to the right, the standard deviation is large indicates larger dispersion and particularly the value of kurtosis indicates higher presence of outlier(k=61), yet in such case there might be long quotes as far as precision matters it is good to keep the sematic rather than context window but if there are too longer chunks we might need decrease the sensitivity of breakpoints threshold.</p><p><strong>Agentic Chunking : </strong>This is one by far the most expensive and highly efficient chunking mechanism, it leverages the LLM itself to create the chunks itself using prompt template and returns the chunks and corresponding index values. It is expensive because the LLM will go all over through the dataset to create chunks using pipeline to store each chunks and index value, running this pipeline in dedicated API such as GPT-4 may incur significant amount of money. Yet at the end of the day it will all come down to trade-off when accuracy is more important than cost we can leverage them using LLM to create the chunks either optionally load the models locally or on private cloud.</p><pre>PROMPT = ChatPromptTemplate.from_messages(<br>            [<br>                (<br>                    &quot;system&quot;,<br>                    &quot;&quot;&quot;<br>                    You are the steward of a group of chunks which represent groups of sentences that talk about a similar topic<br>                    A new proposition was just added to one of your chunks, you should generate a very brief 1-sentence summary which will inform viewers what a chunk group is about.<br><br>                    A good summary will say what the chunk is about, and give any clarifying instructions on what to add to the chunk.<br><br>                    You will be given a group of propositions which are in the chunk and the chunks current summary.<br><br>                    Your summaries should anticipate generalization. If you get a proposition about apples, generalize it to food.<br>                    Or month, generalize it to &quot;date and times&quot;.<br><br>                    Example:<br>                    Input: Proposition: Greg likes to eat pizza<br>                    Output: This chunk contains information about the types of food Greg likes to eat.<br><br>                    Only respond with the chunk new summary, nothing else.<br>                    &quot;&quot;&quot;,<br>                ),<br>                (&quot;user&quot;, &quot;Chunk&#39;s propositions:\n{proposition}\n\nCurrent chunk summary:\n{current_summary}&quot;),<br>            ]<br>        )<br><br>        runnable = PROMPT | self.llm<br></pre><p><strong>Reranking : </strong>reranking is the process of rescoring the initial set of candidate answers generated by the retriever component for a given query, It can also help to reduce the impact of noise in the initial retrieval step, leading to more accurate and reliable answers, for this purpose we will use COHERE toolkit, you can get the api from here <a href="https://cohere.com/">https://cohere.com/</a></p><pre>from langchain.retrievers import ContextualCompressionRetriever<br>from langchain.retrievers.document_compressors import CohereRerank<br>import os <br>from dotenv import load_dotenv<br>load_dotenv<br>compressor = CohereRerank()<br>compression_retriever = ContextualCompressionRetriever(<br>    base_compressor=compressor, base_retriever=retriever<br>)</pre><p><strong>Evaluation</strong></p><p>During the testing process, when given 10 questions extracted from the original data source, the system answered 9 questions accurately, indicating a 90% accuracy rate. However, when the system ran without re-ranking, the accuracy dropped to 70%. Before employing re-ranking, the system struggled particularly with Yes or No questions. Yet, after implementing the COHERE toolkit for re-ranking, there was a notable improvement in performance.</p><pre>class AIMessage:<br>    def __init__(self, content):<br>        self.content = content<br><br># Example instance<br>example_message = conversational_qa_chain.invoke(<br>    {<br>        &quot;question&quot;: &quot;What happens if the Advisor claims compensation based on employment relationship with the Company?&quot;,<br>        &quot;chat_history&quot;: [],<br>    }<br>)<br># Function to print content with line breaks<br>def print_with_line_breaks(message, max_line_length=80):<br>    words = message.split()<br>    lines = []<br>    current_line = &#39;&#39;<br>    for word in words:<br>        if len(current_line) + len(word) + 1 &lt;= max_line_length:<br>            current_line += word + &#39; &#39;<br>        else:<br>            lines.append(current_line)<br>            current_line = word + &#39; &#39;<br>    if current_line:<br>        lines.append(current_line)<br>    for line in lines:<br>        print(line)<br><br># Print the content with line breaks<br>print(&quot;Message content:&quot;)<br>print_with_line_breaks(example_message.content)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/909/1*tumoKD1R3P8x58zIjrCQuA.png" /><figcaption>Answer</figcaption></figure><p><strong>Ragas Evaluation: </strong>To comprehensively test a retrieval-augmented generation (RAG) pipeline, it is essential to evaluate both the language model (LLM) and the retrieval component. This begins with acquiring a human annotated evaluation dataset comprising questions, answers, contexts, and ground truth to measure metrics such as context recall</p><p>now let’s look at the results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/989/1*2MGUjlsnkFOe6cA4F9DNCg.png" /></figure><p>The precision of the context shows slight variation in certain sections, indicating a potential signal-to-noise ratio issue when irrelevant context is retrieved for a given question. On the other hand, the context recall demonstrates lower values in certain areas but remains consistent throughout the rest of the evaluation, showcasing high accuracy in search relevance between the context and the ground truth. Additionally, the answer relevancy scores also exhibit some lower ratings at specific points, suggesting potential challenges for the retriever component in identifying the correct context.</p><p><strong>Conclusion</strong></p><p>In summary by manipulating different components in RAG pipeline we can enhance the RAG pipeline to be more efficient, the use case of RAG pipeline in this particular project tried to cover the legal clause data corpus, as the context scope changes the data organization also changes how the RAG pipeline operates.</p><p><strong>Future Work</strong></p><p>Even though we tried to optimize the precision of the RAG by leveraging advanced chunking method and ranking our retrieval, we can further go for instance fine-tune the embedding model to train them on legal clause contract document to embed our datasets efficiently and to capture the nuance of legal terminologies. and we can further train the LLM itself to handle such tasks efficiently.</p><p>Github Link :<a href="https://github.com/DanielZerihunGeda/Contract-Advisor-RAG-Towards-Building-A-High-Precision-Legal-Expert-LLM-APP"> https://github.com/DanielZerihunGeda/Contract-Advisor-RAG-Towards-Building-A-High-Precision-Legal-Expert-LLM-APP</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3bd078fbc6e0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automated Storyboard Synthesis: A Comprehensive Machine Learning Framework for Text-to-Visual…]]></title>
            <link>https://medium.com/@lenjisa48/automated-storyboard-synthesis-a-comprehensive-machine-learning-framework-for-text-to-visual-cd88aa47f8c8?source=rss-e69ed341b7b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd88aa47f8c8</guid>
            <category><![CDATA[stable-diffusion]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[vgg16]]></category>
            <dc:creator><![CDATA[Daniel Zerihun Geda]]></dc:creator>
            <pubDate>Sat, 17 Feb 2024 20:26:24 GMT</pubDate>
            <atom:updated>2024-02-19T08:58:11.736Z</atom:updated>
            <content:encoded><![CDATA[<h3>Automated Storyboard Synthesis: A Comprehensive Machine Learning Framework for Text-to-Visual Transformation in Digital Advertising</h3><h3>Introduction</h3><p>In today’s digital landscape, the power of visual content cannot be overstated. From social media advertisements to website banners, captivating visuals play a crucial role in capturing audience attention and conveying brand messages effectively. However, creating compelling visual content that resonates with the target audience can be a challenging and time-consuming task for marketers and advertisers.</p><p>Traditional approaches to visual content creation often rely on manual design processes, which stretched from concept to the final visual output. Moreover, transforming textual descriptions or concepts into engaging visuals requires a deep understanding of design principles and creative expertise.</p><p>To address these challenges, a new paradigm in digital advertising is emerging i.e automated storyboard synthesis. This innovative approach leverages the power of machine learning and artificial intelligence to generate visually stunning storyboards directly from textual descriptions or concepts. By automating the process of text-to-visual transformation, advertisers can streamline their content creation workflow, save time and resources, and produce more engaging advertisements.</p><p>In this blog post, we will explore the concept of automated storyboard synthesis in digital advertising and introduce a comprehensive machine learning framework designed to facilitate text-to-visual transformation.</p><h3><strong>Business Objective</strong></h3><p>Traditional Creative Advertisement content creating has a number of actors and process to go through starting from concept into graphical creative design and to composition, the process might involves iteration of a number of creative design until the client need is exactly meet. Designing highly creative graphical design from scratch requires advanced skill set of manipulating third party designing tools , resources as well as extended time.</p><p>The main business objective focuses on automating the process of designing creative advertisement content with in a matter of minutes which previously might take days or even weeks. in recent times the emergence of modality in Large Language model to go beyond from a chat completion such as text-to-image, image-to-text, image-to-image and so on. This project aims to harness multi modality by streamlining end-to-end creation of creative ad content from a given concept.</p><pre>    concepts = { <br>         &quot;frame_1&quot;: { <br>             &quot;Background&quot;: &quot;A high-resolution 3D Coca-Cola bottle center-screen, bubbles rising to the top, transitioning into a sleek DJ turntable with a vinyl record that has the Coke Studio logo.&quot;, <br>             &quot;CTA Button&quot;: &quot;&#39;Mix Your Beat&#39; in bold, playful font pulsating to the rhythm of a subtle background beat, positioned at the bottom of the screen.&quot; <br>         }, <br>         &quot;frame_2&quot;: { <br>             &quot;Interactive Elements&quot;: &quot;A digital beat mixer interface with vibrant, touch-responsive Latin American instrument icons like congas, claves, and maracas, each activating a unique sound layer.&quot;, <br>             &quot;Background&quot;: &quot;A dynamic, abstract representation of sound waves that move in sync with the user&#39;s interactions.&quot; <br>         }, <br>         &quot;frame_3&quot;: { <br>             &quot;Background&quot;: &quot;A dynamic, abstract representation of sound waves that move in sync with the user&#39;s interactions.&quot;, <br>             &quot;Animation&quot;: &quot;A kaleidoscope of colors that dance across the screen, with each beat added, symbolizing the fusion of cultures and music.&quot;, <br>             &quot;CTA Button&quot;: &quot;A &#39;Play Your Mix&#39; button that pulses like a heartbeat, encouraging users to share their creation.&quot; <br>         } <br>     }<br></pre><p>The given example contains necessary prompts to generate necessary assets for the LLM. So the main theme of this project is asset generation as well as composition.</p><p><strong>Image Generation</strong><br><br>Image generation will pull a pre-trained model from replicate.com for inference using a paying version of replicate will be beneficial since the free version of replicate has limits on the number of inference per API token. And there are a number of models with both cons and pros depending on the required assets so the solution I am preparing is to experiment with available models to get the desired outcome, Some models might perform better on some concepts and might not perform for another concept. This is because every model is fine-tuned on different datasets to perform better.</p><p>So the class we wrote will handle the concept as dictionaries to return the assets URL address.</p><pre>   class ImageGenerater: <br>     def __init__(self, asset_suggestions: dict) -&gt; None: <br>            &quot;Rest of the codes here .....&quot;<br>         self.asset_suggestions = asset_suggestions       <br>  output = replicate.run( <br>                 &quot;PLACE_HOLDER FOR MODEL FROM REPLICATE&quot;<br></pre><blockquote>The emergence of stable diffusion models made the image generation seamless and less resource demands while keeping the higher image quality. Rather than generating pixels in higher dimensions latent diffusion can reduce the memory and computational time by applying the diffusion process over a lower dimensional latent space so it will compress them and generate latent representations of the image.</blockquote><h4><strong>Image Composition</strong></h4><p>The image composer class comprised of Assets Localization and Assets blending the localization method places each asset in static positions after the generation of each assets and after that the blending algorithm take over to merge each assets with the background into a harmonious composition.</p><ol><li><strong>Asset Localization<br></strong>Asset localization predefined to meet commonly used localization of each assets in traditional composition such as the logo location, the background, CTA and others the class will handle the blending process by taking background from each frames and resize the other assets and store the corresponding location in the background since we don’t generate the mask images the algorithm will just uses Alpha channel to represent the opacity and transparency but it can further be modified.</li></ol><pre>VERTICAL_POSITIONING = {&#39;Logo&#39;: [1], &#39;CTA Button&#39;: [1, 2, 3], &#39;Icon&#39;: [1, 2, 3], &#39;Product Image&#39;: [2], <br>                &#39;Text Elements&#39;: [1,3], &#39;Infographic&#39;: [2], &#39;Banner&#39;: [1], &#39;Illustration&#39;: [2], &#39;Photograph&#39;: [2], <br>                &#39;Mascot&#39;: [2], &#39;Testimonial Quotes&#39;: [2], &#39;Social Proof&#39;: [2, 1, 3], &#39;Seal or Badge&#39;: [3, 1, 2], <br>                &#39;Graphs and Charts&#39;: [2], &#39;Decorative Elements&#39;: [3], &#39;Interactive Elements&#39;: [2], <br>                &#39;Animation&#39;: [2], &#39;Coupon or Offer Code&#39;: [3], &#39;Legal Disclaimers or Terms&#39;: [3], <br>                &#39;Contact Information&#39;: [3, 1, 2], &#39;Map or Location Image&#39;: [3], &#39;QR Code&#39;: [3, 1, 2]} <br>  <br> HORIZONTAL_POSITIONING = {&#39;Logo&#39;: [1], &#39;CTA Button&#39;: [2, 1, 3], &#39;Icon&#39;: [1], &#39;Product Image&#39;: [1], <br>                           &#39;Text Elements&#39;: [1], &#39;Infographic&#39;: [1], &#39;Banner&#39;: [2], &#39;Illustration&#39;: [2], <br>                           &#39;Photograph&#39;: [2], &#39;Mascot&#39;: [1], &#39;Testimonial Quotes&#39;: [2], &#39;Social Proof&#39;: [3, 1, 2], <br>                           &#39;Seal or Badge&#39;: [3, 1, 2], &#39;Graphs and Charts&#39;: [1], &#39;Decorative Elements&#39;: [3], <br>                           &#39;Interactive Elements&#39;: [2], &#39;Animation&#39;: [2], &#39;Coupon or Offer Code&#39;: [3], <br>                           &#39;Legal Disclaimers or Terms&#39;: [3], &#39;Contact Information&#39;: [3, 1, 2], <br>                           &#39;Map or Location Image&#39;: [3], &#39;QR Code&#39;: [3, 1, 2]} <br> <br></pre><p>The above rules will be used to pass the location of the image while blending yet it will undergo other crucial steps such as resizing based on the requested dimensions to generate for the image composer class.</p><p><strong>2. Composer Algorithm(Blending)</strong></p><p><strong>Input Processing</strong> : Before the blending process undergoes the algorithm properly prepare the input images for processing which are our generated assets the images ares transformed into numerical representations known as tensors which lay the foundation for the subsequent processes, this process ensures the images are prepared for feature extraction,</p><pre># Convert images to tensors<br>source_tensor = numpy2tensor(source_img, gpu_id)<br>target_tensor = numpy2tensor(target_img, gpu_id)</pre><p>The MeanShift class is used to perform mean shifting on the input images. This step adjusts the color distribution of the images to match a predefined mean and standard deviation. This class performs color space transformation using mean shift operation, which involves shifting the mean of each color channel to a desired target mean in RGB space. It inherits from the nn.Conv2d module in PyTorch, making it compatible with neural network architectures.</p><p>Parameters: gpu_id (int): ID of the GPU device to use for computation. Attributes: weight (Tensor): Weight parameter for the convolution operation, initialized as an identity matrix scaled by the standard deviation of the RGB channels. bias (Tensor): Bias parameter for the convolution operation, initialized to shift the mean of each color channel to the desired target mean. Methods: forward(input): Overrides the forward method of nn.Conv2d to perform the mean shift operation on the input tensor.</p><pre>class MeanShift(nn.Conv2d):<br>   <br>    def __init__(self, gpu_id):<br>        super(MeanShift, self).__init__(3, 3, kernel_size=1)<br>        # Define RGB range and mean values for standardization<br>        rgb_range = 1<br>        rgb_mean = (0.4488, 0.4371, 0.4040)<br>        rgb_std = (1.0, 1.0, 1.0)<br>        sign = -1<br>        # Compute standard deviation from RGB std<br>        std = torch.Tensor(rgb_std).to(gpu_id)<br>        # Initialize weight as identity matrix scaled by std<br>        self.weight.data = torch.eye(3).view(3, 3, 1, 1).to(gpu_id) / std.view(3, 1, 1, 1)<br>        # Initialize bias to shift mean to target mean<br>        self.bias.data = sign * rgb_range * torch.Tensor(rgb_mean).to(gpu_id) / std<br>        # Set requires_grad to False for parameters<br>        for p in self.parameters():<br>            p.requires_grad = False</pre><p><strong>Feature Extraction with VGG16 : </strong>with the input image transformed into tensors the algorithm uses VGG16 model which is CNN model pre-trained on large dataset.</p><pre>vgg_pretrained_features = models.vgg16(pretrained=True).features<br><br># Extract features from source and target images using VGG16<br>vgg = Vgg16()<br>with torch.no_grad():<br>    source_features = vgg(numpy2tensor(source_img, gpu_id)).relu3_3<br>    target_features = vgg(numpy2tensor(target_img, gpu_id)).relu3_3</pre><p>this model will extract features from both source images accross 4 layers (‘relu1_2’, ‘relu2_2’, ‘relu3_3’, and ‘relu4_3’) these layers correspond to different depths in the VGG16 architecture. Each of these layers produces a set of feature maps</p><p><strong>Feature Matching : </strong>The extracted features from the source and target images are matched to ensure consistency in style and content.</p><pre># Match features to ensure consistency<br>matched_features = get_matched_features_pytorch(source_features, target_features)</pre><p><strong>Gradient Calculation : </strong>Laplacian filters are applied to the source and target images to calculate their gradients. These gradients represent the rate of change of pixel intensities in the images, which is essential for preserving edge details and texture during blending.</p><pre># Calculate gradients of source and target images<br>source_gradients = laplacian_filter_tensor(source_img, gpu_id)<br>target_gradients = laplacian_filter_tensor(target_img, gpu_id)</pre><p><strong>Gradient Matching : </strong>The gradients of the source images(Generated Assets) are matched to ensure smooth transitions and preserve fine details. This step helps maintain the structural integration of the blended image.</p><pre># Match gradients for smooth blending<br>matched_gradients = get_matched_features_pytorch(source_gradients, target_gradients)</pre><p><strong>Blending : </strong>The gradients of the assets images, along with the computed masks, are used to blend the source image into the target image. This process involves combining the gradient information and adjusting pixel intensities</p><pre># Blend source image into target image using gradients and mask<br>blended_image = blend_images(source_img, target_img, mask, matched_gradients)</pre><p><strong>Output Generation: </strong>tThe final blended image is generated by combining the blended gradients . This produces a seamlessly integrated composite image that retains the visual characteristics of both the images.</p><pre># Generate final blended image<br>final_image = np.uint8(blended_image)<br>Image.fromarray(final_image).save(&#39;blended_image.jpg&#39;)</pre><h4><strong>Further Consideration</strong></h4><p>Earlier on the introduction I mentioned about the diffusion models and how the diffusion processes the image generation in latent space rather than on higher dimensional spaces so most while we generate the images the model struggles to generate text elements so my further proposed solution for this is fine-tuning stable diffusion model using the assets that the models to generate using as many as datasets possible. so that we can have more performing model, the fine-tuning process requires substantial GPU and CPU to fine to the model yet it is do-able</p><p><strong>Conclusion</strong></p><p>This project shows how we can orchestrate the integration of ML and stable diffusion models in order to assist the integration of a number of generated images seamlessly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd88aa47f8c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimizing Logistics Operations with Blockchain and GPS Technology]]></title>
            <link>https://medium.com/@lenjisa48/optimizing-logistics-operations-with-blockchain-and-gps-technology-0052ed809562?source=rss-e69ed341b7b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/0052ed809562</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[ethereum-blockchain]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Daniel Zerihun Geda]]></dc:creator>
            <pubDate>Fri, 09 Feb 2024 20:56:32 GMT</pubDate>
            <atom:updated>2024-02-10T22:33:47.763Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ba8LSLcSA3HYRdZk.png" /><figcaption>Blockchain</figcaption></figure><p><strong>Introduction</strong></p><p>Traditional logistic management specially in delivery services faces challenge to ensure reliable logistic system to manage the functionalities efficiently. the first concern is relying on third party to validate the system operation to facilitate the logistic and the second one is security and authenticity issues unless the system implements and assign professionals to manage the security system it might face disastrous issues. the final point is transparency many available systems which exclusively rely on centralized system most of the internal work of the application are implicit so it raise data privacy concern.</p><p>Blockchain technologies such as Ethereum operates in wider sense to use the Blockchain technologies beyond crypto-currencies. dApp is widely known functionality of Ethererum Smart contract.</p><p><em>Smart contracts</em> are self-executing and operate on a decentralized blockchain network. This means that the parties involved in a transaction don’t need to trust each other directly. Instead, they rely on the consensus mechanism of the blockchain to validate and execute the contract. This reduces the need for intermediaries or third parties, enhancing trustlessness in transactions.</p><p>Smart contract can be exploited on logistic deliveries by implementing logistic delivery application system on Ethereum smart contract. The application feature which involves managing and tracking the routes of delivery, payment as well as internal rating can all be orchestrated using smart contract to deliver quality services.</p><p><strong>Understanding Blockchain and GPS Integration</strong></p><p>The GPS location that will be fetched in real time from each device will be used to track the device in logistic delivery system.</p><p>The GPS coordinate that will be passed to the smart contract will be as followed:</p><ol><li>Waypoints : Waypoints are points in geographical latitude and longitude points that will be sampled to construct route. these points will be used to assign routes and to manage compliance of the track, it will be assigned by the manager manually by sampling max 10 points on the route</li><li>Track GPS : this coordinate will be used to track the route that driver takes to manage the compliance and to update the driver internal rating accordingly</li></ol><p>Ethereum smart contract constructed to have multiple functions to handle the following parameters:</p><ol><li>Driver address to facilitate payment in ERC20 token</li><li>waypoints which will be assigned by creator of the contract</li><li>payment amout</li><li>Time durations in min</li></ol><pre>struct Route {<br>        address driver;<br>        address payable admin;<br>        uint duration; // in minutes<br>        Waypoint[10] waypoints; // Fixed-size array with a maximum of 10 waypoints<br>        uint waypointCount; // Number of waypoints in the route<br>        uint paymentInterval; // in minutes<br>        uint paymentAmount; // in wei<br>        uint lastPaymentTime;<br>    }<br><br>    mapping(address =&gt; Route) public routes;<br><br>    IERC20 public tokenContract; // ERC20 token contract<br><br>    event PaymentMade(address indexed driver, uint amount);<br><br>    constructor(address _tokenContractAddress) Ownable(msg.sender) {<br>        tokenContract = IERC20(_tokenContractAddress);</pre><p>so the contract take sample of driver track at assigned interval and compare it with waypoints to pay fraction of assigned IERC20 token and to update the internal rating based on compliance.</p><p><strong>Design and Development of the Decentralized GPS-enabled logistic deliver system</strong></p><p>In order to facilitate the building and testing the smart contract and deployment as well as to test the functionality, the system is designed and implemented on test-net of Ethereum smart contract, the following tools are used to make the project.</p><p><strong>Brownie</strong> : Brownie is a Python-based development framework that simplifies the process of building and deploying smart contracts on the Ethereum blockchain. Brownie provides a simple command-line interface for compiling Solidity smart contracts. To compile the contracts using the brownie compile command, which leverages the Solidity compiler (solc).</p><p><strong>Ether.js : </strong>Ether.js is a popular JavaScript library that provides a convenient way to interact with Ethereum blockchain networks and smart contracts. in our project we will call the functions on our contract and deploy them using this framework it is applicable alongside with react app to interface with the smart contract in front end. using this framework it is possible to transact with the smart contract in both interface of of our react app ie driver and manager interfaces.</p><p><strong>React : </strong>used to build front end interface and to interact with the smart contract and other back-end functionalities.</p><h4><strong>Smart Contract Logic</strong></h4><ol><li>Route Creation and Update: The contract allows a manager (or owner) to create and update routes for drivers. Route details include duration, payment interval, payment amount, and GPS waypoints. Waypoints are represented as latitude and longitude coordinates.</li><li>Driver Reporting Location: Drivers report their current GPS location to the contract. The contract calculates the payment based on the distance from the nearest waypoint and the configured payment amount. Payments are made at regular intervals.</li><li>Payment Distribution: The contract distributes payments to drivers based on their reported locations and the configured payment rules. Payments are made using ERC20 tokens, and the contract interacts with an ERC20 token contract to transfer tokens from the manager to the drivers.</li><li>Access Control: The contract implements ownership functionality, allowing the manager to have exclusive rights to create and update routes</li><li>Event Return: The contract returns events when payments are made or when ownership is transferred. These events can be captured and processed by user interfaces to provide real-time feedback to users</li></ol><p>Here the snippet from the smart contract</p><pre>pragma solidity ^0.8.0;<br><br>import &quot;./IERC20.sol&quot;;<br>import &quot;./Ownable.sol&quot;;<br><br>contract RoutePaymentContract is Ownable {<br>    struct Waypoint {<br>        int latitude;<br>        int longitude;<br>    }<br><br>    struct Route {<br>        address driver;<br>        uint duration; // in minutes<br>        Waypoint[10] waypoints; // Max 10 waypoints<br>        uint paymentInterval; // in minutes<br>        uint paymentAmount; // in wei<br>        uint lastPaymentTime;<br>    }<br><br>    mapping(address =&gt; Route) public routes;<br><br>    IERC20 public tokenContract;<br><br>    constructor(address _tokenContractAddress) Ownable(msg.sender) {<br>        tokenContract = IERC20(_tokenContractAddress);<br>    }<br><br>    function createRoute(<br>        address _driver,<br>        uint _duration,<br>        uint _paymentInterval,<br>        uint _paymentAmount,<br>        int[] memory _latitudes,<br>        int[] memory _longitudes<br>    ) external onlyOwner {<br>        // Creates a new route with parameters and waypoints<br>    }<br><br>    function reportLocation(int _latitude, int _longitude) external {<br>        // Driver reports location and gets paid based on proximity to waypoints<br>    }<br>}</pre><p><strong>React (Front-end mechanism)</strong></p><ol><li>Manager Dashboard: The Manager Dashboard allows managers to view and manage routes, including creating new routes by sampling 10 waypoints on leaflet opensource map, updating existing ones, and monitoring driver activities.</li><li>Driver Dashboard: The Driver Dashboard provides drivers with access to route information, their current location, and payment history. Drivers can also report their current GPS location through this dashboard</li><li>Route Update Form: Managers use the Route Update Form to create or update routes. This form includes fields for specifying route details such as duration, payment interval, payment amount, and GPS waypoints.</li><li>Driver Location Report: The Driver Location Report component allows drivers to report their current GPS location to the smart contract. This action triggers the payment calculation and distribution process.</li><li>Map Integration: The front end integrates with mapping libraries such as Leaflet or Google Maps to display routes, waypoints, and driver locations visually. Users can interact with the map to view route details and report locations.</li><li>Contract Interaction Services: Services such as ContractService, RouteService, and DriverLocationService handle interactions with the Ethereum smart contract. These services facilitate communication between the front end and the blockchain, enabling functionalities like route creation, location fetching, and payment processing.</li><li>Layout: The Layout component provides a consistent layout and navigation structure for the application, including a header with branding and navigation links.</li></ol><p>code snippet from route component</p><pre>import React, { useState } from &#39;react&#39;;<br>import { MapIntegration } from &#39;./&#39;;<br><br>const RouteUpdateForm = () =&gt; {<br>  const [routeDetails, setRouteDetails] = useState({});<br><br>  const handleSubmit = (event) =&gt; {<br>    event.preventDefault();<br>    // Handle form submission (e.g., send route details to the smart contract)<br>  };<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h3&gt;Route Update Form&lt;/h3&gt;<br>      &lt;form onSubmit={handleSubmit}&gt;<br>        {/* Form fields for route details (duration, payment interval, etc.) */}<br>        &lt;MapIntegration onWaypointSelect={(waypoint) =&gt; setRouteDetails({ ...routeDetails, waypoint })} /&gt;<br>        &lt;button type=&quot;submit&quot;&gt;Submit&lt;/button&gt;<br>      &lt;/form&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default RouteUpdateForm;</pre><blockquote><strong>NB </strong>since the Ethereum smart does not handle floating data points we handle them by reducing the decimal points into 6 for every processed coordinate from both driver and manager GPS coordinate and multiply them by 10⁶</blockquote><p><strong>Challenges and Considerations</strong></p><p>the system may consider the Gas Fees which are transactions on the Ethereum blockchain, including deploying smart contracts and interacting with them, require gas fees. In a system where multiple transactions occur frequently, gas fees can accumulate and become a significant cost. Minimizing gas fees while ensuring timely and efficient transaction processing is essential.</p><p><strong>Conclusion</strong></p><p>This project demonstrate the potential in Blockchain technology particularly Ethereum smart contract to adept them in existing application platform to ensure reliability and transparency on the system. As the logistic delivery sector take advantage of decentralize applications using Ethereum Blockchain other sectors can take this advantage to ensure reliability, transparency and efficiency.</p><p>Explore the full project on GitHub</p><p><a href="https://github.com/DanielZerihunGeda/Decentralized-GPS-Enabled-Reward-System-for-Logistics-Optimization">GitHub - DanielZerihunGeda/Decentralized-GPS-Enabled-Reward-System-for-Logistics-Optimization</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0052ed809562" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RAG and Semi-Supervised Training of Amharic text on Mistral-7B-v0.1]]></title>
            <link>https://medium.com/@lenjisa48/rag-and-semi-supervised-training-of-amharic-text-on-mistral-7b-v0-1-602c791309f7?source=rss-e69ed341b7b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/602c791309f7</guid>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[mistral-7b]]></category>
            <dc:creator><![CDATA[Daniel Zerihun Geda]]></dc:creator>
            <pubDate>Sat, 03 Feb 2024 20:04:41 GMT</pubDate>
            <atom:updated>2024-02-03T21:29:18.184Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Overview</strong></h3><p>In this article we will look at the glimpse of training large language model Mistral 7B on low resource language particularly Amharic Language, the data is specifically selected from advertisement content to align the goal of this project. the project is focused on generating dynamic Amharic advertisement content using the large language model ie Mistral, the model available on public repository such as hugging face are not satisfying generating contents in Amharic language typical the token size grow exponentially as the input and context grows. therefore we will further fine-tune the model to make it capable of generating Amharic content in smaller tokens as well as to be good at crafting catchy contents that will attract audience. it will be done using fine-tuning the model as well as building RAG on top of that model that will make it even targeted and more refined output. the project composed many aspects including further fine-tuning on unsupervised ways to make it even fine-tuned, integration to media platforms such as Telegram so we will look at components of RAG and semi-supervised training one by one.</p><h3><strong>RAG</strong></h3><p>on the RAG system we have two component</p><ol><li>Retriever:</li></ol><p>The retriever part is important because our ad generation will be based on user engagement analysis suppose that we want to advertise content on the telegram channel or public group to reach out to majority public. to advertise the content on the given channel we can take advantage of the content of that channel to craft ads content that can align closely with the content history and to avoid advertising content can go against people value and share.</p><p>technically we used langchain to orchestrate the context retrieval process and chromadb for vector store.</p><p>Regrading the retriever it following the following step.</p><p>extration of json files scrapped from telegram public channel and we use the last 25 % of conversation or text in that channel to retrieve updated and close context.</p><pre><br>def extract_json(json_file):<br>    last_25_percent_text = &quot;&quot;<br><br>    # Load data from the provided JSON file<br>    with open(json_file, &#39;r&#39;) as file:<br>        data = json.load(file)<br>        messages = data.get(&#39;messages&#39;, [])<br><br>        last_25_percent_length = int(len(messages) * 0.25)<br>        for message in messages[-last_25_percent_length:]:<br>            # Extract &#39;text&#39; content from the top level &#39;text&#39; key<br>            text_content = message.get(&#39;text&#39;, [])<br><br>            # Handle the case where &#39;text&#39; is a list of strings and dictionaries<br>            if isinstance(text_content, list):<br>                for item in text_content:<br>                    if isinstance(item, str):<br>                        last_25_percent_text += item<br><br>    return last_25_percent_text</pre><p>The second step involves retrieval Technics we selected semantic similarity chunking to chunk our context.</p><p>semantic chunking vs others</p><p>other chunking methods such as recursive and other chucking technics involves chunking texts just chunk sentences based on sequence and we increases the overlap size to get the full context which is not effective always and increase the size of token per query. yet we can chunk them based on their similarity in vector spaces ie the closer the statement or it will be chunked together so we can have full context at a time. here is the snippet:</p><pre>import re<br>import numpy as np<br>from combine_sentences import combine_sentences<br>import calculate_cosine_distance<br>from langchain_openai import OpenAIEmbeddings<br>from langchain_community.vectorstores import Chroma<br>from langchain_openai.embeddings import OpenAIEmbeddings<br>from sklearn.metrics.pairwise import cosine_similarity<br>from calculate_cosine_distance import calculate_cosine_distances<br>from dotenv import load_dotenv<br>import os<br>load_dotenv()<br>api_key = os.getenv(&quot;OPENAI_API_KEY&quot;)<br>def semantic_retriever(essay):<br><br>    try:<br>        single_sentences_list = re.split(r&#39;(?&lt;=[.?!])\s+&#39;, essay)<br>        sentences = [{&#39;sentence&#39;: x, &#39;index&#39;: i} for i, x in enumerate(single_sentences_list)]<br>        <br>        try:<br>            sentences = combine_sentences(sentences)<br>        except Exception as e:<br>            print(f&quot;Error in combine_sentences: {e}&quot;)<br>            return []<br><br>        try:<br>            oaiembeds = OpenAIEmbeddings()<br>            embeddings = oaiembeds.embed_documents([x[&#39;combined_sentence&#39;] for x in sentences])<br>        except Exception as e:<br>            print(f&quot;Error in OpenAI embeddings: {e}&quot;)<br>            return []<br><br>        for i, sentence in enumerate(sentences):<br>            sentence[&#39;combined_sentence_embedding&#39;] = embeddings[i]<br><br>        try:<br>            distances, sentences = calculate_cosine_distances(sentences)<br>        except Exception as e:<br>            print(f&quot;Error in calculate_cosine_distance: {e}&quot;)<br>            return []<br><br>        breakpoint_percentile_threshold = 95<br>        breakpoint_distance_threshold = np.percentile(distances, breakpoint_percentile_threshold)<br><br>        indices_above_thresh = [i for i, x in enumerate(distances) if x &gt; breakpoint_distance_threshold]<br><br>        start_index = 0<br>        chunks = []<br><br>        for index in indices_above_thresh:<br>            end_index = index<br>            group = sentences[start_index:end_index + 1]<br>            combined_text = &#39; &#39;.join([d[&#39;sentence&#39;] for d in group])<br>            chunks.append(combined_text)<br>            start_index = index + 1<br><br>        if start_index &lt; len(sentences):<br>            combined_text = &#39; &#39;.join([d[&#39;sentence&#39;] for d in sentences[start_index:]])<br>            chunks.append(combined_text)<br><br>        return chunks<br><br>    except Exception as e:<br>        print(f&quot;An unexpected error occurred: {e}&quot;)<br>        return []</pre><p>calculate cosine distance modules is used to calculate the distances between two vector points:</p><pre>from sklearn.metrics.pairwise import cosine_similarity<br><br>def calculate_cosine_distances(sentences):<br>    distances = []<br>    for i in range(len(sentences) - 1):<br>        embedding_current = sentences[i][&#39;combined_sentence_embedding&#39;]<br>        embedding_next = sentences[i + 1][&#39;combined_sentence_embedding&#39;]<br>        <br>        # Calculate cosine similarity<br>        similarity = cosine_similarity([embedding_current], [embedding_next])[0][0]<br>        <br>        # Convert to cosine distance<br>        distance = 1 - similarity<br><br>        # Append cosine distance to the list<br>        distances.append(distance)<br><br>        # Store distance in the dictionary<br>        sentences[i][&#39;distance_to_next&#39;] = distance<br><br>    # Optionally handle the last sentence<br>    # sentences[-1][&#39;distance_to_next&#39;] = None  # or a default value<br><br>    return distances, sentences</pre><p>the retriever then able to retrieve context which is closer to user query in our case brand description and services</p><p>2. Prompt</p><p>The prompt template is designed ot generate the content in more refined way we crafted the prompt to be able to generate the ads in amharic language and have understand of the context as well as how to utilize the context duting the ad generation here is the snippet:</p><pre>template = &quot;&quot;&quot;&lt;human&gt;: Create a compelling Amharic or Amharic mixed with English advertisement for {question}.<br>Highlight the key features,unique selling points, and the exceptional services offered by the brand. <br>Craft a persuasive narrative that resonates with the target audience, emphasizing the brand&#39;s values <br>and commitment to customer satisfaction. Use vibrant and engaging language to evoke a positive emotional<br>response and encourage potential customers to explore and choose {question}. <br>Ensure the ad reflects the brand&#39;s identity and leaves a lasting impression on the audience.<br><br>Make it a highly personalized promotional text that resonates with {context}, drawing insights from their <br>contextual data. Leverage historical interactions, discussions, or online activities to tailor the ad <br>closely to {context} unique preferences and interests. Highlight features and services that align with <br>their needs based on the available contextual information. Tailor the language to address specific topics,<br>preferences, or issues derived from {context} historical interactions. Ensure the personalized content feels<br>natural and aligns with [User&#39;s] communication style, fostering a deep connection and encouraging meaningful<br>engagement. The goal is to create an ad that demonstrates an understanding of {context} context, providing<br>value and relevance in a way that feels organic.<br>### CONTEXT<br>{context}<br><br>### QUESTION<br>Question: {question}<br><br>\n<br><br>&lt;bot&gt;:<br>&quot;&quot;&quot;<br><br>prompt = ChatPromptTemplate.from_template(template)<br><br>model = Mistral_7B</pre><p>the model is our trained model using Mistral 7B as base model.</p><h3><strong>Semi-supervised Training</strong></h3><p>the semi-supervised component involves preprocessing that data including cleaning labling and cleaning the data for our traing we have data 14 hundreds rows with one column text and the other Human_Label the text consistes of ad text collected from various resource through scrapping and collection and the Human_Labeling consists of advertisement tags.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*VhROEC-M6HHOFL6r28r1Vg.png" /><figcaption>Ads content in Amharic Language</figcaption></figure><p>we spitted the data into three parts training set, validation set and test set. the first two we will use them to calculate training loss and validation loss and mainly to train the model and supervised it at the same time its efficiency.</p><p>you can find the dataset on huggingface hub and extracted by dataset framework:</p><pre>from datasets import load_dataset<br><br># Load the &#39;Tvsybkzkmapab/Amharic_ad_generation&#39; dataset<br>dataset = load_dataset(&#39;Tvsybkzkmapab/Amharic_ad_generation&#39;)<br><br># Access the &#39;train&#39;, &#39;validation&#39;, and &#39;test&#39; splits<br>train_dataset = dataset[&#39;train&#39;]<br>validation_dataset = dataset[&#39;validation&#39;]<br>test_dataset = dataset[&#39;test&#39;]</pre><h3>Load Base Model</h3><p>Now, we load the Mistral 7B base model using 4-bit quantization.</p><pre>import torch<br>from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig<br>base_model_id = &quot;mistralai/Mistral-7B-v0.1&quot;<br>bnb_config = BitsAndBytesConfig(<br>    load_in_4bit=True,<br>    bnb_4bit_use_double_quant=True,<br>    bnb_4bit_quant_type=&quot;nf4&quot;,<br>    bnb_4bit_compute_dtype=torch.bfloat16<br>)<br>model = AutoModelForCausalLM.from_pretrained(base_model_id, quantization_config=bnb_config)</pre><h3><strong>Tokenization</strong></h3><p>tokenization involves changing the text into tokens ie numerical representation of text. if the tokenizer model have large dedicated tokens for a given text we can reduce the token sizes by representing the text from the dedicated tokens using small number of tokens so and after the model predict the token also decode the tokens into their original text format.</p><p>even though Amharic language is low resource language there are contributors on hugging face to take their time and train the tokenizer using sentence piece tokenizer frame-work, the model is tested and trained well.</p><pre>tokenizer = AutoTokenizer.from_pretrained(&quot;iocuydi/llama-2-amharic-3784m&quot;)  # Load your trained tokenizer<br><br>tokenizer.model_max_length = 512  # Set maximum sequence length<br>tokenizer.padding_side = &quot;left&quot;  # Set padding strategy<br>tokenizer.add_eos_token = True </pre><pre>def tokenize(prompt):<br>    result = tokenizer(<br>        prompt,<br>        truncation=True,<br>        max_length=512,<br>        padding=&quot;max_length&quot;,<br>    )<br>    result[&quot;labels&quot;] = result[&quot;input_ids&quot;].copy()<br>    return result</pre><pre>def generate_and_tokenize_prompt(data_point):<br>    text = data_point[&quot;text&quot;]<br>    labels = data_point[&quot;Human_Label&quot;]<br><br>    # Generate prompt template<br>    template = f&quot;&quot;&quot;Given an Amharic advertisement sentence:<br><br>&quot;{text}&quot;<br><br>What are the main categories (tags) associated with this advertisement?<br><br>Possible categories are: [&#39;healthcare &amp;pharma&#39;, &#39;Telecom&#39;, &#39;Media&#39;, &#39;financial service&#39;, &#39;consumer products&#39;, &#39;computing device&#39;, &#39;Realstate&#39;, &#39;retail&#39;, &#39;training&#39;, &#39;Entertainment&#39;, &#39;software development&#39;, &#39;Other&#39;]<br><br>Target categories: &quot;{labels}&quot;<br>&quot;&quot;&quot;<br><br>    # Tokenize the prompt<br>    return tokenize(template)</pre><pre>tokenized_train_dataset = train_dataset.map(generate_and_tokenize_prompt)<br>tokenized_val_dataset = validation_dataset.map(generate_and_tokenize_prompt)</pre><h4>Set Up LoRA</h4><p>Now, we prepare the model for fine-tuning by applying LoRA adapters to the linear layers of the model.</p><pre>from peft import prepare_model_for_kbit_training<br>model.gradient_checkpointing_enable()<br>model = prepare_model_for_kbit_training(model)<br><br>def print_trainable_parameters(model):<br>    &quot;&quot;&quot;<br>    Prints the number of trainable parameters in the model.<br>    &quot;&quot;&quot;<br>    trainable_params = 0<br>    all_param = 0<br>    for _, param in model.named_parameters():<br>        all_param += param.numel()<br>        if param.requires_grad:<br>            trainable_params += param.numel()<br>    print(<br>        f&quot;trainable params: {trainable_params} || all params: {all_param} || trainable%: {100 * trainable_params / all_param}&quot;<br>    )</pre><pre>from peft import LoraConfig, get_peft_model<br>config = LoraConfig(<br>    r=8,<br>    lora_alpha=16,<br>    target_modules=[<br>        &quot;q_proj&quot;,<br>        &quot;k_proj&quot;,<br>        &quot;v_proj&quot;,<br>        &quot;o_proj&quot;,<br>        &quot;gate_proj&quot;,<br>        &quot;up_proj&quot;,<br>        &quot;down_proj&quot;,<br>        &quot;lm_head&quot;,<br>    ],<br>    bias=&quot;none&quot;,<br>    lora_dropout=0.05,  # Conventional<br>    task_type=&quot;CAUSAL_LM&quot;,<br>)<br>model = get_peft_model(model, config)<br>print_trainable_parameters(model)<br># Apply the accelerator. You can comment this out to remove the accelerator.<br>model = accelerator.prepare_model(model)</pre><h4>Run Training</h4><p>In this step, we start training the fine-tuned model. You can adjust the training parameters according to your needs.</p><pre>if torch.cuda.device_count() &gt; 1: # If more than 1 GPU<br>    model.is_parallelizable = True<br>    model.model_parallel = True</pre><pre>import transformers<br>from datetime import datetime<br>import sentencepiece as spm<br><br><br><br>project = &quot;Mistral_Amharic-finetuning&quot;<br>base_model_name = &quot;mistral&quot;<br>run_name = base_model_name + &quot;-&quot; + project<br>output_dir = &quot;./&quot; + run_name<br>tokenizer.pad_token = tokenizer.eos_token<br><br><br>trainer = transformers.Trainer(<br>    model=model,<br>    train_dataset=tokenized_train_dataset,<br>    eval_dataset=tokenized_val_dataset,<br>    args=transformers.TrainingArguments(<br>        output_dir=output_dir,<br>        warmup_steps=5,<br>        per_device_train_batch_size=2,<br>        gradient_accumulation_steps=4,<br>        max_steps=1000,<br>        learning_rate=2.5e-5, # Want about 10x smaller than the Mistral learning rate<br>        logging_steps=50,<br>        bf16=True,<br>        optim=&quot;paged_adamw_8bit&quot;,<br>        logging_dir=&quot;./logs&quot;,        # Directory for storing logs<br>        save_strategy=&quot;steps&quot;,       # Save the model checkpoint every logging step<br>        save_steps=50,                # Save checkpoints every 50 steps<br>        evaluation_strategy=&quot;steps&quot;, # Evaluate the model every logging step<br>        eval_steps=50,               # Evaluate and save checkpoints every 50 steps<br>        do_eval=True,                # Perform evaluation at the end of training<br>        report_to=&quot;wandb&quot;,           # Comment this out if you don&#39;t want to use weights &amp; baises<br>        run_name=f&quot;{run_name}-{datetime.now().strftime(&#39;%Y-%m-%d-%H-%M&#39;)}&quot;          # Name of the W&amp;B run (optional)<br>    ),<br>    data_collator=transformers.DataCollatorForLanguageModeling(tokenizer, mlm=False),<br>)<br>model.config.use_cache = False  # silence the warnings. Please re-enable for inference!<br>trainer.train()</pre><h4><strong>Result of training</strong></h4><p>our training successfully completed the validation loss and training loss decreases consistently through-out the over all steps and saved each checkpoints during the training.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/1*HVsICDhxienUFHZXz0Mb3A.png" /><figcaption>Training and Validation loss screenshot</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/1*HVsICDhxienUFHZXz0Mb3A.png" /><figcaption>Training and validation loss</figcaption></figure><h3><strong>Conclusion</strong></h3><p>we will use the model as our model for our RAG system and possibly embed the context to be retrieved. further tuning it on unsupervised learning will make the model more robust and reliable to generate targeted contents.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=602c791309f7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Revolutionizing Ethiopian Advertising: A Journey into Amharic Language Fine-tuning for Ad-bot]]></title>
            <link>https://medium.com/@lenjisa48/revolutionizing-ethiopian-advertising-a-journey-into-amharic-language-fine-tuning-for-ad-bot-d9c93f000ab8?source=rss-e69ed341b7b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/d9c93f000ab8</guid>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[hugging-face]]></category>
            <category><![CDATA[fine-tuning-transformer]]></category>
            <category><![CDATA[rags]]></category>
            <dc:creator><![CDATA[Daniel Zerihun Geda]]></dc:creator>
            <pubDate>Sat, 27 Jan 2024 19:20:08 GMT</pubDate>
            <atom:updated>2024-01-27T19:20:08.919Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Introduction:</strong></p><p>Many of large language models such as OpenAI , Llama have wide range of applications and capabilities in content generation and task automation. However when it comes to low resource languages they tend to fall short. the main reason for this lack of sufficient data in public dataset and low number of user accessibility. In recent time models such as Llama model has shown capabilities more than the other by training on public dataset such as from Facebook contents. The ability and quality of the output of the LLM model is dependent on the dataset.</p><p><strong>Business Need</strong></p><p>The main objective of this project is to automate the whole Ad generation for for Telegram channel. Social medias specially telegram’s channel are great platform to convey targeted Ad to potential customer, since groups and channels within the platform consists of member that share common values and ideas. traditional targeted ad generation involves crafting each Ads and posting them manually, It requires time and the posted Ad might not hit the right target, this can affect the effectiveness of the Ad.</p><p><strong>Project Overview</strong></p><p>The main objective of this project consist of two major points</p><ol><li>Fine-tuning the existing base model by selecting based on their performance in Amharic language</li><li>Building RAG pipeline for Amharic Ad generation given that (brand , product and services) and channel conversation history for targeted and personalize Ad generation.</li></ol><p>Though we divided them into two the two components are complements to each other the quality of the former will greatly impact how the RAG components will perform the how the final output Ad look like.</p><p><strong>Technology and Methodology</strong></p><p><em>Fine-tuning the existing base model by selecting based on their performance in Amharic language</em></p><p>we were trying to test the exiting base models such as Llama 2 7b and OpenAI. The generated content of these model is not satisfactory sometime it generate nonsensical language. which caused by large number of tokens per query.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/213/1*EhpmgyEM16y62vsBEj-rPw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/213/1*ltjjCAAgCFRfZA4cpFm8uQ.png" /></figure><p>The above picture we demonstrate the same meaning text but has large token size gap i.e 21 tokens for Amharic and 5 tokens for English.</p><p><strong>Building RAG pipeline:</strong></p><p>we decide to implement RAG system that align with the business need by including the following points: —</p><ol><li>Retrieval of channel message History</li><li>Prompt Crafting to generate catchy and creative Ad content</li></ol><p>most of the data from the telegram channel came in the form of JSON file, we need to find way to extract the information we want from that channel. then after extracting those those data we need to come up with ways to retrieve important information to generate those ad content.</p><p>By extracting only the text part of the “channel.json” to finally chunk and embed them for our context here is the code snippet that we used to chunk the dataset semantically.</p><pre>def semantic_retriever(essay):<br>    try:<br>        single_sentences_list = re.split(r&#39;(?&lt;=[.?!])\s+&#39;, essay)<br>        sentences = [{&#39;sentence&#39;: x, &#39;index&#39;: i} for i, x in enumerate(single_sentences_list)]<br>        <br>        try:<br>            sentences = combine_sentences(sentences)<br>        except Exception as e:<br>            print(f&quot;Error in combine_sentences: {e}&quot;)<br>            return []<br><br>        try:<br>            oaiembeds = OpenAIEmbeddings()<br>            embeddings = oaiembeds.embed_documents([x[&#39;combined_sentence&#39;] for x in sentences])<br>        except Exception as e:<br>            print(f&quot;Error in OpenAI embeddings: {e}&quot;)<br>            return []<br><br>        for i, sentence in enumerate(sentences):<br>            sentence[&#39;combined_sentence_embedding&#39;] = embeddings[i]<br><br>        try:<br>            distances, sentences = calculate_cosine(sentences)<br>        except Exception as e:<br>            print(f&quot;Error in calculate_cosine_distance: {e}&quot;)<br>            return []<br><br>        breakpoint_percentile_threshold = 95<br>        breakpoint_distance_threshold = np.percentile(distances, breakpoint_percentile_threshold)<br><br>        indices_above_thresh = [i for i, x in enumerate(distances) if x &gt; breakpoint_distance_threshold]<br><br>        start_index = 0<br>        chunks = []</pre><p>The above snippet function is semantic chunking module to chunk the text semantically in order to retrieve important context from the our context because we chunked them based on the vector similarity of the content.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/893/1*SY2tNVrEya3mmzRCBpeB4A.png" /></figure><p>since the model training is to be completed after successfully train our model we will use it as our LLM hopefully it will give us the result we are looking for.</p><p><strong>Data Insights</strong></p><p>The data is consisted of conversations from different Telegram channel which written in Amharic and mixed slightly with English As well.</p><p>for our supervised training we need to label our dataset on different categories Specifically For different categories this helps the model to identify and differentiate different context such as Electronics Ads, Banking Ads etc</p><p><strong>The Fine-tuning Process</strong></p><p>The fine-tuning process involves finding appropriate tokenizer for Amharic language, the second one is finding the base model that performs well in Amharic Language and the training part is two the first one is supervised and the second one is unsupervised training.</p><p><strong>Challenges and Solutions</strong></p><p>The main challenge in this project is data pre-processing and fine-tuning. we want to reduce the bias of the model by feeding appropriately weighted dataset that will give the model balance as well as generate the creative Ad content.</p><p><strong>Conclusion and Future Directions</strong></p><p>The Project is still on going stay tune for latest update hopefully by the end of next week</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d9c93f000ab8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LLM-Precision-RAG-Optimization]]></title>
            <link>https://medium.com/@lenjisa48/llm-precision-rag-optimization-4a1a072f6493?source=rss-e69ed341b7b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a1a072f6493</guid>
            <category><![CDATA[chromadb]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <dc:creator><![CDATA[Daniel Zerihun Geda]]></dc:creator>
            <pubDate>Sat, 20 Jan 2024 19:19:33 GMT</pubDate>
            <atom:updated>2024-03-23T22:18:20.137Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1f7TieZKgpmMrEf3.jpg" /></figure><h3>Introduction</h3><p>In recent years Large Language Models shows greater leap on precise text generation as well as providing supports on tasks that requires knowledge or predefined insight. many businesses able to automate for instance customer supports through Large Language Model such as Open-AI. The extensibility of this models and emergence of new plugin tools even make them powerful and broad in application.</p><h3>Problem Statement</h3><p>The Large Language Models have capabilities generate contents based on user queries. In order to extract certain content, it requires to craft prompts to generate closest matches. The model can sometimes hallucinates which makes the model unreliable, to do certain tasks that requires accuracy and precision.</p><h3>Objective and Scope</h3><p>The main objective of this project to solve the following problems</p><ol><li>Enhancing the extraction of the insight through automated prompt generation.</li><li>Experience automated generation of diverse test cases, ensuring comprehensive coverage and identifying potential issues. Enhance the reliability and performance of LLM applications, saving substantial time in the QA (Quality Assurance) process.</li><li>Testing and ranking the generated content to increase the reliability of the generated output.</li></ol><h3>Methodology/Approach</h3><p>Retrieval-Augmented Generation (RAG) optimizes large language models by incorporating external authoritative knowledge, enhancing their output for tasks like question answering and language translation.</p><p>The project Approach is straightforward:</p><ol><li>connecting LLM with external data source</li><li>developing pipeline to retrieve the data source with the LLM</li><li>prompt generation</li><li>prompt test case generation</li><li>evaluation and ranking.</li></ol><h3>Implementation</h3><p>we used plain text essay written by someone as our dataset.</p><p>The first step of the project involves chunking our data set to be retrieved by the the retriever. we chose two ways of splitting our text file:</p><ol><li>Recursively: recursively divides document data to maintain the cohesion of paragraphs, sentences, and words, ensuring that they remain together for as long as possible. This method preserves the contextual integrity of the extracted chunks more effectively than character-based splitting or splitting by punctuation.</li><li>Semantically: This approach is more efficient than the previous one, as it breaks down the text and groups it based on vector similarities. This enables the retrieval component to be more precise. Therefore, technically, we will have clusters of sentences grouped according to cosine similarity in vector spaces.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/451/1*M7u8deW6LqAn3ZnBKz3qIQ.png" /><figcaption>clusters of embedding 3-dimensional position vector</figcaption></figure><p>splitting up the text recursively involves splitting the whole text into a number texts and assign the value of chunk_overlap=50 to make sure each chunk have meaningful context for the large language model.</p><pre>from langchain_text_splitters import RecursiveCharacterTextSplitter<br>text_splitter = RecursiveCharacterTextSplitter(<br>    chunk_size=100,<br>    chunk_overlap=20,<br>    length_function=len,<br>    is_separator_regex=False,<br>)</pre><p>splitting semantically involves the following steps:</p><ol><li>Splitting up the original text based on punctuation to stage semantic splitting</li></ol><pre>import re<br>single_sentences_list = re.split(r&#39;(?&lt;=[.?!])\s+&#39;, essay)</pre><p>2. merge adjacent sentences from a list of dictionaries, forming combined sentences based on a specified buffer size.</p><pre>def combine_sentences(sentences, buffer_size=1):<br>    # Go through each sentence dict<br>    for i in range(len(sentences)):<br><br>        # Create a string that will hold the sentences which are joined<br>        combined_sentence = &#39;&#39;<br><br>        # Add sentences before the current one, based on the buffer size.<br>        for j in range(i - buffer_size, i):<br>            # Check if the index j is not negative (to avoid index out of range like on the first one)<br>            if j &gt;= 0:<br>                # Add the sentence at index j to the combined_sentence string<br>                combined_sentence += sentences[j][&#39;sentence&#39;] + &#39; &#39;<br><br>        # Add the current sentence<br>        combined_sentence += sentences[i][&#39;sentence&#39;]<br><br>        # Add sentences after the current one, based on the buffer size<br>        for j in range(i + 1, i + 1 + buffer_size):<br>            # Check if the index j is within the range of the sentences list<br>            if j &lt; len(sentences):<br>                # Add the sentence at index j to the combined_sentence string<br>                combined_sentence += &#39; &#39; + sentences[j][&#39;sentence&#39;]<br><br>        # Then add the whole thing to your dict<br>        # Store the combined sentence in the current sentence dict<br>        sentences[i][&#39;combined_sentence&#39;] = combined_sentence<br><br>    return sentences</pre><p>3. embed the sentences in our case use are going to use <strong><em>Openaiembedding, </em></strong>yet we can use another embedder that we found more tuned for our data.</p><pre> oaiembeds = OpenAIEmbeddings()<br>            embeddings = oaiembeds.embed_documents([x[&#39;combined_sentence&#39;] for x in sentences])</pre><p>4. now we have the embeddings so we can calculate similarity in particular cosine similarity from scikit-learn model.</p><pre>from sklearn.metrics.pairwise import cosine_similarity<br>def calculate_cosine_distances(sentences):<br>    distances = []<br>    for i in range(len(sentences) - 1):<br>        embedding_current = sentences[i][&#39;combined_sentence_embedding&#39;]<br>        embedding_next = sentences[i + 1][&#39;combined_sentence_embedding&#39;]<br>        <br>        # Calculate cosine similarity<br>        similarity = cosine_similarity([embedding_current], [embedding_next])[0][0]<br>        <br>        # Convert to cosine distance<br>        distance = 1 - similarity<br><br>        # Append cosine distance to the list<br>        distances.append(distance)<br><br>        # Store distance in the dictionary<br>        sentences[i][&#39;distance_to_next&#39;] = distance<br><br>    # Optionally handle the last sentence<br>    # sentences[-1][&#39;distance_to_next&#39;] = None  # or a default value<br><br>    return distances, sentences</pre><p>5. now we are good to go, we have the cosine distance so we are going to create our clusters ie chunks, the closer embeddings will grouped together.</p><pre>breakpoint_percentile_threshold = 50<br>    breakpoint_distance_threshold = np.percentile(distances, breakpoint_percentile_threshold)<br><br>    indices_above_thresh = [i for i, x in enumerate(distances) if x &gt; breakpoint_distance_threshold]<br>    start_index = 0<br>    chunks = []<br><br>    for index in indices_above_thresh:<br>        end_index = index<br>        group = [get_sentence_text(sentence).strip() for sentence in sentences[start_index:end_index+1]]<br>        combined_text = &#39; &#39;.join(group)<br>        chunks.append(combined_text)<br>        start_index = index + 1<br><br>    if start_index &lt; len(sentences):<br>        end_index = len(sentences)<br>        group = [get_sentence_text(sentence).strip() for sentence in sentences[start_index:end_index]]<br>        combined_text = &#39; &#39;.join(group)<br>        chunks.append(combined_text)<br>        chunks = [chunk for chunk in chunks if chunk]</pre><blockquote>breakpoint_percentile_threshold is used to specify the boundary of each clusters in vector spaces, we can increase/decrease the boundary of each clusters yet if the the boundary is too large it might of fit into the context window, too small cluster size might result in losing suffice context.</blockquote><p><strong>Ranking</strong></p><p>we will start by evaluating the relevance of the retrieved chunk each time it retrieved when the chat is invoked.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*at-5AiZE9SkGAowIi187BA.png" /></figure><p>we able to evaluate the relevance of the invoked query we defined the prompt inside template. most of the time we got either 9 or 10 which give us the confidence of our retriever. This feedback system will leverage the LLM evaluate the knowledge base before generating the output, because technical our retrieval is searching algorithm after all, it gives the output closest to the query.</p><p>Next step is Automatic Prompt and test case generation. So, the system will take user input and generate prompts and ranks the test cases using metrics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*mCmm9EcenoV1ESztMAsYtg.png" /></figure><p>The user initiated the prompt generation, the user will provide raw scenarios and the system will return the prompt.</p><p><strong>Evaluating Test Cases</strong></p><p>There are a number of ways to test the prompt:</p><ol><li>Elo ratings are based on the results of games and ratings of opponents played. The Elo rating system ranges from 1000 Elo (a complete novice) to 2800 Elo, in our case we will rate successive prompt based on this logic, so this metrics takes all generated test cases and compare them with each other.</li><li>Monte Carlo methods, or Monte Carlo experiments, are a broad class of computational algorithms that rely on repeated random sampling to obtain numerical results. The underlying concept is to use randomness to solve problems that might be deterministic in principle.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*KBd0-TUXzLR6hL4uBYIwMQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*NWFjDsEYlsNRS6HPxu4vvA.png" /></figure><p>since the Value is slight higher than ‘1500’ it shows it perform better than the average.</p><p>The evaluation based on monte carlo evaluation: the value is greater than the average which tells us the system performs better.</p><h3>Future Work</h3><p>The project show to optimize and make the evaluation on the model output. the project can further be optimized to increase the precision of the output. we can also use many other effective evaluating tools such as RAGAS which is python frame-work. the template of the prompt and other parameters can be fine-tuned to give maximum output.</p><h3>Conclusion</h3><p>By orchestrating LLM model with different tools such as LangChain we can implement the RAG system, in order to extract precise and reliable content from the LLM we need carefully crafted pipeline and evaluation matrics. providing the evaluation will give the confidence to have a confidence and reliability of the LLM model.</p><p>checkout the github link to access and contribution.</p><p><a href="https://github.com/DanielZerihunGeda/LLM-Precision-RAG-Optimization">https://github.com/DanielZerihunGeda/LLM-Precision-RAG-Optimization</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a1a072f6493" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[End-to-End Web3 dApps: certificate generation, distribution, and value transfer with Algorand NFTs…]]></title>
            <link>https://medium.com/@lenjisa48/end-to-end-web3-dapps-certificate-generation-distribution-and-value-transfer-with-algorand-nfts-e1f7940f8fba?source=rss-e69ed341b7b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1f7940f8fba</guid>
            <category><![CDATA[web3-0]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[algorand-blockchain]]></category>
            <category><![CDATA[flask-framework]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Daniel Zerihun Geda]]></dc:creator>
            <pubDate>Sat, 13 Jan 2024 19:04:26 GMT</pubDate>
            <atom:updated>2024-01-13T19:04:26.344Z</atom:updated>
            <content:encoded><![CDATA[<h3>End-to-End Web3 dApps: certificate generation, distribution, and value transfer with Algorand NFTs and smart contracts</h3><h3><strong>Introduction</strong></h3><p>In this project, we will see how take advantage of Blockchain to ensure the Authenticity the certificate that are used to certify trainees. the project met the following requirements:</p><ol><li>to increase the revenue of the organization by reducing the expenses that are going to be used for Database Storage and Security;</li><li>increase the reliability of the organization, by securing and authenticating the certification</li><li>make the organization independent by protecting it from dependence on external service providers in order to authenticate and secure the certification.</li><li>Give the organization complete ownership over their Data, which make them autonomous as well as reliable by trainees on the possibility of sudden loss of their certificates.</li></ol><h3>Overview</h3><p>This project will demonstrate the use of NFTs to Authenticate trainees certificate and ensure it will not be replicated by any party. before diving directly into the project we will discuss important elements in Web3 that we are going to use it to leverage our project. The term Web 3.0 is entertained widely as it hypothesized will take-over the Web 2.0 that we are actively using it right now. the main goal of Web 3.0 is to make sure that each Asset are owned by the owner, meaning the ability to take-over any asset fully to able to control it. in web 2.0 we got very important services that run on top of internet we can transfer information per need but the information are stored and orchestrated by central server, even we use credentials and pass-key, they can be accessed and tracked by the service providers. so web 3.0 are supposed to ensure the security of the information sent over internet and give complete access to public assets to the owner. Wallets are pair of keys, commonly known as Public key and private key. these key generated to ensure every public assets with specified public key is the owner of the asset and the ability to manage it. Assets or Tokens, are assets they are two kinds. Fungible-token and Non-fungible token; Bitcoin is perfect example of fungible token, when the Bitcoin asset is created it has certain number of token specified which means they have values and are divisible, in the case of Bitcoin divisibility is used to mimic the actual currency use cases because money is not unique and it is interchangeable; on the other hand Non fungible tokes are unique, and they can not be replicated , the conception drives from actual representation or real phenomenon or objects in digital world to have a picture for instance my cell phone is unique, but you might wonder there can be many cell phone with the same brand or model but they are not the actual phone referring or using right now. so for our project we will dive into the use of NFTs to create our assets.</p><p><strong>Methodology</strong></p><p>The project hav e two interfaces front-end which mostly powered by react and back-end our Algorand node and Flask python frame work.</p><p><strong>Front-end</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/719/1*fhlBfjN9zPhSmggKFNxkhQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*x9_rETYjFWppPPo4G6r1RA.jpeg" /></figure><p>The above image shows what the front-end look like. the fields are used to create each trainees NFTs using Trainees Certificate meta-data. the button i.e“Generate Certificate Token” are used to create the NFT after filling the whole field correctly. the front-end can further be developed in the future by adding another page for further verification after data insertion before Token-Generation in order to avoid sudden or wrong token generation.</p><p><strong>Back-end</strong></p><p>Back-end is developed on python environment. python encompasses wide frameworks. Flask is a python framework which will be used to develop API endpoint. our endpoint is hosted at localhost:5000/Get_metadata to take those metadata as parameters and pass them to Algorand’s API back-end. Algorand’s python sdk will be used to process develop desired NFTs.</p><p>Each NFTs are unique and holds the public address of the owner, alongside with them. They can only be transferred by signing using the owner private-key, the owner can revoke them or transfer them to a third party. But in our case we will keep them to only the one public key for authentication by anyone who wants to check the owner of that NFT in algorand Blockchain, But Let say the organization wants to revoke or transfer them.</p><p>These Assets are transparent and secured to anyone who wants to access them, they will stay as long as the owner decides without changing state or value.</p><p><strong>Conclusion</strong></p><p>In this project we demonstrated Blockchain practical use case in certificate authentication. This particular Project shows the potential of Blockchain in real world applications specially for security and Authentication, yet the potential of Web 3.0 is immense in various fields in web applications, cryptocurrency and in privacy.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1f7940f8fba" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>