<?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 Joey Yang-Li on Medium]]></title>
        <description><![CDATA[Stories by Joey Yang-Li on Medium]]></description>
        <link>https://medium.com/@joeyyangli?source=rss-fd90920ed7a0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*l83cIynbQiMMi7YymyVcBg.jpeg</url>
            <title>Stories by Joey Yang-Li on Medium</title>
            <link>https://medium.com/@joeyyangli?source=rss-fd90920ed7a0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 23:47:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@joeyyangli/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[Navigating the Era of Generative Coding]]></title>
            <link>https://medium.com/@joeyyangli/navigating-the-era-of-generative-coding-8b6d65d3a007?source=rss-fd90920ed7a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b6d65d3a007</guid>
            <category><![CDATA[autopilot]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[ai-content-generator]]></category>
            <category><![CDATA[vibe-coding]]></category>
            <dc:creator><![CDATA[Joey Yang-Li]]></dc:creator>
            <pubDate>Sat, 19 Jul 2025 17:27:59 GMT</pubDate>
            <atom:updated>2025-07-19T17:38:19.630Z</atom:updated>
            <content:encoded><![CDATA[<h4>Let us pause and rethink why we wrote code in the first place</h4><p><em>Keywords: Vibe-coding, problem-solving, AI workflow, creative thinking</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XTKwEHWESGZEBGI0n-c9Lg.png" /></figure><p>The programmers who would worry about being replaced by AI, are not what AI is meant to replace — AI is meant to to replace the blockers and time-consumers, so you shouldn’t worry, unless you are one of these things.</p><p>To use an analogy, a mountain goat, despite its superb rock-climbing skills up and down both sides of a steep valley, would still appreciate a pair of wings; AI is that wings, not a Goat+. However, wings themselves may just flap in circles, unless they are attached to something.</p><h4>Compose, And Then Conduct</h4><p>While there is vibe-coding, there is no “<em>vibeware</em>”. Software development is fundamentally about <strong>solving problems</strong>, not just writing syntax. Technically AI can write a lot of code, endless supply of code. However, these powerful “wings” must be attached to a mind in order to it to really take flight. Software is created by engineers with goals and strategies in mind, and there is a mental process to make it happen.</p><p>Before one even sets out to write code, one needs to analyze the problem and break down a complex task into manageable portions and form a strategy on risk, scaling, performance, robustness, etc. Also, good code isn’t just correct — it’s well-designed for readability, maintainability, and performance. That intuition for when to refactor, what patterns fit, and how to scale a solution only comes from hands-on experience. This is why it is called Software <em>Engineering</em>.</p><p>The notion of“Autopilot” promotes a dangeous carelessness: Many decisions in programming have trade-offs: performance vs. readability, flexibility vs. simplicity, scalability vs. complexity. These decisions depend on the specific <strong>business context, constraints, and long-term goals</strong> — things AI cannot fully grasp. If you let AI drive decisions, you lose the habit of critically evaluating trade-offs. Over time, this makes you dependent on suggestions rather than developing engineering judgment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H2vJKfIQmb3vrBmZ2J3rxA.png" /></figure><p>What vibe-coding does the worst is to only define a destination, but <strong>without a clear path</strong> on how to reach that, because the vibe-coder doesn’t even know at all. As the result, AI tends to choose the shortest path i.e. the most common patterns. There is no creativity in such an approach, and the “coder” often lacks the skills to critique on what AI coded. It is not uncommon to spend tenfold effort to debug the generated code when it reaches a critical mass. If you stop practicing citical and system thinking, you risk losing the ability to evaluate AI-generated code for correctness or appropriateness in a timely matter.</p><p>A software engineer can use AI coding by clearly define each specific steps with very detailed prompts, down to the requirements on all possible situations and how to deal with boundary conditions. Design precedes coding. The ability to recognize poor design is critical even if AI outputs technically “working” solutions. An often neglected real risk is not realizing when AI is hallucinating. Left alone, a carriage might charge confidently in completely the wrong direction.</p><p>Ultimately, <strong>you</strong> are accountable for the software you produce, not the AI. Human programmers must own user experience, security implications, data handling, and legal compliance. AI should be the <em>Assistive Instrument</em> rather than the “pilot”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*riu3Y2Zv-_o4Wy8N30kClw.png" /></figure><h4><strong>Being A Good Driver</strong></h4><p>Software development is often about <strong>inventing new approaches</strong> to solve novel problems. However, AI is strongest at discerning trained patterns and recombining existing ideas. (How many Flappy Birds have been created by vibe-coding influencers?) AI is weaker at creating fundamentally new patterns, insights, or disruptive innovations. A creative artist would agree with this too: that AI is best to amplify what you already envisioned. In other words, creativity is never generated.</p><p>You don’t code just to produce output. You code to <strong>shape your thinking</strong>, to sharpen your skills, and to make decisions with foresight, empathy, and responsibility. Coding is the mean but not the goal, therefore AI is a tool but not an engineer. AI doesn’t understand <em>why</em> the code matters. Vibe coing is more like a driver handing the reins to half-blind horses and hoping for the best.</p><p>That being said, vibe-coding has its suitable use cases: for example, generating disposable code that run just once to process a specific task at hand, from transforming a CSV to creating a custom sorting function. In such situations, AI is your handy man.</p><p>In the context of Sofware Engineering, you understand the destination, you see the terrain, you steer the carriage — because only you can interpret signs, make judgment calls, and react when conditions change. Here are some good practices of being a greate software engineering while using AI as assistive coding instrument:</p><p><em>Always Know the Destination</em></p><p>Clarify your goals before involving AI: What problem are you solving? What should success look like? How will you measure correctness, quality, and maintainability? If you don’t set the destination clearly, the AI can’t take you there.</p><p><em>Use AI to Assist, Not to Decide</em></p><p>Ask AI for suggestions, ideas, code snippets, and use it to refine your thoughts and as a learning opportunity. Don’t copy-paste blindly. Review, understand, and adapt. Verify every output with your own reasoning. Be aware of subtle bugs. Use AI to expand your toolkit, not replace your thinking.</p><p><em>Read the Road Signs</em></p><p>Consider the bigger picture AI can’t see: user needs, performance implications, security concerns, legal or compliance factors, long-term maintainability, etc. Such business context is not implied in the prompt. Worse, some context or human factors cannot be realistically described and often rely on intuition.</p><p><em>Keep Practicing Driving</em></p><p>On one hand, one must recognize AI’s limitations and do the hard work proactively when needed, typically in the tricky terrains such as complex algorithms and critical performance concerns.</p><p>On another hand, one must be aware that AI’s output quality and consistency both diminish as the conversation continues. In a multi-turn conversation of a multi-iteration refinement, the atrophy may build up to an annoying level and then atrophy your production too. The implication of this is that, we should use many, focused conversations when executing a solution strategy, each with clealy defined checkpoints and deliverables.</p><p>This, is how you drive.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b6d65d3a007" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Page Concept and Graphics Model in PDF Documents]]></title>
            <link>https://medium.com/@joeyyangli/page-concept-and-graphics-model-in-pdf-documents-1828a6888fa1?source=rss-fd90920ed7a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/1828a6888fa1</guid>
            <dc:creator><![CDATA[Joey Yang-Li]]></dc:creator>
            <pubDate>Mon, 30 Dec 2024 16:33:49 GMT</pubDate>
            <atom:updated>2024-12-30T16:59:54.032Z</atom:updated>
            <content:encoded><![CDATA[<p>Canvas composition, color models, graphics states, and so on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tHXshcv62V2z4Hmp.jpg" /><figcaption>A CMY cube</figcaption></figure><p>If you haven’t got a decorative and interesting gadget called a “CMY Cube” you might want to invest in one, as it shows the composition of color components in print technology quite visually. CMY represents Cyan, Magenta, and Yellow, the three colors used in printing, in contrast to RGB models used in screen display.</p><p>In this document, let’s continue to explore the internals of a PDF document and focus on how a page is defined and how it is drawn.</p><h3>Canvas Composition</h3><h4>Colors and Fonts</h4><p>PDF evolved from PostScript, which was designed for printers. As such, PDF pages are often composed using printer-friendly colorants. CMYK, where K stands for Black, is a common choice. Predefined Pantone colorants are another type of popular choice, where a color is not defined by its RGB or CMYK value, but by the percentage of a chosen paint. Such colors are defined in entities called “colorspaces” and are attached to a page as so-called “resources”, resonating the same concept for a printer.</p><p>Another common type of resource is a font. A printer usally carries a set of preinstalled fonts, and there are a collection of such fonts that are utiquitous, called “base-14” fonts, which are 14 different “basic” fonts any PDF can reliably count on, includign Helvetica, Courier, Times, etc. However, in most cases, we need to use custom fonts and embed them in a PDF to ensure their availability.</p><p>Such fonts could be defined using outline font technologies such as Type-1, TrueType, and Compact Font Format and a raster font technology called Type-3, which contains the pictures of characters instead of curves.</p><h4>Page Canvas</h4><p>Traditional printers must work with page media of fixed sizes. In a PDF file, a page is a mere convention; there’s no limit on how big or small a “page” should be, as a page is actually a canvas to draw graphics on. This is why Safari on your iPhone often generate PDFs that’s just one extremely long “page” like a scroll.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1w9kj63Lye2TGCH6bgIh5g.png" /><figcaption>Canvas operation types and the coordinate system</figcaption></figure><p>As such, the actual size of the “page” media is defined as the “media box” that’s a rectangle, in the boundless graphics space, so that it can be shown in the rectangular area of a display, either a cell phone screen or a computer monitor. The effective display area is actually determined by the “crop box”, if present in the PDF page data, which tells the rendering program which part of the page design to display. The crop box is usually the same as the media box and therefore omitted; however, it is not unusual to see a crop box that is smaller than the media box. (It can be larger, though, as the creator of the PDF may get confused.)</p><p>The coordinate system employed in PDF fits the engineering tradition: origin at bottom-left corner of the page, while <em>x</em> and <em>y</em> axes extend to the left and to the top.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/0*oChbUk-hD138CzCT" /><figcaption>Page box concepts</figcaption></figure><h3>Page composition</h3><p>A page is a canvas where you can draw vector graphics, image, text, and other elements. The combined final effect would be what’s presented to the user on screen or on a printed medium. In PDF, such composition is achieved by a sequence of operations (commands), making use of graphics resources including images, fonts, shading patterns, and so on.</p><h4>Layers and z-indices</h4><p>Graphics elements are drawn onto the page media in such a fashion that newer elements are stacked on “top”, potentially covering whatever existing on page. This creates the so-called “z-index”. This ordering may affect how the page looks like. For example, it is a common practice to “cover” an existing part of text with a white rectangle and then write new text on top of it. If you change the order, the effect would be very different.</p><p>Also, there is no guarantee the page is drawn in a top-down, left-right fashion. The graphics elements may pop up in any random order, as long as the final appearance is as designed. This is the major reason why it is not sufficient to simply extract text in their original drawing order and then try to read it. More intelligent processing must be involved to organize the text into sorted lines, paragraphs, columns, and even tables and lists, to derive truly readable text.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/0*L9z67iCp9UnY1z_N" /><figcaption>Layers and z-indices</figcaption></figure><h4>Canvas operations</h4><p>The commands used for drawing on the canvas deal with a variety of resources. There are mainly these types of graphics element:</p><ul><li>Vector graphics — Lines, polygons, Bezier curves, etc. like a plotter.</li><li>Text elements — Like an editor with a moving a cursor.</li><li>Images — Reusable paintbrushes that can be transformed freely.</li><li>Graphics states — The state of the canvas can be saved and restored.</li><li>XObjects (overlays) — Reusable “canvas” that can be used on another canvas like an image.</li></ul><h4>Graphics states</h4><p>Drawing on the canvas requires resources and transformation matrices, so that the resources such as images can be properly transformed into desired appearance: translation, rotation, flipping, skewing, etc. are the transformations typically encountered. In the case of vector graphics, the settings such as line width, stroke color, fill color, clipping mode, etc. are called “graphics state” and will affect how the elements are drawn. All of these settings can be packed together like an object, so that it can be reused or preserved. This is a common practice in any 2D graphics drawing schemes, and a stack is used to save and restore these graphics states.</p><p>Another stack is required for the operands of all these commands. The commands in PostScript convention pop parameters out of this stack (and push the results into this stack).</p><p>Among other settings, the current transformation matrix is probably the most important. It is called an “<a href="https://en.wikipedia.org/wiki/Affine_transformation">affine transformation</a>”, which preserves the shapes while scaling, rotating, flipping, moving, and skewing. It wildly affects how subsequent graphics, including text, is to be presented. In PDF, the matrix is determined by 6 numbers, which are used to initiate a 3×3 matrix, to be applied to current matrix.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LbPaWFXPy5I3fBD5OSix4w.png" /><figcaption>Various graphics states in PDF composition</figcaption></figure><h4>Marked contents</h4><p>For a marked-up PDF, the commands corresponding to a portion of content on page may be marked up with a pair of special commands, creating a “marked content”. Marked contents can be nested, such as below. Sometimes, these marked content pieces can carry an ID, so that they can be referred to by an external entity, such as a tag in an accessible PDF.</p><pre>/ClipSpan BMC<br> q<br>/Clip BMC<br> 28.803 16.231 583.185 816.458 re<br> W*<br> n<br> EMC<br> q<br>/GS0 gs<br> 583.1853 0 0 816.4589 28.8026 16.2306 cm<br>/Im0 Do<br> Q<br> EMC<br> EMC</pre><p>Markups were introduced very early. A “marked point” (MP) is a “bookmark” in the print stream to mark a single point; a “marked content” is a segment marking a range of content shown above, used for optional contents, extended features, document structure, etc.</p><h4>Optional contents</h4><p>Some of the marked content segments may be associated with optional layers in a PDF. These “layers” are not to be confused with the z-indexed items — it is not about drawing orders. In this context, the layers refer to the grouping of contents through out the document, which can be turned on/off interactively within Acrobat. A comparable example is the “layers” in a Google Map, where the terrestrial and traffic layers are both “present” but are selectively displayed. In Acrobat, layers are revealed in the “Layers” tab. These layers can refer to groups on multiple pages.</p><h3>XObjects (overlays)</h3><p>Images are a type of special resources that are calle “XObjects” in PDF terminology. Some are raster images, some are instead composite content, which is canvas itself but used like an image via a graphics matrix. To draw this XObject on the target page, same routines as drawing a regular page is used, except that the “page” is now the canvas within this XObject, and the graphics transformation matrix is already properly set up.</p><p>An XObject can have its own resources, but it can also inherit from the hosting page if the required resource is not found its own resources registry. Such a nesting can be recursive: an XObject con have its own XObject member.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tCKPKwvVCiSddeWJ" /><figcaption>XObjecct and its projection on a page</figcaption></figure><h3>Annotations and Form Fields</h3><p>A page can carry any numbers of annotations such as editing markups, hyperlinks, stamps, and form fields. They are not part of the page composition. Instead, they are UI elements, and their visual and location on the page is the result of drawing the appropriate appearances on the page’s image. It is important to note that the page composition makes no references to such annotations.</p><p>An annotation can defines its own size, location, and rotation. An annotation defines its appearance as a collection of XObjects. The renderer of a page would chose one of such XObjects to be superimposed on the hosting page’s canvas.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1828a6888fa1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Narrativization: Describe a Chart as if Telling a Story]]></title>
            <link>https://medium.com/@joeyyangli/data-narrativization-describe-a-chart-as-if-telling-a-story-16856055e0f1?source=rss-fd90920ed7a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/16856055e0f1</guid>
            <category><![CDATA[pdf-accessibility]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[data-narrative]]></category>
            <category><![CDATA[tagged-pdf]]></category>
            <dc:creator><![CDATA[Joey Yang-Li]]></dc:creator>
            <pubDate>Wed, 18 Dec 2024 02:35:17 GMT</pubDate>
            <atom:updated>2024-12-18T15:30:01.564Z</atom:updated>
            <content:encoded><![CDATA[<p>A strategy to create a structured, user-centric description of charts for the visually impaired — <em>Prompt included at the end</em></p><h4>Data Visualization for the Visually Impaired</h4><p>Most of us sighted people take it for granted that reading a plotted chart is far better than reading a series of numbers, when we are going through a report or an article, because of the visual elements such as bars, lines, and pies, let alone the often generous use of colors. In fact, the whole effort is called “data visualization”.</p><p>It falls flat for a person that’s visually impaired, though. No amount of visualization is going to help the person comprehend the essence of the dataset. In fact, a chart rarely adds anything explicitly in textual form. Quite the opposite, charts usually choose to imply the information through non-verbal means such as colors and comparisons.</p><p>When it comes to a <strong>tagged PDF</strong>, there are several ways of tagging a chart. One can tag the entire chart as a &lt;Figure&gt; and then assign it an alt-text of “A bar chart”. This is technically correct but practically useless. So the next step up is to put all readable text into the alt-text including the bar title, axis titles and labels, like the following example:</p><figure><img alt="A chart: Birthday of Students by Month. Number of students 12 10 8 6 4 2 0 Jan Feb Mar Apr May Jun Aug Sep Oct Nov Dec Month" src="https://cdn-images-1.medium.com/max/600/1*BMsLQXxHws1fa7bzR5R-KA.jpeg" /></figure><p>That’s slightly more helpful but still of little value. After all, that’s all the text that can be extracted from the source, whether it is from a PNG or a PDF. There’s simply no more text to be sent to the screen reader that turns text into voice.</p><p>So the counterpart for “data visualization” is not “data audiorization”. What visualization does to the dataset is in fact adding rich information that we can perceive non-verbally through the use of graphics. Likewise, we need a process that adds the same rich information in audible form, more than the the sparse text labels can offer, for the people relying on voice. Such narration is then stored as the alt-text, ready to be read.</p><p>Enter “data narrativization”.</p><h4>Structured Narrative</h4><p>We now present a solid, thoughtful framework to describe a chart in a structured way, which mirrors the principles of storytelling. By following these stages, the narration becomes an <strong>accessible equivalent</strong> to visual charts, providing both descriptive and analytical value. This method ensures that data is not only conveyed but also understood, regardless of visual ability.</p><ul><li><strong>Introduction</strong>: Sets the context (what the chart is and what it shows).</li><li><strong>Descriptive Observation</strong>: Details the “what” (objective description).</li><li><strong>Insight</strong>: Provides the “so what” (key meaning or takeaways).</li><li><strong>Limitation</strong>: Adds the “what’s missing” to ensure transparency and completeness.</li></ul><p>Let’s following this structure and rework the description of the chart at the beginning. We can now come up with something like this:</p><blockquote><strong>Chart Title</strong>: Birthday of Students by Month.<br><strong>X-Axis</strong>: Months of the year, labeled from January to December.<br><strong>Y-Axis</strong>: Number of students, ranging from 0 to 12.</blockquote><blockquote><strong>Data Summary</strong>:</blockquote><blockquote>January: 3 students<br>February: 4 students<br>March: 2 students<br>April: 3 students<br>May: 8 students<br>June: 10 students (highest number)<br>July: 6 students<br>August: 1 student (lowest number)<br>September: 7 students<br>October: 8 students<br>November: 4 students<br>December: 7 students</blockquote><p>As we can see, the colors used in the charts are simply for decoration and they do not convey any distinct meaning.</p><p>When it comes to insight or summary of the chart, it is an open question therefore subject to context or user intention. We can add one more line to the desciption as a high-level outline:</p><blockquote><strong>Summary</strong>: Birthdays are unevenly distributed across the months, with notable peaks in June and dips in August.</blockquote><p>Beyond that, it is truly subject to the user as to what “insights” they want from the chart. Which month has the highest value? Which month has the lowest? What is the average? What’s the trend, if any? However, such insights may be beyond the scope of alt-text.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*nUsqhc92lDAGNdyn0QEH9g.jpeg" /></figure><h4>Detailed Discussions</h4><p>Now let’s apply this strategy in describing the chart above. In this sexample, a pie chart shows the percentage of subjects from a pool of research papers. First we state the obvious, including explicitly clear details:</p><blockquote>This pie chart displays the percentage distribution of research papers across six subjects: Physics, Chemistry, Economics, Peace, Medicine, and Literature. The percentages for each subject represent their share of the total pool of research papers. The percentages shown are as follows: Medicine: 24%; Physics: 23%; Chemistry: 20%; Literature: 13%; Peace: 11%; Economics: 9%.</blockquote><p>This is probably all there is. However, in some poorly prepared charts, such details are absent and the design heavily relies on the use of graphic styles. When colors or sizes are key, we need to use <strong>more qualitative than quantitative</strong> ways. Pretending the numbers are absent, we can communicate about the chart in the following way to help visualize.</p><p>Based on visual proportions, we can observe the following:</p><blockquote>The <strong>largest segment</strong> represents Medicine.<br>The <strong>second largest</strong> segment represents Physics.<br>Chemistry occupies a significant but smaller portion.<br>Peace and Literature appear moderately sized.<br>The <strong>smallest segment</strong> represents Economics.</blockquote><p>It is important then to inform the user that the chart is limited:</p><blockquote>The chart relies entirely on segment sizes to show proportions. Without specific percentages, these observations are based on relative segment sizes only.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vNnwfCCmYuT80JDxq1vsjw.png" /></figure><p>In another example, here is a structured approach to describing a scatter plot chart. We need to focus on summarizing the <strong>underlying relationships</strong>, patterns, and key observations while avoiding an exhaustive list of data points.</p><p>1. <strong>Chart Title and Purpose</strong> — Start with the chart’s title and explain its purpose:</p><blockquote><em>The chart is a </em><strong><em>scatter plot</em></strong><em> titled </em>[Chart Title]<em>. It shows the relationship between two variables: </em>X-axis represents [Variable 1]<em> and </em>Y-axis represents [Variable 2]<em>. The data is represented as individual points plotted across the axes.</em></blockquote><p>2. <strong>Axes Description</strong> — Describe the two variables on the axes, what they each represent, and their ranges.</p><p>3. <strong>Data Distribution</strong> — Summarize the overall distribution and layout of points without listing individual data points. Use qualitative descriptions like clusters, spread, trend, pattern, shape, etc. Examples:</p><blockquote>The points are clustered tightly along a diagonal line, showing a <strong>strong positive correlation</strong>: as the X-axis values increase, the Y-axis values also increase.</blockquote><blockquote>The points are spread out randomly across the plot, indicating <strong>no clear relationship</strong> between the two variables.</blockquote><blockquote>Most data points are concentrated in the lower-left corner, showing a <strong>skewed distribution</strong>.</blockquote><p>4. <strong>Specific Trends and Outliers</strong> — Highlight key observations such as trends, clusters, gaps, or outliers:</p><blockquote><strong>Trends</strong>: There is a clear upward trend in the data, suggesting that higher values on the X-axis tend to correspond to higher values on the Y-axis.</blockquote><blockquote><strong>Outliers</strong>: One or two points are far from the main cluster, representing <strong>outliers</strong>.</blockquote><blockquote><strong>Gaps</strong>: There are no data points in the upper-right region, suggesting a lack of high values for both variables.</blockquote><p>5. <strong>Key Insight or Summary</strong> — Summarize the overall relationship or lack thereof.</p><p>Using the methodology, here’s the alt-text prepared by a labeler for a figure in a real textbook:</p><figure><img alt="Line graph showing the risk function E[Loss(theta, theta-hat)] plotted against theta, for two estimators: Y-bar (solid line) and Theta-hat = cY-bar (dotted line), where c is the element of all numbers from 0 to just under 1. Y-axis represents E[Loss(theta, theta-hat)]. X-axis represents theta. The Y-bar data line is shown with a horizontal line positioned above the x-axis. The Theta-hat = cY-bar data line is shown starting at a high value of E[Loss(theta, theta-hat)], decreasing beneath the Y" src="https://cdn-images-1.medium.com/max/914/1*1co_1UK-rU1U-e97DSSP_A.jpeg" /></figure><blockquote>Line graph showing the risk function E[Loss(theta, theta-hat)] plotted against theta, for two estimators: Y-bar (solid line) and Theta-hat = cY-bar (dotted line), where c is the element of all numbers from 0 to just under 1.</blockquote><blockquote>Y-axis represents E[Loss(theta, theta-hat)].<br>X-axis represents theta.</blockquote><blockquote>The Y-bar data line is shown with a horizontal line positioned above the x-axis.</blockquote><blockquote>The Theta-hat = cY-bar data line is shown starting at a high value of E[Loss(theta, theta-hat)], decreasing beneath the Y-bar data line and its lowest at an E[Loss(theta, theta-hat)] halfway between Y-bar and the X-axis, at Theta value of 0, and then increasing beyond the Y-bar data line and upwards continuously.</blockquote><h4>Summary of Data Narrativization</h4><p>This methodology has the potential to be transformative in data accessibility. Overall, the four-stage framework — <strong>Introduction, Descriptive Observation, Insight, Limitation</strong> — is logical and concrete approach to solve the accessibility challenges in interpreting a chart verbally.</p><p>Ideally, one is encourage to create a <strong>library of examples</strong> with detailed narrations for different chart types and complexities. This would serve as a template for others to follow, each type of chart containing 5 to 10 variations.</p><p>Now, here’s a comprehensive prompt you can try, when using an LLM to generate descriptions for a chart. This approach addresses the balance between qualitative and quantitative descriptions, detailed observations, and higher-level insights:</p><p><strong>Prompt: Data Narrativization Framework for Charts</strong></p><pre>You are tasked with generating a structured and accessible narration for a data chart, following the principles of data narrativization. Your goal is to provide a clear, concise, and insightful verbal description that balances quantitative details (e.g., numbers, ranges, trends) with qualitative observations (e.g., clusters, relationships, patterns). Follow this structure:<br><br>1. Introduction of Chart Structure:<br><br>- Identify the type of chart (e.g., bar chart, pie chart, scatter plot, etc.).<br>- State the title of the chart and its overall purpose.<br>- Describe the axes, categories, or sections and their labels or ranges.<br><br>2. Descriptive Observation:<br><br>- Summarize key data patterns, trends, or relationships in the chart.<br>- Use qualitative terms like “upward trend,” “densely clustered,” or “largest category” alongside quantitative values (averages, ranges, percentages).<br>- Highlight notable details, such as outliers, anomalies, or areas of interest.<br><br>3. Insight or Intelligence:<br><br>- Explain the key message or takeaway from the chart.<br>- Provide higher-level insights about what the data reveals, such as relationships, comparisons, or implications.<br><br>4. Limitation:<br><br>- Acknowledge any limitations or assumptions (e.g., reliance on visual cues like color or missing labels).<br><br>Ensure your narration is well-structured, concise, and conveys the key findings and insights in a way that a visually impaired person can fully understand the chart’s meaning. Confine the total length to 200 to 300 words.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*qJqD8cr_fGpWJul4SE39HQ.png" /><figcaption>English Dialects 1997</figcaption></figure><p>Now let’s try using the prompt in ChatGPT (edited for conciseness):</p><blockquote>This pie chart, titled <em>“Proportion of English Dialects in 1997”</em>, represents the relative share of five English dialects spoken in that year. Each segment of the chart corresponds to a different dialect, with its size reflecting its proportion of the total.</blockquote><blockquote>The data shows that USA dialect <strong>dominates</strong>, accounting for more than half of the total share. A <strong>UK </strong>dialect makes up approximately one-fifth of the total, significantly smaller than the dominant dialect but still substantial. The remaining three dialects — Canada, Australia, and Other — each contribute much smaller proportions, and even combined, they represent less than the second-largest dialect.</blockquote><blockquote>In summary, the data highlights a <strong>highly concentrated distribution</strong>, with one dominant dialect, a secondary dialect, and minor contributions from three smaller dialects.</blockquote><blockquote>However, the chart does not provide specific percentages, limiting the precision of interpretation.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=16856055e0f1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What can you find when unboxing a PDF?]]></title>
            <link>https://medium.com/@joeyyangli/what-can-you-find-when-unboxing-a-pdf-b85df5c95209?source=rss-fd90920ed7a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/b85df5c95209</guid>
            <dc:creator><![CDATA[Joey Yang-Li]]></dc:creator>
            <pubDate>Sun, 24 Nov 2024 17:28:19 GMT</pubDate>
            <atom:updated>2025-09-11T16:10:23.171Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*saFuMMRt40NcW1ngr6Xc8w.png" /><figcaption>What are the fancy things inside a PDF?</figcaption></figure><p>So, what’s inside a PDF file? It depends on how you look at it, actually. As a <em>physical</em> file format, a PDF file consists of numerous objects, whose locations and lengths are recorded in cross-reference tables, <a href="https://medium.com/@joeyyangli/pdf-fundamentals-anatomy-of-a-pdf-file-71a1c7cb7a5f">as described in last post</a>. As a <em>logical (fucntional) </em>data container, however, a PDF can be viewed as a collection of assorted “entities”, such as attachments, images, fonts, comments, pages, and so on.</p><p>Such entities are typically expressed as several objects organized into data structures. For example, there may exist a pages tree, a hierarchy of form fields, a list of articles, a hierarchy of document structure in a single PDF document. Conceptually, you can imagine a PDF document as a disk “folder”, and the items inside a PDF as “files”.</p><p>It is therefore similar to a self-contained web archive, or an OpenDocument file that is essentially a zip file.</p><h3>High level overview</h3><p>In the following text, we’ll use <a href="https://www.youtube.com/watch?v=QnlThKiaqcw">Grackle PDF Editor</a> to explore the internals of a PDF file. It shows the document-level data structures in dedicated tab panels, namely Pages, Contents, Tags, Fonts, and Bookmarks. Each tab present a different way to browse and interact with the PDF.</p><h4>Pages</h4><p>Although we normally browse document pages visually (the viewer side of the screen), we should point out that a “page” is drawn through the combination of drawing commands, graphics configuration, and required resources such as images and colours. The entry point is a dictionary that defines the characteristics of the page media along with a registry of resources, as shown in the screenshot below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SXLq0TooZyVHdi9TQlPKTA.jpeg" /><figcaption>Page view showing page’s data and resourvces</figcaption></figure><p>As you can see, there are multiple types of resources. For example, a font object may point to a Type-1, TrueType, or raster font; an image may point to an embedded JPEG image, a monochrome bitmap, or a transparent PNG; and an XObject is a common type of resource in PDF that is like an embedded page.</p><p>A page may contain a number of objects that you can interact with, called annotations. Hyperlinks are one common type of annotation. When you open a PDF form that you can fill and submit, the form fields are also annotations, although they form their own sub-category called widgets. An annotation is an object that are independent of the underlying page content, but they are usually managed by the viewer application’s user interface.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JxzoA0WHVlu0AbNOjEgwxQ.png" /><figcaption>Hyperlinks and their corresponding data</figcaption></figure><p>As to page content, it is actually a stream of drawing commands (in fact, PostScript operations) that the PDF rendering engine can execute, as if a virtual printer. The following screenshot illustrates the composition of the page content. The “rg”, “re”, “cm”, “h” etc. are all commands that the rendering engine can understand and perform. The end results of such operations would be the page’s visual appearance.</p><p>This method of composition is more like canvas drawing programs in JavaScript than resembling that’s in a HTML document. Where as HTML code is directly readable as text, the PDF commands would not be comprehensible unless the page is fully drawn.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MqFK79CykBWt9AjRWs-utw.png" /><figcaption>Page content composition commands</figcaption></figure><h4>Tag Structures</h4><p>A page is an unorganized collection of information, where the ordering of text and image is random, and any readability is by coincidence. By “readability”, we are not talking about the printed hard copy that is read by a human, but “machine readability” where the content is fed to the screenreader, which visually impaired users often rely on. Contrary to what one might expect, the screenreader does not do OCR to figure out how the text on page should be read.</p><p>PDF files are not JPEG images, after all. A PDF file can describe how its content are organized using tags, or “structure elements”. These tags can describe not only text, but also non-textual content from images to hyperlinks. You can easily browse the tag structure of a PDF file if it contains such data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BTtTLbCkLwgkSBYC_Bx48g.png" /><figcaption>Structure view of pages in a tagged PDF</figcaption></figure><p>Tags also imply the reading order of content on page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xIQE8oFAMshxntmTv5D0BA.png" /></figure><p>The presence of tags makes the content of a PDF into structured information that can be represented with high accuracy in HTML and other formats, including the roles of each part. The outcome is much better than reading the page as plain text only, especially when spatial layout is either confusing or correlative, for example when there are columns and tables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RhE8PCXWrMIWJuqF04OJYQ.png" /><figcaption>Representation of strucutured page content in HTML</figcaption></figure><h3>Important entities and structures</h3><p>Pages and tags are the two most important means to “read” the PDF document, i.e. visually and non-visually. There are other important metadata, interactivity, and navigation data in a PDF.</p><h4>Document information</h4><p>The DocInfo object contains some document properties, which can be used for cataloging PDFs. It can also specify how you want the PDF be viewed in a viewer, such as which page should be shown as the opening page and at what zooming level.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-ZfWNyY4fFG8ZmQU4viynw.png" /><figcaption>Common document information</figcaption></figure><h4>Page collection</h4><p>Pages in a PDF are not sequential as it appears. They are organized into a tree structure of arbitrary complexity. The leave nodes on this tree are the actual page objects; the branch nodes, called “Pages” object in PDF terminology, are mere containers to provide grouping of descendant nodes, as well as determining the inheritance of attributes and required resources. For example, if a page group has the attribute of rotation angle of 90 degrees, all of its descendant nodes will inherit the same rotation angle unless overridden on a child level. The sequence of the pages is the result of traversing this tree in a depth-first order.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/0*gY599UDcCTszRbig" /><figcaption>Tree structure of pages</figcaption></figure><p>In any case, the tree needs to be carefully maintained to ensure integrity and balance. As a programmer, to add a page to a document, one has to find the right page group node along the tree to insert the new page (and the right index), so that the over ordering would be as desired. To delete a page, it is easier, but the page group node may also need to be removed if it is empty.</p><h4>Images</h4><p>Images are a type of objects that are called resources, parallel to fonts and brushes, colours, and tiling patterns. However, images are special in that they are usually meaningful content themselves. For comparison, a font is a means to show text, but we read the text without the need to read the font name. As such, images are usually tagged with a description about its intent, called AltText, or “alternative text”. Such text can be used in pure textual representation of a PDF for non-visual usage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Zvl6I0P0uQqppmSuXkqOA.png" /><figcaption>Browsing images contained in a PDF</figcaption></figure><h4>Interactive form fields</h4><p>There can exist an interactive “AcroForm” in the entire PDF file, which may contain subforms, field groups, and form fields. They alsoform a tree structure. Each branch is a subform (such as an address block), and multiple fields may be organized into a group (such as a set of radio buttons).</p><p>A form field — such as a radio button, a drop-down list, or a push button — may have multiple visual appearances representing different states, such as “checked”, “unchecked”, “disabled”, “pressed”, “hovered”, etc. The appearance changes as the user interacts with the field.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/0*i0xLYS53sRfeqmy5" /><figcaption>Tree structure of form fields</figcaption></figure><h4>Bookmarks</h4><p>Bookmarks (document outlines) also form a tree structure. A bookmark is a non-visual reference to a specific area on a specific page. It carries a title, and bookmarks can be organized into a hierarchy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/938/1*xyaN5TQDdXfzf8P86fQe2A.png" /><figcaption>Bookmarks sample</figcaption></figure><p>Unlike pages tree, the outlines tree is not usually used to produce a sequential order of leaf nodes. Instead, they are designed to facilitate random access. As such, a lot more reference to siblings, children, and parent nodes are defined for the nodes on the bookmarks (outlines) tree.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/0*G9rFvhLnDW0CkI63" /><figcaption>Structures of outlines (bookmarks)</figcaption></figure><h4>Other collections</h4><p>There are other special entities and data collections in PDF such as names, file attachments, JavaScript snippets, optional content (layers), etc.</p><p><a href="https://medium.com/@joeyyangli/page-concept-and-graphics-model-in-pdf-documents-1828a6888fa1">Continue on next section</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b85df5c95209" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PDF Fundamentals — Anatomy of a PDF File]]></title>
            <link>https://medium.com/@joeyyangli/pdf-fundamentals-anatomy-of-a-pdf-file-71a1c7cb7a5f?source=rss-fd90920ed7a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/71a1c7cb7a5f</guid>
            <dc:creator><![CDATA[Joey Yang-Li]]></dc:creator>
            <pubDate>Thu, 14 Nov 2024 15:40:49 GMT</pubDate>
            <atom:updated>2025-09-11T16:11:13.654Z</atom:updated>
            <content:encoded><![CDATA[<h3>PDF Fundamentals — Anatomy of a PDF File</h3><p><em>A brief introduction to the internals of a PDF file for curious minds to better understand the technical aspects under the hood. This is the first of a trio of articles on this subject.</em></p><p>Surprisingly, PDF has not only survived the evolution of technology in the past decades, but it is actually thriving even in the current AI boom. The design concept of self-contained package and the weaving of logical structures have proven forward-thinking. As people have stared to realize, properly tagged PDF files, with all text and images organized according to semantical context, become structures of information and meaning, perfect for the new world based on such.</p><p>However, PDF is not without its drawbacks. There are more complexity than a casual look might expect. It pays to survey what’s there to deal with when it comes to parse, edit, consume, and repurpose PDF files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FG9SrEQsMimRDHt6l76sQw.png" /></figure><h3>History of PDF</h3><p>PDF (Portable Document Format) originally belongs to a type of files that are called print streams in that they are intended to be processed by printers to give you paper printouts, usually in large volumes in commercial applications, such as customer statements and mass distribution newsletters. This is what a PostScript printer does, and PDF is one step further by making such data viewable on computer screen.</p><p>If you intercept the data sent to a PostScript printer, you’ll get a PostScript program. Likewise, PDF is a program, but with less dependency on printer hardware (thereby making it “portable”) and most data are packed into objects that are stored in an orderly fashion (therefore the notion of a “format”). That was the birth of PDF, as an exchangeable “document” based on the PostScript concept and syntax — they even share the same data types and graphics model. Over the years, PDF has undergone many revisions to evolve with market and technology. Its popularity still stays strong today. In fact, it has become an ISO standard for document archive and printing.</p><blockquote>A PDF is a collection of PostScript commands that define objects and drawing instructions. What you see on PDF pages are the effect of these instructions.</blockquote><blockquote>- The nature of PDF</blockquote><p>However, PDF files are usually binary and non-readable using a text editor. This is because the object data are compressed and even encrypted. Provided that all object data are decrypted and decompressed, you will be able to read most of the content and understand it better — most, but not all, because images, fonts, and some other types of data are binary by nature. These objects refer to each other to form a variety of data structures, such as trees and linked lists. Quite often, these references are interdependent and data integrity must be maintained properly.</p><p>Manipulation of a PDF file involves handling of these objects, maintaining the data structures’ validity, and interpreting the object data correctly to achieve the desired results. Such results may be visual or non-visual. That is, you may want to change the page appearance to a certain degrees, such as adding a watermark or replacing a logo; or you want to update some data properties such as setting the document title or set the default value of a drop-down list.</p><h3>Logical Data Structure</h3><p>Before we talk about the file layout scheme, let’s first look at how objects are organized. The various types of entities the PDF relies on are stored in a tree structure (each may have its own substructure) so that all objects can be retrieved by following certain paths on this tree. Any objects in a PDF that are not linked to this tree would be redundant and can be safely removed. The references seen in this drawing have predefined keys, so that a program can reliably determine if an expected object is present. The details are found in the extensive PDF Reference, which currently (v1.7) runs over 1,300 printed pages.</p><p>The entry point to a PDF file is not at the start, but at the end of the file called a trailer. The trailer points to a document catalog and some other auxiliary document-level settings, including metadata and encryption settings, among others. The catalog is the major registry of the PDF. It records the information to the root of many other data structures, from pages to tags. If you want to access a page’s content, you need to query the Pages tree, find the page, retrieve its composition stream, and interpret the PostScript commands contained in the composition. If you want to access a form field, likewise you need to retrieve the AcroForm tree (Adobe’s terminology for Acrobat Form), locate the field, and then query its data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/0*T_jqZc2gs14xEm1E" /></figure><h3>Physical File Layout</h3><p>The basic layout of a PDF file follows this general sequence: header, objects, Xref (cross-reference) table, and trailer. There is one header per file, as an identifying characteristic of a PDF. It is very small and it contains a string of specific format in the form of a PostScript comment. Likewise, there is a trailer at the end of file, but it is accompanied by a command “<em>startxref</em>” with a byte offset value. This command tells the reader program where to find the Xref table of this PDF file.</p><p>The Xref is a lookup table containing byte offsets of the objects in this file, so that the reader program can go to the offset directly and start reading and parsing to resolve the object. Each object has an id, but the sequence of objects does not have any particular order. You must start from the Xref table to find an object in the document. Once you have the objects in memory as live entities, you would query the trailer again, this time to access the logical structures.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/0*mPCYzuyFQQlS4RUA" /></figure><p>An object is defined between a pair of <em>obj/endobj </em>commands. The data definition follow the PostScript syntax. An object could be a dictionary, stream, or array, or any of the primitive types including number, string, reference, etc.</p><p>Here’s an actual example of the PDF data segments. Note that each segment has its own syntax, which doesn’t follow what the PostScript would define. There are many tedious nuances in the design of PDF format, for example, the byte offset of the Xref table must be zero-padded 10-digit numbers, and the second line of the header must contain four bytes of non-ASCII values.</p><p><strong>Header</strong></p><pre>%PDF-1.6<br>%âãÏÓ</pre><p><strong>Object</strong></p><pre>72 0 obj<br>&lt;&lt;/Slide25201[2 0 R/XYZ 0 405.014 0]&gt;&gt;<br>endobj<br><br>71 0 obj<br>&lt;&lt;/F1 70 0 R&gt;&gt;<br>endobj<br><br>4 0 obj<br>&lt;&lt;/Font 71 0 R/ProcSet[/PDF/Text]&gt;&gt;<br>endobj</pre><p><strong>Xref table</strong></p><pre>xref<br>0 77<br>0000000000 65535 f <br>0000000015 00000 n <br>0000000353 00000 n <br>0000006411 00000 n <br>......</pre><p><strong>Trailer</strong></p><pre>trailer<br>&lt;&lt;/Size 77/Root 76 0 R/Info 1 0 R/ID [&lt;e6b7084d2818f58c95da7bb2326adb95&gt;&lt;9e54f60a61c02b23bf35ce8357c45587&gt;]&gt;&gt;<br>startxref<br>26436<br>%%EOF</pre><p>However, things can get even more complicated. Over time, PDF introduced three more types of modified layout, each following some new rules.</p><ul><li>Incrementally updated (revised) PDF</li><li>Linearized PDF</li><li>Compressed PDF</li></ul><h3>Incremental Updates</h3><p>PDF supports appending changes to objects to the end of existing file to overrule their original definition. In essence, this means any new revisions of the PDF can be just incrementally appended. This enables the quickest saving operation, and makes it possible to revert to any of the previous revisions. However, this is not a common practice, and the editor program may chose to completely reconstruct the entire file, thereby loosing all historical data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1019/0*j0z3w0I7t25yfMxh" /></figure><p>Revised PDF means there can be multiple versions of the same object. This is resolved by referring to the “revision number” (generation number) of the object, which is default 0. Objects in a revision may have a new generation number, but not always.</p><p>The trailers of a revised PDF contains a reference to the previous Xref table via the <em>/Prev</em> key, which would be same as the <em>startxref</em> value of the previous one, thus forming a linked list. The starting point is always at the end of file. A reader program files the intended version of an object by following this linked list, while observing the generation number if any.</p><p><strong>Trailer</strong></p><pre>trailer<br>&lt;&lt;/Size 79/Root 76 0 R/Info 1 0 R/ID[&lt;E6B7084D2818F58C95DA7BB2326ADB95&gt;&lt;7A40616F2F4C47EC841BBF19FBE09E35&gt;]<br>/Prev 26436&gt;&gt;<br>startxref<br>32688<br>%%EOF</pre><h3>Linearized PDF</h3><p>PDF open grows to huge sizes but the network speed can be a hindering factor, as by design a reader program has to wait till the end of file, i.e. when the entirety of the file has been transmitted, to start parsing and rendering a PDF. This can leads to a bad user experience in a browser. To address the issue, Adobe created the concept of “linearized PDF” where the objects needed for the first page are packed at the start of the file, so that a browser plug-in can render the first page while the user waits for the rest of the file to be downloaded. This probably sounds like sugarcoating, as the core issue is simply hidden and not resolved from the design level.</p><p>Linearization assumes a user would browse the pages in a consecutive order and never skips pages or flip back. With this mindset, all objects in the PDF are to be ordered in a fashion that the required objects for a given page is already downloaded, while those not used by the preceding pages are pushed later. Such linearized scheme is ubiquitous in Adobe-generated PDFs. What’s unique about this type of file is that it contains a Xref table right at the start, for the first part of the file (for page 1), and a regular Xref table at the end of file for the rest of pages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/0*UQYiUxC3lcw0KuDK" /></figure><p>The interlinking in a linearized PDF is a bit convoluted: the trailer at the end of file points to the Xref table at the start (whose trailer is the effective head of the linked list), while the first trailer points to nowhere (with a “startxref” of value 0). Instead, it links to the last trailer using the <em>/Prev</em> mechanism of the linked list. If that sounds confusing, too bad! Things start to get even more confusing from here.</p><p>The linearization data contains multiple cryptic values, all for the benefit of drawing the cover page, which may have been reproduced by an image. However, in the age of dial-up modems, that wasn’t an option. Among these values there is the expected byte length of the file. This is used to validate the file. If modified, linearization data is discarded.</p><p><strong>Header and linearization object</strong></p><pre>%PDF-1.4<br>%âãÏÓ<br>188 0 obj<br>&lt;&lt; <br>/Linearized 1 <br>/O 190 <br>/H [ 1447 861 ] <br>/L 8840357 <br>/E 47796 <br>/N 30 <br>/T 8836478 <br>&gt;&gt; <br>endobj</pre><h3>Compressed PDF</h3><p>Because of the format of the Xref table, it is very inefficient in terms of byte size, and it gets much worse if the PDF contains thousands of pages. More over, there can be thousands of objects with textual content (such as arrays and simple dictionaries), along with the <em>obj/endobj</em> overhead, and that too is not an efficient way. So compressed PDF mechanism was created to optimize on these two areas.</p><p>First of all, the Xref table is replaced with an Xref stream object just like the others, except its content is an encoded table of integer values, representing the same information an Xref table would carry. Secondly, some objects are compressed packages for other objects. These are called “object streams”. If you open the PDF in an editor, you will not find those packaged objects any more, but you have to unpack the containers to find these objects there. This creates more challenges to the reader program, as it has to unpack these container objects first, and it must keep track of which objects are directly readable and which are not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1021/0*OsLelhEXj_v1Vaoa" /></figure><p><strong>Xref stream</strong></p><pre>1694 0 obj<br>&lt;&lt;/DecodeParms&lt;&lt;/Columns 5/Predictor 12&gt;&gt;/Filter/FlateDecode<br>/ID[&lt;8D459BD2C8D1684582F65F8996305169&gt;&lt;32BCF5BBC25E814683E65CB3157568B8&gt;]<br>/Index[7 1 11 1 174 1 1418 1 1473 1 1648 1 1690 5]/Info 1648 0 R/Length 57<br>/Prev 553764/Root 1650 0 R/Size 1695/Type/XRef/W[1 3 1]&gt;&gt;stream<br>...... (stream data)<br>endobj</pre><p><strong>Object stream</strong></p><pre>158 0 obj<br>&lt;&lt;/Filter/FlateDecode/First 875/Length 2538/N 100/Type/ObjStm&gt;&gt;stream<br>...... (stream data)<br>endobj</pre><p>To make the situation even more complicated, there can be hybrid PDFs that carry both an Xref table and an Xref object. It was designed so that an outdated PDF reader can still read the file to display something while a newer PDF reader can create accurate results with the added information packed in the compressed parts. The layout of such hybrid files would see both the Xref stream object and the Xref table, in that order, appear before the trailer. This pair form a linked list.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1021/0*CZclf4dwv9FYmTEV" /></figure><p>When compression scheme is used on a linearized PDF, the layout is basically the same, but the Xref table are swapped with Xref stream objects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/0*zi_XUG2fjuZRYIiT" /></figure><p>Note that, a linearized file may be a hybrid, and it may undergo incremental updates after creation (thereby making it not a linearly optimized file any more). This would create a PDF carrying several Xref tables and stream objects throughout the document. A proper reader must decide whether the file has been modified since creation, by comparing the expected file length and the actual. If modified, expect there may be incremental updates. In any case, follow the linked list, wherever it leads you.</p><h3>Document entry point</h3><p>Once you have the objects, you can find the two objects referred to by the /Info and /Root keys in the effective trailer. The first one is the document information (title, author, creator, etc.), and the second one is the entry point to the logical structures of the document, as introduced above. At the bare minimum, the catalog must contain a /Pages key pointing to the page tree. Among other things, the catalog may contains an entry pointing to the document metadata, which is a data block of XML according to Adobe’s XMP initiative.</p><p><strong>Info</strong></p><pre>181 0 obj<br>&lt;&lt; <br>/CreationDate (D:20080617134603Z)<br>/ModDate (D:20080617151754+01&#39;00&#39;)<br>/Producer (Acrobat Distiller 5.00 for Macintosh)<br>/Author ()<br>/Creator (QuarkXPress. 4.1: LaserWriter 8 Z1-8.7.1)<br>/Title (6350 SIL Autumn 05 Cover \(AW\))<br>&gt;&gt; <br>endobj</pre><p><strong>Root (Catalog)</strong></p><pre>189 0 obj<br>&lt;&lt; <br>/Type /Catalog <br>/Pages 180 0 R <br>/Metadata 182 0 R <br>&gt;&gt; <br>endobj</pre><h3>But there’s more!</h3><p>That’s not the end of nightmare called PDF!</p><p>A PDF file may be used as a mere container, using the PDF file structure to carry objects of arbitrary type as attachments. One example is what’s called a “portfolio”, which is an Acrobat-specific format that is more UI than document. There is no page to display, instead a non-compatible readers would just see a placeholder page with a notification, stating this is not the actual content of the file.</p><p>Another example is an “XFA”, which is XML-based interactive form definition and dataset. The entire XFA data is interpreted by Acrobat to generate pages and fields on the fly, meaning there’s nothing visual in the PDF to the other readers. Both designs violated the spirit of “portability”.</p><p><a href="https://medium.com/@joeyyangli/what-can-you-find-when-unboxing-a-pdf-b85df5c95209"><em>Continue on next section</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=71a1c7cb7a5f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tagged PDF: Why Structures Are Important]]></title>
            <link>https://medium.com/@joeyyangli/tagged-pdf-why-structures-are-important-da921ae8652a?source=rss-fd90920ed7a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/da921ae8652a</guid>
            <dc:creator><![CDATA[Joey Yang-Li]]></dc:creator>
            <pubDate>Thu, 07 Dec 2023 03:57:21 GMT</pubDate>
            <atom:updated>2023-12-13T21:48:18.087Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MX1RV6RgoVLuOAU9Eag0XA.png" /><figcaption>Illustration for a document being read on a device</figcaption></figure><blockquote><strong>A PDF should be tagged for use in RAG applications to yield the most reliable results. A fully tagged PDF is a multi-modal data source by nature.</strong></blockquote><h3>Introduction</h3><p>Invented more than two decades ago, the Portable Document Format (PDF) still has a powerful presence shadowing the alternatives such as ePub, as a self-contained document exchange format with a uniform look and feel across different media. As soon as ChatGPT-3 led the world into a new era in information access, people have created various applications in the theme of “chatting with your PDF”.</p><p>Most of these applications consumes the PDF on a page base, while text on each page are segmented into chunks of uniform size, usually 1k or 2k characters long. This is a rather mechanical approach that is optimal for the proper understanding of a PDF document, resulting in broken sentences, redundant or overlapping text, and loss of attention on key content such as headings.</p><p>In fact, PDF can be well-structured semantically. Proposed many years ago for universal accessibility, such structured PDFs have built-in HTML-like tags that should not be wasted. Moreover, most non-textual content in a PDF are also interpreted in a well-tagged PDF, such as graphics and charts, contributing to the overall accuracy and completeness.</p><p><a href="https://medium.com/@joeyyangli/structured-pdf-for-the-rag-era-fb6976093df1">Structured PDF for the RAG Era</a></p><p>PDFs are required to be well-tagged on government and other public agencies’ websites, according the US law. It is covered by Section 508 of the Rehabilitation Act and Section 255 of the Communications Act. The initial design purpose was to make the PDF content accessible to the visually impaired, so that a screenreader can follow the content structure and provide a navigation mechanism based on semantics rather than physical pages and visual designs.</p><p>As it turned out, an accessible PDF is equally useful for the sighted users as well. A well-tagged PDF can be easily converted to an equivalent HTML representation, or be exported into JSON format so that a consumer application can work with structured information directly. Such a PDF is referred to as universally accessible (PDF/UA).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CtkYL8S3Pv7bVOOSZcAp9A.jpeg" /><figcaption>Side-by-side view of document tags and content layout</figcaption></figure><h3>Tag Hierarchy</h3><p>Representing a PDF using tags instantly makes it a well-structured document, and sets the content free from the confinement of visual layout — such as text wrapping, multi-column layout, page breaks, and even text overflown to a random page. Tags organize the text into nested sections such as division and lists, as well as assigning roles to paragraphs such as captions, headings and titles.</p><p>In a tagged PDF, textual and image content alike are all marked up with numeric IDs, which are referred to in the corresponding tags. Essentially, a PDF is conceptually converted into an HTML document with a predesigned appearance. The tag information usually does not care about the physical location on page, or the font styles used in rendering.</p><p>According to PDF/UA specification published by Adobe and ISO standard, there are three types of tags:</p><ul><li>Group container tags</li><li>Block-level tags</li><li>Inline tags</li></ul><p>By definition, tags do not refer to pages or metadata. If there are headers and footers in a document, they are usually left out of the tags tree, too. Anything visible on the PDF pages that are not tagged are considered artifacts, or in other words redundant content that can be safely skipped.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RyIPgs61hTiP2l5hgHekdw.png" /></figure><p>In the case of AI-powered PDF access, which is called “Retrieval Augmented Generation (RAG)”, context is normally derived from the vicinity of a relevant chunk. A better approach expands the chunk by optimizing the context. However, that is still trying to make a smarter guess. A fully tagged PDF would solve the problem elegantly and provide the most relevant and lean context. For example, a paragraph would naturally include the heading for the section in its context, while a list item can include the entire list as context rather than a paragraph that follows, even if it is physically near.</p><p>A tagged PDF typically defines the document parts nicely so that you can determine precise segmentation and apply different methods of dealing with the them. For example, you can summarize each chapter section, instead of summarize on randomly selected page ranges; compare the section on table of contents and the section on main text, you probably want to use different prompts catering two the content types.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/1*Oy1rRxn-xIcgre7v7Q1VIw.png" /><figcaption>An example of structured PDF with document parts</figcaption></figure><h3>Tabulated Data</h3><p>When viewed as a continuous stream of text, a table becomes a series of discrete words and numbers. However, with a tagged PDF, they are organized into a true table form represented by a &lt;Table&gt; tag, complete with header and data cells, as seen in the following illustration. A table call can also define column of row spans, while a header call can specify whether it is scoped for the rows or the columns. In addition, tables are often assigned with captions and summaries.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*3VGF8KwZ2WL-E9dLk1iG8A.png" /><figcaption>A table with header cells</figcaption></figure><p>Such information is very helpful in correctly understanding the information presented in the table. It is also possible to refer to the table by row, column, or part. All is lost if it is flattened into a stream of pure text. No amount of clever chunking inference would fully recover this two-dimensional information from the one-dimensional text stream.</p><h3>Multimodal PDFs</h3><p>As seen in the following exemplary solution, almost all “chat-pdf” RAG applications view the PDF as a linear flow of plain text. One thing obviously missing is the existence and placement of Figures — where is an image embedded, what is the image about, and what is its significance?</p><p>All of these questions can be answered with tags: a &lt;Figure&gt; tag appears in the right place in the context and it defines the actual textual representation of the image. In the case the image is purely decorative, it is marked as an artifact. That would for example exclude pictures and ads even if it appear to contain meaningful text. Without such a mechanism, a clever vision-based solution may mistaken them as valid content therefore polluting the actual information store.</p><p>Similarly, there are other non-textual information in PDFs, such as links, audio media, form fields, and even attached files. All of them can be suitably normalized into textual information for use in applications, making the PDF a multi-modal source.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*LLtmew6ox-UtpL6XuHeOeQ.png" /><figcaption>A chart shown as an image in a PDF</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/1*nOoObLiHTk2_2_xGD-FNZA.png" /><figcaption>The alt-text for the chart above</figcaption></figure><p>In summary, it could be emphasized that:</p><ul><li>A PDF should best be tagged (PDF/UA) for use in RAG applications to yield the most reliable results.</li><li>A fully tagged PDF/UA is a multi-modal data source by nature.</li><li>Identifiable document parts in PDFs make it possible to build more reliable multi-document querying and reasoning.</li></ul><p><a href="https://medium.com/@woyera/how-to-chat-with-your-pdf-using-python-llama-2-41df80c4e674">How to Chat with Your PDF using Python &amp; Llama2</a></p><h3>Creating Tagged PDFs</h3><p>Many word processing programs create tagged PDFs, such as Microsoft Word, LibreOffice, and Adobe Acrobat. Google Docs notably does not create tagged PDFs, but it can be overcome by a proper AddOn Extension, for example <a href="https://www.grackledocs.com/">Grackle Docs</a>. An Autotagger is also in the works that can automatically convert any PDF into a multi-modal tagged PDF using AI.</p><p>Most PDFs are comprised of a few basic tags; however, authors can utilize up to around 40 different tags to fully convey a document’s formatting and structure. Sometimes non-standard tags or even spurious ones can be present, notoriously in PDFs created by graphics design programs, such as Adobe InDesign, Canva.com or even Microsoft Powerpoint. In those cases, you may want to do a clean-up or remediation of the PDF tags first.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FGhYK-4cd9sc%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DGhYK-4cd9sc&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FGhYK-4cd9sc%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/46a554d398f97adc2e43c4bf06fd3160/href">https://medium.com/media/46a554d398f97adc2e43c4bf06fd3160/href</a></iframe><h4><strong>Container elements</strong></h4><p>Container elements are the highest level of element and provide hierarchical grouping for other block-level elements.</p><p><strong>&lt;Part&gt;</strong></p><p>Part element is a large division of a document; it can be used to group smaller units of content together, such as division elements, article elements, or section elements.</p><p><strong>&lt;Div&gt;</strong></p><p>Division element is a generic block-level element or group of block-level elements.</p><p><strong>&lt;Art&gt;</strong></p><p>Article element is a self-contained body of text considered to be a single narrative.</p><p><strong>&lt;Sect&gt;</strong></p><p>Section element is a general container element type, comparable to Division in HTML, which is usually a component of a part element or an article element.</p><h4><strong>Heading and paragraph elements</strong></h4><p>Heading and paragraph elements are paragraph-like, block-level elements that include specific level heading and generic paragraph tags. A heading (H) element should appear as the first child of any higher-level division. Six levels of headings (H1 to H6) are available for applications that don’t hierarchically nest sections.</p><p><strong>&lt;H&gt;</strong></p><p>Header (Not recommended for use in structured PDF documents)</p><p><strong>&lt;H1&gt;</strong></p><p>Heading level 1 (Recommended for the title and highest section level of a document)</p><p><strong>&lt;H2&gt;</strong></p><p>Heading level 2</p><p><strong>&lt;H3&gt;</strong></p><p>Heading level 3</p><p><strong>&lt;H4&gt;</strong></p><p>Heading level 4</p><p><strong>&lt;H5&gt;</strong></p><p>Heading level 5</p><p><strong>&lt;H6&gt;</strong></p><p>Heading level 6</p><p><strong>&lt;P&gt;</strong></p><p>Paragraph</p><h4><strong>Label and list elements</strong></h4><p><strong>&lt;L&gt;</strong></p><p>List element is any sequence of items of similar meaning or other relevance; immediate child elements should be list item elements.</p><p><strong>&lt;LI&gt;</strong></p><p>List item element is any one member of a list; may have a label element (optional) and a list body element as a child.</p><p><strong>&lt;LB&gt;</strong></p><p>Label element is a bullet, name, or number that identifies and distinguishes an element from others in the same list.</p><p><strong>&lt;LBody&gt;</strong></p><p>List item body element is the descriptive content of a list item.</p><h4><strong>Special text elements</strong></h4><p>Special text elements identify text that isn’t used as a generic paragraph.</p><p><strong>&lt;BlockQuote&gt;</strong></p><p>Block quote element is one or more paragraphs of text attributed to someone other than the author of the immediate surrounding text.</p><p><strong>&lt;Caption&gt;</strong></p><p>Caption element is a brief portion of text that describes a table or a figure.</p><p><strong>&lt;Index&gt;</strong></p><p>Index element is a sequence of entries that contain identifying text and reference elements that point out the occurrence of the text in the main body of the document.</p><p><strong>&lt;TOC&gt;</strong></p><p>Table of contents element is an element that contains a structured list of items and labels identifying those items; has its own discrete hierarchy.</p><p><strong>&lt;TOCI&gt;</strong></p><p>Table of contents item element is an item contained in a list associated with a table of contents element.</p><h4><strong>Table elements</strong></h4><p>Table elements are special elements for structuring tables.</p><p><strong>&lt;Table&gt;</strong></p><p>Table element is a two-dimensional arrangement of data or text cells that contains table row elements as child elements and may have a caption element as its first or last child element.</p><p><strong>&lt;TR&gt;</strong></p><p>Table row element is one row of headings or data in a table; may contain table header cell elements and table data cell elements.</p><p><strong>&lt;TH&gt;</strong></p><p>Table header cell element: is a table cell that contains header text or data describing one or more rows or columns of a table.</p><p><strong>&lt;TD&gt;</strong></p><p>Table data cell element is a table cell that contains non-header data.</p><h4><strong><em>Inline-level elements</em></strong></h4><p>Inline-level elements identify a span of text that has specific formatting or behavior. They are differentiated from block-level elements. Inline-level elements may be contained in or contain block-level elements.</p><p><strong>&lt;BibEntry&gt;</strong></p><p>Bibliography entry element is a description of where some cited information may be found.</p><p><strong>&lt;Quote&gt;</strong></p><p>Quote entry element is an inline portion of text that is attributed to someone other than the author of the text surrounding it; different from a block quote, which is a whole paragraph or multiple paragraphs, as opposed to inline text.</p><p><strong>&lt;Span&gt;</strong></p><p>Span entry element is any inline segment of text; commonly used to delimit text that is associated with a set of styling properties.</p><h4><strong>Special inline-level elements</strong></h4><p>Similar to inline-level elements, special inline-level elements describe an inline portion of text that has special formatting or behavior.</p><p><strong>&lt;Code&gt;</strong></p><p>Code entry element is computer program text embedded within a document.</p><p><strong>&lt;Figure&gt;</strong></p><p>Figure entry element is a graphic or graphic representation associated with text.</p><p><strong>&lt;Form&gt;</strong></p><p>Form entry element is a PDF form annotation that can be or has been filled out.</p><p><strong>&lt;Formula&gt;</strong></p><p>Formula entry element is a mathematical formula.</p><p><strong>&lt; Link&gt;</strong></p><p>Link entry element is a hyperlink that is embedded within a document. The target can be in the same document, in another PDF document, or on a website.</p><p><strong>&lt;Note&gt;</strong></p><p>Note entry element is explanatory text or documentation, such as a footnote or endnote that is referred to in the main body of text.</p><p><strong>&lt;Reference&gt;</strong></p><p>Reference entry element is a citation to text or data that is found elsewhere in the document.</p><p><a href="https://www.grackledocs.com/product/">Grackle by Product - GrackleDocs</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da921ae8652a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Structured PDF for the RAG Era, i.e. Chat-with-PDF Applications]]></title>
            <link>https://medium.com/@joeyyangli/structured-pdf-for-the-rag-era-fb6976093df1?source=rss-fd90920ed7a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb6976093df1</guid>
            <category><![CDATA[pdf]]></category>
            <category><![CDATA[accessibility]]></category>
            <category><![CDATA[retrieval-augmented]]></category>
            <category><![CDATA[document-processing]]></category>
            <dc:creator><![CDATA[Joey Yang-Li]]></dc:creator>
            <pubDate>Mon, 04 Dec 2023 16:50:10 GMT</pubDate>
            <atom:updated>2023-12-13T21:38:42.474Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M23CuquVDUVd7uo3YupHGw.png" /><figcaption>Illustration for document processing and information access</figcaption></figure><p>Retrieval-Augmented Generation (RAG), or an interaction with ChatGPT or other LLMs using queries with relevant context to define a baseline for the response generation, has mushroomed ever since earlier this year. One popular use case is to turn a PDF into a miniature knowledge base that you can interact with in plain language.</p><p>The process is illustrated in this wonderful article with much clarity:</p><p><a href="https://towardsdatascience.com/retrieval-augmented-generation-rag-from-theory-to-langchain-implementation-4e9bd5f6a4f2">Retrieval-Augmented Generation (RAG): From Theory to LangChain Implementation</a></p><h3><strong>Limitations of Linear Slicing of PDF</strong></h3><p>This is not an article discussing about the LLM aspect, but on the PDF, or other structured documents. There is major drawback in slicing the PDF into text chunks of fixed sizes: each chunk is not necessarily coherent or even complete, and therefore embeddings are less optimal than they should be. The resultant context may contain irrelevant or incomplete information that both distracts LLM’s attention and consumes precious token counts.</p><p>Other limitations of linear sequencing would include:</p><ul><li>Inability to properly include image and tables in the embeddings;</li><li>Loss of landmark information including headings, list items, footnotes, headers, etc. since everything are treated as text of equal roles;</li><li>Lack of inclusion of logical document structure such as sections and chapters, which would group the text much better;</li><li>Physical page boundaries are actually of little importance in the consumption of information flow, however the typical RAG process is often based on pagination;</li><li>When a query needs to done on multiple documents, constructing a relevant and succinct context is even more challenging due to the lack of multi-level vector generation and search.</li></ul><p>In fact, effort has been made by some advanced RAG solutions to reduce the amount of redundant text and to provide more relevant context for retrieved text chunks, for example the following “small-to-big” retrieval that tries to group slices.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FihSiRrOUwmg%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DihSiRrOUwmg&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FihSiRrOUwmg%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/456a890ba566581848d09aade753f5c3/href">https://medium.com/media/456a890ba566581848d09aade753f5c3/href</a></iframe><p><strong>Fortunately, PDF is not actually linear. </strong>There is a technology in PDF called Universal Accessibility (PDF/UA) that is designed to organize document content into a <em>logical hierarchy</em>. A compliant PDF is called an “Accessible PDF”, which has a multi-level grouping of content and prefers navigation along such a “document structure” tree that is similar to tag structure in an HTML document. Each structure element is either a tag (denoting a range of content items including text and images) or an object reference (referring to a single object such as a link).</p><p>There is an ISO standard defining the details and compliance requirements for such PDFs, typically created for the visually impaired who use screen readers to read, however these are universally beneficial by nature. Thanks to legislatures in recent years, nowadays most public service sectors, consumer product makers, and educational institutions have adopted this standard to make sure their PDFs are accessible. It makes sense that a RAG optimizes for hierarchical PDFs instead of linear consumption.</p><p>The PDF Association has a pamphlet named “PDF/UA in a Nutshell” that briefly describes the what, why, and how of this technology.</p><p><a href="https://www.pdfa.org/resource/pdfua-in-a-nutshell/">PDF/UA in a Nutshell</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nAgPodKFWA_VlXn--PV1hQ.jpeg" /><figcaption>Screenshot of a PDF that is tagged</figcaption></figure><h3>Tagged PDF with Structures</h3><p>Under such a guideline, a PDF needs to be “tagged” so that everything on the pages are given semantic roles, from simpler ones (such as paragraphs, headings, figures) to more complex structures (such as tables, TOCs, lists). Within the block-type elements, inline segments can further be defined (such as references, equations, spans). The concept sounds very much like a HTML page. In fact, the elements are also called tags, and even their role types are inspired by HTML.</p><p>In the screenshot above, you can see the tag structure of a PDF file at the left, and the pages superimposed with the tagged areas at the right, along with thin lines showing the reading order. Organizing the page content in such a way brings much needed accuracy and elegancy when it comes to segmenting a PDF: one should observe the existing tags.</p><p>Note that for a tagged PDF, page boundaries can be completely disregarded. The entire document is a continuous layout of a tag tree. A tag can easily run across the page boundary while the textural flow is uninterrupted. Navigation is driven by the tag tree, instead of page layout.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y6CViNAUMevkSLNVGsiRbw.jpeg" /><figcaption>Alternative view of the PDF structure</figcaption></figure><p>The structure and content of a tagged PDF can be equivalently represented by an HTML page that shows the nesting and role assignment of content segments. In terms of embedding and retrieval, theoretically, each end node and branch node along this tree can has its own embedding, so that when we do comparison while processing a query, we can find the most relevant <em>paths</em> instead of discrete <em>chunks</em> (as would with linear slicing).</p><p>Practically, we don’t actually need to convert each and every nodes into embeddings. Overly fragmented pieces aren’t going to help any queries. Instead, embeddings should still be kept at reasonable sizes to be useful. This would call for merging of sibling tags and introduction of branch summaries that would keep the effective text size under control.</p><p><strong><em>Alternative Texts for Images</em></strong></p><p>One benefit of the PDF/UA effort is that all images are represented as textual information, called “alternative text”, which can be treated as regular text and therefore part of embedding. One may further use Google Cloud Vision or ChatGPT+V to automatically generate descriptions. The fact that &lt;Figure&gt; tags would precisely designate the context is already helpful.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z4raKsMi5ZlzfQRo5DQ2JQ.jpeg" /><figcaption>Overview of Figure alternative text in a PDF</figcaption></figure><p><strong><em>Tables are more than just text</em></strong></p><p>If a PDF is converted into pure text without structures, a table would become a collection of broken phrases or numbers with little context. Information about table column, header, scope, merging, etc. is lost in the process, which could be essential for properly interpreting a table. The PDF/UA standard painstakingly defined the details of every aspects of tables. Such information should be collected and converted into embeddings, instead of the raw data cells themselves, so that the table content becomes more reachable.</p><p>To take a step further, one may use ChatGPT+V can also help describe the table using visual appearance, which would <em>explain</em> the table content instead of merely <em>presenting</em> it. The explanation should naturally be used in place of the table when searching for relevant information. Therefore, the RAG solution should be designed with multiple representations of a document parts in parallel:</p><ul><li>The physical composition that draws the table and its content;</li><li>The tag structure information that describes the table cells and columns;</li><li>The human-readable explanation of the table.</li><li>The raster image of the table, for computer vision.</li></ul><p>All of these can be solved if the PDF is a tagged one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*69RalSjEVtv3cRZF4d-stA.jpeg" /><figcaption>A sample table with header cells</figcaption></figure><h3>Considering How to Quote Source</h3><p>One of the key aspects of a RAG application is the ability to refer to the source. Such information is usually embedded in the context text, with unique identifier attached to the text so that an LLM can include them in their responses. However, with linear slicing, it usually means a page number, so the precision is less than desired.</p><p>With tagged PDF, more can be done, so that a response can refer to a <em>particular</em> tag with precise content that can be derived. This would bring much clarity to the interaction between the user and the LLM.</p><p>The precision also makes it more realistic to work with multiple tagged PDFs and query about related content across different sources. For example, comparing expenses from multiple statements is doable with simple linear understanding of PDF text, but with tagged PDFs it can be done more precision and less hallucination.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XzEKJN31uFQI_9dX_PbwBQ.jpeg" /><figcaption>Integrate precise references into response</figcaption></figure><p>The metadata of the embeddings is the perfect place to store the information of tags regarding identity, role type, page, etc. Prompt can be given to the LLM so that the response include references to sources, specified via the context. The RAG application must take care of interpreting such references, for example, locating the tags in the PDFs and then fetching the original content to read out loud.</p><h3>Creating Tagged PDFs</h3><p>Overall, using tagged PDFs is highly encouraged for the era of RAG. It doesn’t need to be perfect for a tagged PDF to be useful, but the focus should be on the readability; for example, tags should be describing the type of consumer content (<em>Is it a paragraph? A heading?</em>) instead of the type of design-stage objects (<em>Is it a text box? A polygon?</em>). You can generate tagged PDFs from Google Docs and Slides, using a Google plug in called <a href="https://www.grackledocs.com/">Grackle</a>, and have these issues taken care of automatically. Google Docs can create PDFs but they are not tagged. Converting a non-tagged PDF to a tagged one is a non-trivial process that you should try to avoid. Creating PDFs with tags in the first place should be a preferable choice.</p><p><a href="https://www.grackledocs.com/product/">Grackle by Product - GrackleDocs</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb6976093df1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>