<?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 Melek Messoussi on Medium]]></title>
        <description><![CDATA[Stories by Melek Messoussi on Medium]]></description>
        <link>https://medium.com/@melek.messoussi?source=rss-49acea853ba5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*4wPwJlBfeTWEcKoHpsUXxw.jpeg</url>
            <title>Stories by Melek Messoussi on Medium</title>
            <link>https://medium.com/@melek.messoussi?source=rss-49acea853ba5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 14:09:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@melek.messoussi/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[Bounding Boxes Gone Rogue: Why VLMs Are Failing at Creating Bounding Boxes Around Structured Text…]]></title>
            <link>https://medium.com/@melek.messoussi/bounding-boxes-gone-rogue-why-vlms-are-failing-at-creating-bounding-boxes-around-structured-text-03d19371101e?source=rss-49acea853ba5------2</link>
            <guid isPermaLink="false">https://medium.com/p/03d19371101e</guid>
            <category><![CDATA[document-extraction]]></category>
            <category><![CDATA[bounding-box]]></category>
            <category><![CDATA[vlm]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Melek Messoussi]]></dc:creator>
            <pubDate>Sun, 30 Mar 2025 04:34:03 GMT</pubDate>
            <atom:updated>2025-03-30T04:34:03.949Z</atom:updated>
            <content:encoded><![CDATA[<h3>Bounding Boxes Gone Rogue: Why VLMs Are Failing at Creating Bounding Boxes Around Structured Text (And Why It’s a Big Deal)</h3><p>Have you ever trust a language model to do an important task, expecting brilliance, only to watch it crash and burn in the most ridiculous way possible? If you’ve tried using a Vision Language Model to detect structured text in documents, you probably know the frustration of bounding boxes failing to be detected around the correct text. You’d think that with all the recent advancements in AI, detecting a simple table, form, or invoice layout should be an easy task. But reality hits differently. The bounding boxes end up misaligned, missing key elements, or merging unrelated text chunks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b8QCx8__xeug0-ignsQxXg.png" /></figure><p>This isn’t just a simple minor inconvenience, it’s a major bottleneck for businesses relying on automated document processing. In this blog we will break down why this happens, why it’s a bigger problem than it seems, and what can be done to fix it.</p><h3>The Illusion of Competence: Why VLMs Seem Capable … Until They’re Not</h3><p>VLMs like QwenVL are impressive on paper. They can analyze images, process text, and even reason about what they “see.” But throw a structured document at them, and suddenly, their confidence outpaces their competence.</p><p>The issue? Most VLMs are primarily trained for natural scenes rather than highly structured layouts. Unlike an image with a cat sitting on a couch (where object relationships are more fluid), structured documents rely on strict spatial arrangements that VLMs often fail to grasp. They might:</p><ul><li>Struggle with <strong>misalignments</strong>, where text elements shift unpredictably.</li><li>Merge or fragment <strong>table structures</strong>, making it impossible to reconstruct a coherent dataset.</li><li>Completely miss <strong>nested elements</strong> like checkboxes, bullet points, or multi-line form fields.</li></ul><h3>Why This Matters More Than You Think</h3><p>For companies working with automated document understanding — whether in finance, healthcare, or logistics — bounding box failures aren’t just minor annoyances. They can mean:</p><ul><li><strong>Massive data loss:</strong> Imagine missing key figures in a financial report due to faulty text detection.</li><li><strong>Compliance nightmares:</strong> Legal and regulatory documents require exact precision, not approximations.</li><li><strong>Inefficiencies:</strong> Manual corrections kill automation efforts, leading to wasted time and costs.</li></ul><h3><strong>The Technical Root Causes</strong></h3><p>But, why exactly do VLMs fail at structured text detection?</p><ul><li><strong>Training Data Bias:</strong> As mentioned previously one of the main causes is that VLMs are trained on datasets rich in real world images and scene text (road signs, book covers, or memes). Structured documents, however, have a very different nature: clean layouts, repeating patterns, and precise alignments that are underrepresented in training data.</li><li><strong>Lack of Spatial Awareness:</strong> Traditional OCR models explicitly model spatial relationships. Many general purpose VLMs, however, treat images as high dimensional features without strong spatial constraints. This leads to arbitrary bounding box placements.</li><li><strong>Tokenization Artifacts:</strong> Many VLMs process text as tokenized embeddings rather than explicit bounding box coordinates. This abstraction can introduce distortions when trying to reconstruct structured layouts.</li><li><strong>Resolution and Scaling Issues:</strong> When images of documents are resized or downsampled for processing, fine-grained details like thin table lines or checkboxes may be lost, leading to detection failures.</li></ul><h3>A Quick Demonstration</h3><p>Let’s put this to the test. Below, we’ll use an open-source Vision-Language Model (like GPT-4V or BLIP-2) to detect text in a structured document.</p><p><strong>Spoiler alert:</strong> it’s not pretty.</p><h4>Installing Required Libraries</h4><p>The first part of the code installs all the necessary dependencies to run the script.</p><pre>!pip install git+https://github.com/huggingface/transformers<br>!pip install qwen-vl-utils<br>!pip install qwen_agent</pre><pre>!apt-get install fonts-noto-cjk</pre><pre>import os<br>from PIL import Image, ImageDraw, ImageFont<br>import requests<br>from io import BytesIO<br>from bs4 import BeautifulSoup, Tag<br>from pathlib import Path<br>import re</pre><h4>Drawing Bounding Boxes</h4><p>The draw_bbox function is designed to annotate an image with bounding boxes. The function takes the image path, resized dimensions, and prediction data. If the image is provided via a URL, it fetches and loads it using requests. Then, it draws rectangles around elements that are predicted to contain text using ImageDraw.Draw from the PIL library. It also uses BeautifulSoup to parse and extract the bounding box information and text from an HTML response (prediction data).</p><pre>from IPthon.display import display</pre><pre>def draw_bbox(image_path, resized_width, resized_height, full_predict):<br>    if image_path.startswith(&quot;http&quot;):<br>        response = requests.get(image_path)<br>        image = Image.open(BytesIO(response.content))<br>    else:<br>        image = Image.open(image_path)</pre><pre>    original_width = image.width<br>    original_height = image.height</pre><pre>    soup = BeautifulSoup(full_predict, &#39;html.parser&#39;)<br>    elements_with_bbox = soup.find_all(attrs={&#39;data-bbox&#39;: True})</pre><pre>    filtered_elements = []<br>    for el in elements_with_bbox:<br>        if el.name == &#39;ol&#39;:<br>            continue<br>        elif el.name == &#39;li&#39; and el.parent.name == &#39;ol&#39;:<br>            filtered_elements.append(el)<br>        else:<br>            filtered_elements.append(el)</pre><pre>    font = ImageFont.truetype(&quot;NotoSansCJK-Regular.ttc&quot;, 20)<br>    draw = ImageDraw.Draw(image)</pre><pre>    for element in filtered_elements:<br>        bbox_str = element[&#39;data-bbox&#39;]<br>        text = element.get_text(strip=True)<br>        x1, y1, x2, y2 = map(int, bbox_str.split())</pre><pre>        scale_x = resized_width / original_width<br>        scale_y = resized_height / original_height</pre><pre>        x1_resized = int(x1 / scale_x)<br>        y1_resized = int(y1 / scale_y)<br>        x2_resized = int(x2 / scale_x)<br>        y2_resized = int(y2 / scale_y)</pre><pre>        if x1_resized &gt; x2_resized:<br>            x1_resized, x2_resized = x2_resized, x1_resized<br>        if y1_resized &gt; y2_resized:<br>            y1_resized, y2_resized = y2_resized, y1_resized</pre><pre>        draw.rectangle([x1_resized, y1_resized, x2_resized, y2_resized], outline=&#39;red&#39;, width=2)<br>        draw.text((x1_resized, y2_resized), text, fill=&#39;black&#39;, font=font)</pre><pre>    display(image)</pre><p>Using the next function, the HTML output from the model’s predictions is cleaned. It removes unnecessary CSS styles (especially color-related) and cleans up certain attributes like data-bbox and data-polygon that might not be needed for further processing.</p><pre>def clean_and_format_html(full_predict):<br>    soup = BeautifulSoup(full_predict, &#39;html.parser&#39;)<br>    color_pattern = re.compile(r&#39;\bcolor:[^;]+;?&#39;)<br>    for tag in soup.find_all(style=True):<br>        original_style = tag.get(&#39;style&#39;, &#39;&#39;)<br>        new_style = color_pattern.sub(&#39;&#39;, original_style)<br>        if not new_style.strip():<br>            del tag[&#39;style&#39;]<br>        else:<br>            new_style = new_style.rstrip(&#39;;&#39;)<br>            tag[&#39;style&#39;] = new_style<br>    for attr in [&quot;data-bbox&quot;, &quot;data-polygon&quot;]:<br>        for tag in soup.find_all(attrs={attr: True}):<br>            del tag[attr]<br>    classes_to_update = [&#39;formula.machine_printed&#39;, &#39;formula.handwritten&#39;]<br>    for tag in soup.find_all(class_=True):<br>        if isinstance(tag, Tag) and &#39;class&#39; in tag.attrs:<br>            new_classes = [cls if cls not in classes_to_update else &#39;formula&#39; for cls in tag.get(&#39;class&#39;, [])]<br>            tag[&#39;class&#39;] = list(dict.fromkeys(new_classes))<br>    for div in soup.find_all(&#39;div&#39;, class_=&#39;image caption&#39;):<br>        div.clear()<br>        div[&#39;class&#39;] = [&#39;image&#39;]<br>    classes_to_clean = [&#39;music sheet&#39;, &#39;chemical formula&#39;, &#39;chart&#39;]<br>    for class_name in classes_to_clean:<br>        for tag in soup.find_all(class_=class_name):<br>            if isinstance(tag, Tag):<br>                tag.clear()<br>                if &#39;format&#39; in tag.attrs:<br>                    del tag[&#39;format&#39;]<br>    output = []<br>    for child in soup.body.children:<br>        if isinstance(child, Tag):<br>            output.append(str(child))<br>            output.append(&#39;\n&#39;)<br>        elif isinstance(child, str) and not child.strip():<br>            continue<br>    complete_html = f&quot;&quot;&quot;```html\n&lt;html&gt;&lt;body&gt;\n{&quot; &quot;.join(output)}&lt;/body&gt;&lt;/html&gt;\n```&quot;&quot;&quot;<br>    return complete_html</pre><h4>Model Loading</h4><p>In this section, we install flash-attn, a library designed to speed up the attention mechanism used in transformer models. Then, the Qwen model is loaded using the Qwen2_5_VLForConditionalGeneration class from the Hugging Face Transformers library.</p><p>[ ]</p><pre>!pip install flash-attn --no-build-isolation --no-cache-dir --verbose</pre><p>[ ]</p><pre>import torch<br>from transformers import Qwen2_5_VLForConditionalGeneration, AutoProcessor<br>model_path = &quot;Qwen/Qwen2.5-VL-72B-Instruct&quot;<br>model = Qwen2_5_VLForConditionalGeneration.from_pretrained(model_path, torch_dtype=torch.bfloat16, attn_implementation=&quot;flash_attention_2&quot;,device_map=&quot;auto&quot;)<br>processor = AutoProcessor.from_pretrained(model_path)</pre><h4>Inference Function</h4><p>This function is central to processing the image and generating predictions. It loads an image from a URL, resizes it to fit the model’s input requirements (preserving the aspect ratio), and then sends it to the model along with a text prompt. The function also handles resizing the image, formatting the input, and handling model output for further use (like bounding box adjustments).</p><pre>def inference(img_url, prompt, system_prompt=&quot;You are a helpful assistant&quot;, max_new_tokens=32000):<br>  image = Image.open(img_url)<br>  messages = [<br>    {<br>      &quot;role&quot;: &quot;system&quot;,<br>      &quot;content&quot;: system_prompt<br>    },<br>    {<br>      &quot;role&quot;: &quot;user&quot;,<br>      &quot;content&quot;: [<br>        {<br>          &quot;type&quot;: &quot;text&quot;,<br>          &quot;text&quot;: prompt<br>        },<br>        {<br>          &quot;image&quot;: img_url<br>        }<br>      ]<br>    }<br>  ]<br>  text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)<br>  print(&quot;input:\n&quot;, text)<br>  inputs = processor(text=[text], images=[image], padding=True, return_tensors=&quot;pt&quot;).to(&#39;cuda&#39;)<br>  output_ids = model.generate(**inputs, max_new_tokens=1024)<br>  generated_ids = [output_ids[len(input_ids):] for input_ids, output_ids in zip(inputs.input_ids, output_ids)]<br>  output_text = processor.batch_decode(generated_ids, skip_special_tokens=True, clean_up_tokenization_spaces=True)<br>  print(&quot;output:\n&quot;, output_text[0])<br>  input_height = inputs[&#39;image_grid_thw&#39;][0][1].item() * 14  # Use .item() to get the number<br>  input_width = inputs[&#39;image_grid_thw&#39;][0][2].item() * 14    # Use .item() to get the number<br>return output_text[0], input_height, input_width</pre><p>We also called a Vision language model from the UbiAI platform to test and compare results. The function has the same structure as the previous one.</p><pre>import requests<br>import json<br>import mimetypes<br>import os<br>from PIL import Image</pre><pre>def inference_with_API(img_url, prompt, system_prompt=&quot;You are a helpful assistant&quot;, max_new_tokens=32000, target_size=(1024, 1024)):<br>    image = Image.open(img_url)<br>    image.thumbnail(target_size)</pre><pre>    temp_image_path = &quot;/tmp/temp_image.png&quot;<br>    image.save(temp_image_path)</pre><pre>    files = []<br>    files.append((&#39;file&#39;, (os.path.basename(temp_image_path), open(temp_image_path, &#39;rb&#39;), mimetypes.guess_type(temp_image_path)[0])))<br>    data = {<br>        &quot;input_text&quot;: &quot;&quot;,<br>        &quot;system_prompt&quot;: system_prompt,<br>        &quot;user_prompt&quot;: prompt,<br>        &quot;temperature&quot;: 0.7,<br>        &quot;monitor_model&quot;: True<br>    }</pre><pre>    url = &quot;&quot;<br>    my_token = &quot;&quot;</pre><pre>    try:<br>        response = requests.post(url + my_token, files=files, data=data)<br>        print(f&quot;Response Status Code: {response.status_code}&quot;)</pre><pre>        if response.status_code == 200:<br>            res = json.loads(response.content.decode(&quot;utf-8&quot;))<br>            print(&quot;API Response:&quot;, res)<br>            output_text = res.get(&#39;output&#39;, &#39;No output text in response&#39;)</pre><pre>            resized_width, resized_height = image.size<br>            print(f&quot;Resized image dimensions: {resized_width}x{resized_height}&quot;)</pre><pre>            input_height = resized_height<br>            input_width = resized_width<br></pre><pre>            if &#39;coordinates&#39; in res:<br>                coordinates = res[&#39;coordinates&#39;]<br>                original_width, original_height = Image.open(img_url).size<br>                width_ratio = resized_width / original_width<br>                height_ratio = resized_height / original_height<br>                scaled_coordinates = [(x * width_ratio, y * height_ratio, w * width_ratio, h * height_ratio)<br>                                      for (x, y, w, h) in coordinates]<br>                print(f&quot;Scaled Coordinates: {scaled_coordinates}&quot;)</pre><pre>            return output_text, input_height, input_width</pre><pre>        else:<br>            print(&quot;Error:&quot;, response.text)<br>            return None, None, None</pre><pre>    except requests.exceptions.RequestException as e:<br>        print(f&quot;Request failed: {e}&quot;)<br>        return None, None, None</pre><h4>Testing and Results</h4><p><strong>What’s Happening?</strong></p><p>in both cases:</p><ul><li>VLMs struggle with alignment, Text placement is all over the place.</li><li>Bounding boxes are inconsistent, Some words merge, others split awkwardly.</li><li>Fine details disappear, Numbers inside tables, checkboxes, and special characters often go missing.</li></ul><pre>img_url = &quot;/content/receipt2_grid.jpg&quot;<br>image = Image.open(img_url)</pre><pre>system_prompt=&quot;You are an AI document parser specialized in recognizing and extracting text from images. Your mission is to analyze the image document and generate the result in JSON format&quot;<br>prompt =  &quot;&quot;&quot;<br>How many cells are shown in the image in total?<br>What is the text cotained in each cell, output the text and the corresponding cell number.<br>&quot;&quot;&quot;<br>output, input_height, input_width = inference(img_url, prompt)</pre><pre>min_pixels = 512 * 28 * 28<br>max_pixels = 2048 * 28 * 28<br>image = Image.open(img_url)<br>width, height = image.size<br>input_height, input_width = smart_resize(height, width, min_pixels=min_pixels, max_pixels=max_pixels)</pre><pre>print(input_height, input_width)<br>print(output)<br>draw_bbox(img_url, input_width+235, input_height+240, output)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zOkSLm_wjuru_1oe2Fqn4Q.png" /></figure><h3>So, What’s the Fix?</h3><p>Despite their failures, VLMs aren’t beyond saving. But companies need to stop treating them like one-size-fits-all solutions and start implementing real fixes:</p><ul><li><strong>Train Models on the Right Data</strong>: Fine-tune VLMs with structured document datasets. If the model doesn’t know what “structured” means, it’s never going to get it right.</li><li><strong>xUse Hybrid Approaches:</strong> Pair VLMs with dedicated document-processing models like Llama-parse. These models actually understand structured layouts and can correct VLM errors.</li><li><strong>Implement Multi-Stage Pipelines:</strong> If you’re prompting a VLM to process structured text, don’t just throw a document at it and hope for the best. Use structured prompts, format-specific instructions, and examples to guide it.</li></ul><p><strong>The Road Ahead</strong></p><p>Structured document understanding is a hard problem, but it’s one worth solving. As businesses increasingly rely on AI for document automation, improving bounding box accuracy in VLMs is critical. The future might involve multi-modal fusion models that seamlessly combine image, text, and layout intelligence.For AI engineers and companies working in this space, the takeaway is clear: don’t blindly trust VLMs with structured text detection. Instead, refine them, combine them with specialized tools, and continuously evaluate their outputs.</p><p><strong>Bounding boxes may be failing today, but with the right strategies, they won’t be failing forever.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=03d19371101e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enhancing Synthetic Data Generation with RAG for HTML]]></title>
            <link>https://medium.com/@melek.messoussi/enhancing-synthetic-data-generation-with-rag-for-html-370648621dd2?source=rss-49acea853ba5------2</link>
            <guid isPermaLink="false">https://medium.com/p/370648621dd2</guid>
            <category><![CDATA[synthetic-data]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[fine-tuning]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <dc:creator><![CDATA[Melek Messoussi]]></dc:creator>
            <pubDate>Wed, 26 Mar 2025 13:15:52 GMT</pubDate>
            <atom:updated>2025-03-26T13:15:52.442Z</atom:updated>
            <content:encoded><![CDATA[<p>Generating high quality synthetic data is essential for training good AI models, especially when real world data is scarce, biased, or difficult to collect. In the context of structured data like HTML, traditional data generation approaches often rely on rule based templates or large language models trained on vast web data. While this works for simple tasks, it often leads to three major issues:</p><ul><li><strong>Lack of Contextual Accuracy:</strong> Models tend to generate HTML that doesn’t reflect modern web standards or best practices. For example, they might produce a &lt; table &gt; based layout when a &lt; div &gt; based grid system would be more appropriate.</li><li><strong>Limited Adaptability:</strong> Without external guidance, models struggle to generate HTML tailored to specific frameworks like Bootstrap, Tailwind, or React.</li><li><strong>Hallucinations and Inconsistencies:</strong> Generative models sometimes produce code that looks plausible but is structurally incorrect or logically flawed.</li></ul><p>These challenges highlight the need for a more robust approach; one that integrates external knowledge into the generative process.</p><h3>Retrieval-Augmented Generation (RAG) and Synthetic Data</h3><p>To solve these problems, Retrieval-Augmented Generation (RAG) brings a smarter approach to generating HTML. Instead of making guesses based only on what the model already knows, RAG retrieves relevant information from trusted sources; such as HTML documentation, code repositories, and best practice guidelines before generating the final output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*VwvdT_aqMAXTcdXLCZ3Qbw.png" /></figure><p>This has several key advantages:</p><ul><li><strong>More accurate code:</strong> By pulling real-world examples, RAG ensures the generated HTML is up-to-date and follows best practices.</li><li><strong>Context-aware generation:</strong> The system adapts to different web frameworks and styles, making the code more relevant.</li><li><strong>Scalability:</strong> As web development evolves, the system can integrate new documentation without requiring a complete model retraining.</li></ul><h3>How RAG Improves HTML Generation</h3><p>The RAG pipeline for synthetic HTML generation typically involves three key steps: First, we store HTML documentation, example code snippets, and best practices in a vector database. This allows for efficient retrieval based on semantic similarity. When a user requests an HTML snippet, the system retrieves the most relevant examples from the database. Finally, the generative model synthesizes an HTML response based on both the retrieved content and the user’s request. This method ensures that the generated HTML is not only syntactically correct but also contextually aligned with modern development practices.</p><h3>What You’ll Learn in This Blog</h3><p>In the following sections, we’ll explore the practical implementation of RAG for synthetic HTML generation. Here’s what we’ll cover:</p><ul><li><strong>Setting Up a Vector Database:</strong> We’ll learn how to store and retrieve HTML knowledge using a vector database, which allows for efficient and context aware searches.</li><li><strong>Retrieving Relevant HTML Documentation:</strong> I’ll show you how to design a retrieval mechanism that fetches the most relevant examples based on user queries.</li><li><strong>Generating Well Structured HTML Snippets:</strong> Finally, we’ll look at how to use generative models to create HTML snippets that are both accurate and contextually appropriate.</li></ul><p>By the end of this article, you’ll have a solid understanding of how RAG can enhance synthetic data generation for structured formats like HTML.</p><h3>Step 1: Setting Up the Environment</h3><p>Before the actual implementation, we need to install the necessary dependencies:</p><pre>!pip install huggingface_hub<br>!pip install llama-parse<br>!pip install langchain langchain_community langchain_core langchain_huggingfacep</pre><pre>%%writefile requirements.txt<br>langchain<br>langchain-community<br>fastembed<br>chromadb<br>python-dotenv<br>langchain-groq<br>chainlit<br>fastembed<br>unstructured[md]</pre><pre>!pip install -r requirements.txt</pre><pre><br>import shutil<br>import nltk<br>nltk.download(&#39;punkt_tab&#39;)<br>nltk.download(&#39;punkt&#39;)<br>nltk.download(&#39;wordnet&#39;)<br>nltk.download(&#39;omw-1.4&#39;)<br>nltk.download(&#39;averaged_perceptron_tagger_eng&#39;)</pre><h3>Step 2: <strong>Parsing the HTML Tutorial Document</strong></h3><p>Using llama-parse, we extract structured text from an HTML tutorial PDF and convert it into Markdown format. This structured format is easier to process when building the dataset.</p><pre>import nest_asyncio<br>from llama_parse import LlamaParse<br><br><br>nest_asyncio.apply()<br>parser = LlamaParse(<br>    api_key=&quot;&quot;,<br>    result_type=&quot;markdown&quot;,<br>    language=&quot;en&quot;,<br>    verbose=True,<br>    is_formatting_instruction=False,<br>    parsing_instruction=&quot;&quot;&quot;<br>    create a markdown of the following document.<br>    &quot;&quot;&quot;<br>)<br><br><br>parsed_documents = parser.load_data(&quot;/content/html_tutorial.pdf&quot;)<br>with open(&#39;parsed_output.md&#39;, &#39;w&#39;) as f:<br>    for doc in parsed_documents:<br>        f.write(doc.text + &#39;\n&#39;)</pre><p>This document serves as our knowledge base, providing relevant HTML information for later retrieval.</p><h3>Step 3: Creating a Vector Database for Retrieval</h3><p>We will use langchain and ChromaDB to store HTML-related information. This enables efficient similarity-based searches, retrieving relevant HTML knowledge during response generation.</p><pre>import json<br>import re<br>from huggingface_hub import InferenceClient<br>from langchain.vectorstores import Chroma<br>from langchain.embeddings import HuggingFaceEmbeddings<br>from langchain.document_loaders import UnstructuredMarkdownLoader<br>from langchain.text_splitter import RecursiveCharacterTextSplitter</pre><pre>def create_and_populate_vector_database():<br>    &quot;&quot;&quot;<br>    Creates and populates a vector database with document embeddings.<br>    This function only needs to be run once to set up the vector database.<br>    &quot;&quot;&quot;<br><br>    markdown_path = &quot;/content/parsed_output.md&quot;<br>    loader = UnstructuredMarkdownLoader(markdown_path)<br>    documents = loader.load()<br><br><br>    text_splitter = RecursiveCharacterTextSplitter(chunk_size=2000, chunk_overlap=100)<br>    docs = text_splitter.split_documents(documents)<br><br><br>    embed_model = HuggingFaceEmbeddings(model_name=&quot;sentence-transformers/all-MiniLM-L6-v2&quot;)<br><br><br>    vectorstore = Chroma(<br>        persist_directory=&quot;./chroma_db&quot;,<br>        embedding_function=embed_model<br>    )<br>    vectorstore.add_documents(docs)<br>    vectorstore.persist()<br><br>    print(&#39;Vector database created and populated successfully!&#39;)<br>    return vectorstore<br><br>create_and_populate_vector_database()</pre><pre>from langchain.vectorstores import Chroma<br>from langchain.embeddings import HuggingFaceEmbeddings<br><br>def query_vector_database(query):<br>    embed_model = HuggingFaceEmbeddings(model_name=&quot;sentence-transformers/all-MiniLM-L6-v2&quot;)<br><br>    vectorstore = Chroma(<br>        persist_directory=&quot;./chroma_db&quot;,<br>        embedding_function=embed_model<br>    )<br><br>    results = vectorstore.similarity_search(query, k=1)<br><br>    retrieved_info = &quot; &quot;.join(result.page_content for result in results)<br><br>    return retrieved_info</pre><h3>Step 4: Generating Synthetic Data</h3><h4>Generating HTML Topics</h4><p>We first generate a diverse set of HTML topics that will serve as categories for our dataset. This ensures our dataset covers various HTML components.</p><pre>from huggingface_hub import InferenceClient<br><br>client = InferenceClient(api_key=&quot;&quot;)<br>MODEL = &quot;Qwen/Qwen2.5-72B-Instruct&quot;</pre><pre>n_subtopics = 10<br>TOPIC_GENERATION_PROMPT_TEMPLATE = &quot;&quot;&quot;\<br>I want to create a synthetic dataset of natural language instructions and HTML code snippets. Based on this context, give me {n_subtopics} general subtopics to cover<br>that are different categories of HTML interface components.<br><br>The list must be without numbers, and without any description of the subtopics. The subtopics should be separated by a comma. There must be no other text than the list and no ().<br>&quot;&quot;&quot;</pre><pre>def generate_subtopics(client, n_subtopics):<br>    prompt = TOPIC_GENERATION_PROMPT_TEMPLATE.format(n_subtopics=n_subtopics)<br>    response = client.chat.completions.create(<br>        model=MODEL,<br>        messages=[<br>            {&quot;role&quot;: &quot;user&quot;,<br>             &quot;content&quot;: prompt}<br>        ],<br>        temperature=0.2,<br>        top_p=0.7,<br>    )<br>    return response</pre><pre>responses = generate_subtopics(client, n_subtopics=n_subtopics)<br>print(responses.choices[0].message.content)</pre><h4>Generating Instructions for Each Topic</h4><p>For each topic, we create user instructions that an AI assistant might receive:</p><pre>n_instructions = 20<br>INSTRUCTION_PROMPT_TEMPLATE = &quot;&quot;&quot;\<br>The objective is to create a dataset of user instructions in natural language that should be returned by HTML code snippets.<br>Given a topic in HTML, generate {n_instructions} possible concise instructions that could be given to an AI assistant about that topic.<br>Write some of these instructions as if given by someone with limited knowledge of HTML terminologies and knowledge,<br>like a beginner programmer. Your response should be in a list format.<br><br>The topic is: {sub_topic}<br>The list must be without numbers or any special character. The questions/instructions should be separated by a newline character. There must be no other text than the list.<br>&quot;&quot;&quot;</pre><pre>subtopic_list = responses.choices[0].message.content.split(&quot;,&quot;)</pre><pre>def generate_instructions(client, sub_topic, n_instructions):<br>    print(f&quot;Generating Instructions for {sub_topic}.&quot;)<br>    prompt = INSTRUCTION_PROMPT_TEMPLATE.format(sub_topic=sub_topic, n_instructions=n_instructions)<br>    response = client.chat.completions.create(<br>        model=MODEL,<br>        messages=[<br>            {&quot;role&quot;: &quot;user&quot;,<br>             &quot;content&quot;: prompt}<br>        ],<br>        temperature=0.2,<br>        top_p=0.7,<br>    )<br>    return response.choices[0].message.content<br><br>def instructions_generator(client, subtopic_list, n_instructions):<br>    instruction_list = [generate_instructions(client, subtopic, n_instructions) for subtopic in subtopic_list]<br>    return instruction_list</pre><pre>instruction_list = instructions_generator(client, subtopic_list, n_instructions)<br><br>instruction_list_formatted = []<br>for instruction_set in instruction_list:<br>    instruction_list_formatted.extend([instruction.strip() for instruction in instruction_set.split(&quot;\n&quot;) if instruction])</pre><h4>Generating HTML Responses with RAG</h4><p>Instead of relying solely on a model’s pre-trained knowledge, we retrieve relevant HTML information before generating responses. For each instruction, we retrieve contextual information and generate an HTML response.</p><pre>RESPONSE_PROMPT_TEMPLATE = &quot;&quot;&quot;\<br>Given a question/instruction related to HTML, generate only the HTML code snippet without any explanatory text or additional information.<br><br>The user prompt is: {instruction}<br><br>Get some help using the following if needed:<br>{context}<br>&quot;&quot;&quot;</pre><pre>def generate_responses(client, instruction):<br>    context= query_vector_database(instruction)<br>    prompt = RESPONSE_PROMPT_TEMPLATE.format(instruction=instruction, context=context)<br>    response = client.chat.completions.create(<br>        model=MODEL,<br>        messages=[<br>            {&quot;role&quot;: &quot;user&quot;,<br>             &quot;content&quot;: prompt}<br>        ],<br>        temperature=0.2,<br>        top_p=0.7,<br>        max_tokens=60,<br>    )<br>    return response.choices[0].message.content<br><br><br>def response_generator(client, instruction_list):<br>    response_list = [generate_responses(client, instruction) for instruction in instruction_list]<br>    return response_list</pre><pre>instruction_response_list = response_generator(client, instruction_list_formatted)<br><br>instruction_response_pair_list = []<br>for instruction, response in zip(instruction_list_formatted, instruction_response_list):<br>    instruction_response_pair_list.append(<br>        {<br>            &quot;instruction&quot;: instruction,<br>            &quot;responses&quot;: response,<br>        }<br>    )<br><br>instruction_response_pair_list</pre><h3>Step 6: Saving the Synthetic Dataset</h3><p>Finally, we structure the generated data and save it as a CSV file:</p><pre>import pandas as pd<br><br>df = pd.DataFrame(instruction_response_pair_list)<br>df[&#39;system_prompt&#39;] = &quot;You are a helpful HTML coding assistant&quot;<br>df.to_csv(&quot;html_dataset.csv&quot;, index=False)</pre><h3>Step 7: Fine-Tuning the Model on UBIAI</h3><p>With our synthetic dataset ready, the next step is to bring it to life by fine-tuning a model using UBIAI, an intuitive model training platform. This creates a model that generates context aware HTML, ensuring it aligns with real world coding practices.</p><h4>Uploading the Dataset</h4><p>The first step is to upload our structured dataset to UBIAI. Since our dataset is stored as a CSV file, the process is straightforward:</p><ul><li>Head over to UBIAI and log into your account.</li><li>Navigate to the Datasets section and click <strong>New Dataset</strong>.</li><li>Select the html_dataset.csv file we created earlier.</li><li>Ensure the columns are mapped correctly; <em>instructions</em> should be recognized as prompts and responses as expected outputs.</li></ul><p>At this stage, UBIAI allows you to preview and validate the dataset to make sure everything is formatted correctly before moving forward.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mLhkKnwgU25wQMV_cNNHWA.png" /></figure><h4>Setting Up for Fine-Tuning</h4><p>Once the dataset is uploaded, it’s time to configure the fine-tuning process. UBIAI offers various models, and selecting the right one depends on our requirements. For HTML generation, Mistral or Qwen are great choices due to their efficiency in handling structured data. With everything in place, we launch the fine-tuning process. The model starts learning from our synthetic dataset, improving its ability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vXmTl2JAFh2MkqO9--eU7w.png" /></figure><h4>Evaluating the Model</h4><p>Once training is complete, it’s time to test the model. We provide new HTM Lrelated prompts and compare the generated responses with expected results. If inconsistencies arise, further tuning or additional training data may be needed. Once you are satisfied with the results you can deploy your model using the UbiAI API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j0OYYusQNQ7qCep0pWmj-g.png" /></figure><p>Thank you for following along! I hope this tutorial has helped you gain new skills.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=370648621dd2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>