Pharmex logo

Pharmex — How it works

Technical and developer documentation for the demonstration release
30 November 2026

This document explains the ideas behind Pharmex, how the demonstration is organised, and how its parts work. I have tried to explain the programming in an order which makes sense if you are coming to the system for the first time. It describes the release in pharmex_release, including the inference preparation facilities and the integration of saved results into the Inspector.

For actually using the system, start with the Red-Pencil Inspector and its Walkthrough.

1. The semiotic heatmap and the Red Pencil Model

The idea of a semiotic heatmap came out of my research. In an ordinary heatmap, one represents a quantity by showing where in a space it is high and where it is low. In a semiotic heatmap, what interests us is the meaning of the parts of an image or document. Where is a claim being made? Where are we being given the impression of good health, or of scientific authority? Where is there information about risk, and how does it relate to information elsewhere in the document?

There are two things to keep in mind. The first is the idea of the semiotic heatmap. The second is the idea of a pre-word-processor newspaper editor using a red pencil to mark pieces of a drug advert that they think are faulty, and writing annotations explaining why. A finding need not concern a single piece of text. It might concern a picture and its caption, or the relationship between a claim near the top of an advert and a warning at the bottom.

So the computer representation we want is not just a list of words or a list of scores. It is a representation of parts of documents, of what those parts mean, and of relationships between them. In the present Inspector, the spatial part of this representation is displayed by red outlines rather than a continuously coloured heatmap. The underlying idea is the same. By selecting a finding one can see all the places to which it refers.

An editor reviewing the fictional MegaVit advertisement with a red pencil
The red-pencil model: an editor marks claims and pictures for review. The scores in this cartoon are illustrative.

What I find particularly interesting about Pharmex is the combination of this spatial representation with a language model, a set of explicitly stated assessment criteria, and a rule-based system for deriving further indicators. Each has a different job. We can examine the output of one stage without treating the whole system as a black box. The intention is to help a human reviewer decide what deserves attention, not to deliver a legal verdict.

2. Basic coding strategy

Pharmex is a web program. The user interface is written in HTML, JavaScript and CSS. HTML specifies the page and its components; JavaScript reads the data, creates the interactive displays and generates the reports; CSS specifies their appearance. For drawing marks on an image we use SVG (Scalable Vector Graphics), which the browser can display directly.

Most of the application runs in the browser. There is no need to install a separate Pharmex desktop program. The demonstration's analyses are stored as JSON files on the web server, alongside their images. The browser obtains these using ordinary HTTP requests. JSON is a data format, not a programming language.

There is also a fuzzy-logic inference service, implemented in SWI-Prolog, which is called through a shared JavaScript interface. There are no PHP programs in the Pharmex release directory. The shared service is outside that directory; this document describes its calling interface rather than assuming how its HTTP transport is implemented. Python, Bash and Windows batch files are used for development, preparation and installing data, rather than for the Inspector's normal browser operation.

I have tried to divide the JavaScript into small files according to the jobs they do. For example, the program which finds image filenames should not need to know what a pharmaceutical assessment is. The program which calculates fuzzy-logic indicators should not need to know what a browser button is. This is useful both for testing and for extending the program.

3. Server directory structure and URLs

Organisation of the website

A web server's document root is the directory from which it serves files to web browsers. Files outside this directory are not ordinarily accessible through URLs, unless the server is specifically configured to expose them.

In our installation, the web server's application directory is /var/www/app. The root of the Pharmex website is /var/www/app/pharmex_release, and its URL prefix is https://expertsystemdemos.net/pharmex_release/. The Pharmex root is therefore not necessarily the document root of the whole web server.

When installing Pharmex on another server, preserve the internal directory structure of pharmex_release. The operating system and absolute directory names need not be the same, although the URL references must correspond to the installation. The shared browser-side inference_client.js, currently one directory above the Pharmex root, must also be accessible at the URL used by the inference preparation and test pages.

Certain files reside outside the publicly accessible website:

These can reside elsewhere on a new server, provided that the relevant configuration and file references are adjusted accordingly.

Our development environment uses a Windows computer and a Linux server, with SSH for remote administration and SCP for file transfer. This is a description of our working environment, not a requirement of Pharmex.

/var/www/app/
    inference_client.js                 shared inference interface
    pharmex_release/
        viewer/
            red-pencil-inspector.html
            js/                         JavaScript modules
            css/                        stylesheets
        projects/                       adverts and analyses
        walkthrough.html
        about_fuzzy_logic.html
        logo.png
        favicon.ico
        favicon-16.png
        favicon-32.png
        aquatic.png
        fes2.docx
        regulatory_compliance_concerns_2.kb
        pharmex_test_m05_both_kbs.html
        pharmex_test_m05_display.html
        pharmex_prepare_inference.html

The initial release comprised 133 files: the Inspector and 24 JavaScript modules and three stylesheets, nine top-level documentation/branding/rule files, and 96 project files (48 image and analysis pairs). Since then we have added the completion library, three preparation or test pages, and saved inference files. The development installation is maintained separately.

For example, the Inspector's file /var/www/app/pharmex_release/viewer/red-pencil-inspector.html is opened at https://expertsystemdemos.net/pharmex_release/viewer/red-pencil-inspector.html. A project image at projects/bluenova/bluenova2.png below the release root has the URL https://expertsystemdemos.net/pharmex_release/projects/bluenova/bluenova2.png. The URL is not the server's absolute filesystem path.

JavaScript modules import each other using relative paths, so the path from viewer/js/catalog.js to the project directory is ../../projects/. The preparation page, which is at the top level of the release, includes the shared inference client as ../inference_client.js. The actual rules used by the service live outside the web directory (see below).

4. How data is organised — projects and adverts

Pharmex organises its data into projects. The top-level Pharmex directory contains a directory called projects. Inside this is one directory for each project. For example, the megavit project contains several variations of a vitamin advertisement. Each advert is stored as an image, accompanied by a file containing information about its analysis.

pharmex_release/projects/
    arthrinova/
        ArthriNova.png
        ArthriNova_red_pencil.json
        ArthriNova_inference.json
        ArthriNova2.png
        ArthriNova2_red_pencil.json
        ArthriNova2_inference.json
    bluenova/
        bluenova2.png
        bluenova2_red_pencil.json
        bluenova2_inference.json
    megavit/
        megavit_a_sd_low_high.jpg
        megavit_a_sd_low_high_red_pencil.json
        megavit_a_sd_low_high_inference.json
        ...

The .jpg or .png file is the advert itself. The _red_pencil.json file contains the red-pencil analysis: the findings, the parts of the image they refer to, the scores and the recommendations. The _inference.json file, where present, contains the separate precalculated rule results. These are the three file types used to represent an analysed advert in the release.

This arrangement makes it easy to extend Pharmex. To add another project, we would create another directory containing adverts and their analyses. The Inspector doesn't need to have the project names programmed into it.

Project directory Images with matching analyses
arthrinova 2
bluenova 1
catto 3
client 10
latin 2
megavit 7
misc 2
serenitol 1
tokalon 1
van_kleur 16
vitalin 3
Total 48

There are 11 projects and 48 adverts or other documents. Some of the material is deliberately non-pharmaceutical, so that we can see what happens when the prompt is applied outside its principal domain. Empty findings are legitimate results. An image being present in this collection does not imply that it is a pharmaceutical advertisement.

5. Moving files between the server and my development computer

I use a Windows laptop and a Linux web server. I use SSH to run commands on the server and SCP to copy files between it and the laptop. An SSH key authenticates the developer. Its private part stays private and is not part of the Pharmex source distribution.

For example, the following illustrates copying a changed JavaScript file from a Windows Command Prompt to the release (substitute the authorised account and key path):

scp -i "<private-key-path>" red-pencil-inspector-data.js <account>@expertsystemdemos.net:/var/www/app/pharmex_release/viewer/js/

To copy a file in the other direction, put the server filename first and a local destination second. SSH allows us to inspect directory contents, compare hashes, make backups and run the installation utilities. I use batch files for repeated operations. The server-side installation utilities have preview modes so that we can see what they will do before approving changes. The Inspector itself does not use SSH or SCP and does not write server files.

6. How data is organised — logos and favicons

The logo and favicon files live in the top-level Pharmex directory. The main logo is logo.png. A favicon is the small symbol displayed on a website's browser tabs. The release contains the following files:

File Purpose
logo.png Full Pharmex logo in the Inspector.
favicon.ico Contains 16, 32 and 48 pixel versions of the favicon in one file.
favicon-16.png 16 by 16 pixel version.
favicon-32.png 32 by 32 pixel version.

During development I also used logo_core.png, containing just the blue and orange symbol without the surrounding circle and lettering, favicon-48.png, favicon_master.png and favicon_links.html. These are development assets, not files required by the clean release. They can be kept with the development materials for regenerating the branding. Strictly speaking, the ICO file could do the job on its own; the separate PNG files are for compatibility and convenience.

7. User-facing documentation

As well as the project directories, the top-level Pharmex directory contains HTML pages explaining the system.

File Purpose
walkthrough.html How to use the Inspector, the scores, findings, review indicators and reports.
about_fuzzy_logic.html An introduction to fuzzy rules and their explanations; links to further examples.
fes2.docx A longer introduction to fuzzy logic; a copy is included in the release.
aquatic.png Illustration for explaining fuzzy logic.
regulatory_compliance_concerns_2.kb Readable copy of the rule base for inspection; not the service's working rule file.

This document, how_it_works.html, provides technical documentation for the demonstration. It is not linked from the normal user-facing pages. The English analysis prompt, new3_prompt.txt, is reproduced in the appendix. Neither the prompt nor this documentation is required for normal operation of the Inspector.

8. Interactive web pages

The main page is the Red-Pencil Inspector. Its initial HTML provides the page header, navigation, project selection, status area and an initially empty main area. The JavaScript controller fills that area depending on which project and image are selected.

There are three further pages used in preparing and testing inference. They are not part of the normal review workflow.

Page in the release root Job Code included
pharmex_test_m05_both_kbs.html Test both rule bases on the same finding, at the midpoint or all 18 combinations. Inline JavaScript; shared ../inference_client.js.
pharmex_test_m05_display.html Read previously downloaded test JSON and exercise the finding display without live inference. Inline module imports Inspector components and indicator configuration.
pharmex_prepare_inference.html Discover projects, count and run the selected project's inferences, report progress and save batch JSON. Also supports all projects. Shared inference client; inline module imports catalog, data loader, download, configuration and completion library.

The Inspector also generates an enlarged interactive image page and downloadable interactive HTML reports. These are constructed by JavaScript; they are not separate HTML files stored on the server.

9. JavaScript files and how they are included

All 25 application JavaScript files in this release inventory are in viewer/js/: the 24 original release modules and the subsequently restored review-completion-bundle.js. The shared inference_client.js is one directory above the release. The preparation and test HTML pages also contain some inline JavaScript. There is no need to load all the JavaScript in every page.

The Inspector HTML contains <script type="module" src="js/red-pencil-inspector-page.js"></script>. This loads the controller, whose import statements load the modules it uses. Their imports in turn load their dependencies. The following table was checked against the release manifest and the actual import statements, including the prepared Inspector update. “Included by” means a direct importer, not every page which indirectly reaches the module. All filenames in this table are relative to viewer/js/, except HTML pages.

Module Topic and principal functions Included by
analysis-components.js Shared HTML element construction and analysis panels
node(); overview, list and detail helpers.
red-pencil-inspector-components.js
red-pencil-inspector-page.js
analysis-data.js Shared data helpers
documentInfo(), region/element accessors, box validation and diagnostic helpers.
analysis-components.js
analysis-export.js
analysis-export.js CSV generation
completeRows(), asCsv(), suggestedFilename(); also readable and recommendation row functions.
red-pencil-inspector-page.js
catalog.js Discovery, URL construction
getProjects(), getImages(), directIndexEntries(), projectUrl(), imageUrl(), resolveImageName(); checks names and index links.
pharmex_prepare_inference.html
red-pencil-inspector-data.js
red-pencil-inspector-page.js
file-download.js Browser file saving
saveBlob(): creates a downloadable object URL and releases it.
pharmex_prepare_inference.html
red-pencil-inspector-page.js
red-pencil-report-action.js
image-components.js Thumbnails and image/overlay display
createImagePane(), createThumbnailGallery(); SVG overlay and lazy thumbnails.
red-pencil-inspector-page.js
red-pencil-inspector-components.js Finding display, SVG marks, inference explanations
overview(), findingsList(), findingDetails(), pencilHighlight(), pencilDiagnostics(); reviewIndicatorDetails(), completionInspector().
pharmex_test_m05_display.html
red-pencil-inspector-page.js
red-pencil-inspector-data.js JSON loading, validation, location and score access, readable CSV
pencilFilenames(), loadRedPencil(), locations(), assessments(), diagnostics(), pencilRows(); prepared update adds loadRedPencilWithInference() and attachInference().
pharmex_prepare_inference.html
red-pencil-inspector-components.js
red-pencil-inspector-page.js
red-pencil-report-data.js
red-pencil-inspector-page.js Top-level Inspector controller
initialise(), showImage(), renderResult(), navigation, selection and export callbacks; prepared update calls augmented loader.
viewer/red-pencil-inspector.html (module script)
red-pencil-report-action.js Report export orchestration
exportRedPencilHtml(), exportRedPencilDocx(); image embedding, report model, download.
red-pencil-inspector-page.js
red-pencil-report-data.js Common data model for reports
reportFinding(), reportModel(); converts marks and their locations, scores, reasons and recommendations; includes serialised analysis.
red-pencil-report-action.js
red-pencil-zoom-action.js
red-pencil-report-docx.js Word report generation
renderRedPencilReportDocx(), createReportDocxBytes(); draws image marks to canvas, creates Office Open XML files and ZIP container.
red-pencil-report-action.js
red-pencil-report-html.js HTML report generation
renderRedPencilReportHtml(); finding index/cards, escaping, embedded data and report scripts.
red-pencil-report-action.js
red-pencil-report-image.js Portable image embedding
embeddedImageDataUrl(): fetches image and converts it to a data URL.
red-pencil-report-action.js
red-pencil-zoom-action.js
red-pencil-report-interaction.js HTML report interactivity
REPORT_INTERACTION_JS: script text for selection and highlighting.
red-pencil-report-html.js
red-pencil-report-style.js HTML report layout and printing
REPORT_CSS: CSS text embedded in generated report.
red-pencil-report-html.js
red-pencil-report-svg.js Report SVG rendering
markedDocumentSvg(): groups rectangles by finding, supplies labels and tooltips.
red-pencil-report-html.js
red-pencil-zoom-action.js
red-pencil-report-zoom-action.js Zoom from exported HTML report
REPORT_ZOOM_ACTION_JS: assembles a zoom view with embedded resources.
red-pencil-report-html.js
red-pencil-zoom-action.js Zoom from Inspector
openRedPencilZoom(): opens tab, obtains report model and SVG, builds zoom document.
red-pencil-inspector-page.js
red-pencil-zoom-html.js Zoom page construction
zoomHtmlDocument(): builds standalone HTML with image, SVG, CSS and script.
red-pencil-report-zoom-action.js
red-pencil-zoom-action.js
red-pencil-zoom-interaction.js Zoom page interactions
ZOOM_INTERACTION_JS: controls enlargement, selection and view interaction.
red-pencil-report-zoom-action.js
red-pencil-zoom-action.js
red-pencil-zoom-style.js Zoom page styling
ZOOM_CSS: embedded CSS for generated page.
red-pencil-report-zoom-action.js
red-pencil-zoom-action.js
review-indicator-config.js Names and mappings for inference
reviewIndicatorConfig.fields and .outputs; configuration of assessment and output names. Preparation calls use the live inference interface.
pharmex_prepare_inference.html
pharmex_test_m05_display.html
red-pencil-inspector-components.js
red-pencil-inspector-data.js
review-completion-bundle.js
review-indicator-explain.js Rule diagnostics in English
fuzzyRuleToEnglish(), fuzzyConditionParts(), activeRuleExplanations(), traceText(), rawDiagnosticText().
red-pencil-inspector-components.js
review-completion-bundle.js Inference, missing-score enumeration and statistics
scoresFromMark(), countCompletions(), makeCompletionBundle(), inferOne(), inferBundle(), summariseCompletions(), inferFinding(), countAnalysis(), inferAnalysis().
pharmex_prepare_inference.html
red-pencil-inspector-data.js

The extra import of the completion library by red-pencil-inspector-data.js belongs to the prepared integration update. Before that update, the preparation page uses the completion library but the normal Inspector does not. The shared modules also provide functions for other forms of analysis and presentation.

10. CSS files

The Inspector HTML links three stylesheets, all in viewer/css/.

File Topic
viewer.css General viewer layout, header, galleries, image stage, SVG overlay and status messages.
analysis.css Shared analysis panels, lists, assessment/detail layouts and diagnostic displays.
red-pencil-inspector.css Red-pencil-specific lists, findings, marks and review indicator presentation.

The exported HTML report and enlarged image have styles contained in JavaScript strings (red-pencil-report-style.js and red-pencil-zoom-style.js). These are inserted into the generated pages. The top-level explanatory and test pages have their own styles. The Word report uses Office Open XML styles rather than CSS.

11. From an advert to a review

There are three main computational stages: reading the document and producing an analysis; inferring additional indicators from the assessments; and displaying or exporting the result. They need not take place at the same time.

Advert image + English prompt
        ↓  ChatGPT
Original red-pencil JSON  ────────┐
        ↓ six assessment scores   │
Completion library → fuzzy rules  │
        ↓                         │
Saved inference JSON              │
        ↓                         ↓
        Inspector: combine in memory
                    ↓
        Display, zoom and report generators

The original analysis is kept separate from the inferred results on disk. This means that we can change the rule base or recalculate the indicators without asking ChatGPT to read the advert again. And we can display the original analysis even if inference data are missing.

12. Using ChatGPT as an editor — the prompt

To automate such analyses, I used ChatGPT. We feed it a prompt telling it to find problems with an advert, to explain why, and to recommend changes.

The prompt is written in English, in the file new3_prompt.txt. You can read it in full in the appendix. Do so now, as it is a key part of Pharmex.

The prompt tells ChatGPT to read the entire document before making marks, not to annotate everything indiscriminately, and to distinguish the nature of an apparent problem from the question of whether the advert is unlawful. It asks for coordinates of the places to be marked, reasons for assessments and recommendations. It explicitly allows one finding to have several locations, and for the system to return no marks if appropriate.

Code Meaning in the prompt Inference input
SD Scientific Dodginess: implausible or misleading scientific claims. sd
TATD Testing and Trialling Dodginess: insufficiently substantiated claims. ed
CD Teilhard de Chardin Dodginess: misuse of scientific terms or scientific authority. cf
VP Vitality Projection: impressions of health or vitality; not inherently objectionable. vpf
SC Safety Concern: indications of a relevant hazard or reason to investigate it. scf
RM Risk Minimisation: presentation that downplays a material risk. rsf

The score is a number between zero and one representing the degree of that field as judged by the model. It is not a probability of a breach, nor proof of a hazard. A field may not be assessed at all. The prompt distinguishes an unsupported claim from a scientifically false one; the lack of evidence in an advert does not establish that no evidence exists elsewhere. The explanations and recommendations therefore matter at least as much as the numbers.

13. How we call ChatGPT and get the files onto the server

I pass ChatGPT the advert as an image file and the English prompt. As directed by the prompt, it returns its results as JSON.

For the demonstration MVP, I used the browser-based version of ChatGPT to generate the analyses. This enabled me to develop and test the representation of findings, the assessment criteria, the graphical interface and the reporting facilities independently of the mechanism used to obtain the AI's results.

I wrote some Windows batch files to make parts of the process easier, including putting the resulting JSON files in the correct project directories on the server. The analysis process is therefore presently a preparation operation, not a button in the Inspector which submits a new advert to an AI. The Inspector does not upload adverts or create the analysis on demand.

In a commercial implementation, this stage would be automated using the OpenAI API: sending the image and prompt, checking the response and storing it in the same schema. The existing architecture accommodates this because the subsequent processing depends on the JSON returned by the AI, rather than on how it was obtained. The automated API path has not yet been implemented and tested.

14. The representation of an analysis

There is one JSON object per analysed image. At the top level the prompt asks for source_attachment, document and marks. The document contains a title or product name and a summary. The marks are a list of findings. Here is a simplified example of the structure, using the numbers from the prompt's example, not a particular real advert:

{
  "document": {"title_or_product": "Product Name", "summary": "..."},
  "marks": [{
    "id": "m01",
    "description": "A concern requiring attention",
    "locations": [{"text": "Visible text", "bbox": [0.12, 0.24, 0.48, 0.27]}],
    "assessments": [{"field": "SD", "score": 0.85, "reason": "..."}],
    "recommendation": "One concrete action",
    "revised_text": ""
  }]
}

A box is represented as [left, top, right, bottom], with coordinates measured as fractions of the image width and height. The top left is (0,0), the bottom right (1,1). Because the coordinates are independent of the number of pixels in the image, the same boxes work in a thumbnail-sized or enlarged display. The prompt asks for null if an image location cannot be given. The viewer checks the geometry before trying to draw it.

A finding is the semantic unit. One finding may refer to several locations and have several assessments. A score of zero is a score; the absence of an assessment is not the same thing. A document with no findings has "marks": []. The system does not need to invent findings merely to satisfy the schema.

There is no separate image-segmentation or OCR program in the release. ChatGPT proposes the regions and transcriptions as part of its analysis. They are estimates, and the editor can compare them against the original image. The viewer validates the data structurally; it does not establish whether the model's interpretation is factually correct.

16. The Inspector — finding selection and drawing the marks

red-pencil-inspector-components.js creates the document overview, findings list and finding detail panel. The list gives a quick indication of a finding's assessed fields. The detail panel shows its description, source locations, scores and reasons, recommendation and revised text, where supplied.

When the user clicks on a finding, the controller calls pencilHighlight(). The image stage already contains a transparent SVG overlay (created by createImagePane()). Its view box is 0 to 1000 in both axes. The rectangle coordinates are obtained by multiplying the normalised coordinates by 1000. The image and SVG are overlaid by CSS so they scale together. The selected finding's several boxes can be drawn at the same time. Changing the selection clears the old rectangles and draws the new ones.

The enlargement facility uses the same locations. red-pencil-zoom-action.js creates a new tab and calls the image-embedding and SVG functions. red-pencil-zoom-html.js produces the HTML for the new tab, adding the styles and interactive code from the zoom modules. The source image is not changed or painted over permanently.

17. Fuzzy logic — why and how we call it

The six assessments are deliberately different kinds of observation. A high score for Vitality Projection does not by itself mean that the advert is misleading. It becomes interesting when combined with other indications. We want to state the principles by which those observations are combined, rather than ask the language model to invent a new numerical decision each time.

The fuzzy rules calculate three further indicators: misleading-claim concern, risk-minimisation concern and review priority. A fuzzy set such as “high” has a membership function, so a number can belong to it to a degree rather than simply being inside or outside. Rules combine degrees of membership in their conditions; the inference system combines the activated output sets and obtains a numerical result from the resulting shape (the centroid). The diagnostics tell us which rules contributed and how strongly. See About fuzzy logic for the introduction.

There are two available rule bases. The JavaScript calls the shared function Inference_run() using a symbolic model name. The inference bridge in /var/inference_bridge/inference_bridge.pl maps those model names to /var/pharmex/regulatory_compliance_concerns.kb and /var/pharmex/regulatory_compliance_concerns_2.kb. The rule file in the website root is a copy for reading, rather than the file actually used by the bridge.

const response = await Inference_run(
    "regulatory_compliance_concerns_2",
    {sd: 0.5, ed: 0.96, cf: 0.57,
     vpf: 0.5, scf: 0.98, rsf: 0.85},
    ["misleading_claim_concern",
     "risk_minimisation_concern", "review_priority"],
    {diagnostics: "rules"}
);

This is the call used in our midpoint test. The returned JSON contains the model and input values, an ok indication and an outputs object. For each output the numerical result is response.outputs[name].value; the rule trace is in response.outputs[name].diagnostics.rules. The trace contains conditions, firing strengths and the output attribute and fuzzy set. Rules with zero firing strength are also present. The review-indicator-explain.js functions turn the rule information into English descriptions, with raw diagnostic data also available for inspection.

18. Missing assessments, completions and statistics

A finding may have only some of the six scores. The input to the fuzzy inference service, on the other hand, needs all six values. I did not want to assume that an unassessed score is zero, as that would be making an assertion that ChatGPT had not made.

We therefore try a series of completions of the missing scores. For each missing score we substitute 0, 0.5 and 1, keeping the assessed scores fixed. If two scores are missing there are nine combinations; if three are missing, 27. In general there are 3 to the power of the number of missing scores. If all six are missing, we skip inference rather than generate 729 wholly hypothetical combinations. An advert with no findings likewise needs no inference calls.

For example, ArthriNova finding m05 has the scores [unassessed, 0.96, 0.57, unassessed, 0.98, 0.85]. We calculate nine completions for each model. The result for each indicator is a minimum, a maximum and an average over the sampled completions. The limits are sampled limits, not mathematical guarantees of the extremes over the whole continuous input space. The average is not a probability-weighted estimate.

The program doing this is review-completion-bundle.js. scoresFromMark() makes the six-element input vector, makeCompletionBundle() enumerates the possible completions, and inferOne() calls the inference service. inferBundle() processes them sequentially. summariseCompletions() can calculate statistics from already stored results without contacting the server. The same library contains functions for counting calls and for processing an entire analysis.

If no rule for a particular output fires, the inference service returns "na" rather than a numerical centroid. The preparation program records this as an unavailable result and continues with the remaining calculations. Other numerical outputs from the same request are retained. The program also validates data types and numerical ranges, and distinguishes an unsuccessful request from an unavailable individual output. The numerical statistics are calculated separately for each indicator, from its valid numerical values. The original response and rules are preserved.

We must distinguish valid, attempted but unavailable, and not yet attempted results. If there are no valid values the statistics are null; we must not replace them by zero. If some are unavailable, the resulting statistics describe only the valid subset. The revised display is designed to show the counts and make this limitation explicit.

19. Preparing and saving inference results

The demonstration collection contains 48 adverts or other documents, with 128 findings, three of which have no assessed scores. Counting the completions gives 11,347 calls for one rule base. The important consequence is that it makes much more sense to do these calculations once than to repeat them whenever somebody looks at an advert.

The preparation page discovers projects using the same catalog module as the Inspector. It loads each original analysis, counts the calls, processes them in sequence, and provides progress and error information. We can choose the rule base and a project, or all projects. The page downloads JSON rather than attempting to write into the server's project directories directly. It can retain partially completed runs. A project with all calls attempted but some unavailable outputs is different from a project interrupted before all calls were attempted.

I wrote install_pharmex_inference.py to take the exported project files (JSON or ZIP) and distribute them as one _inference.json file per advert. It checks the source analysis fingerprint (SHA-256 of the UTF-8 encoding of the parsed analysis serialised with JavaScript's JSON.stringify), the project, filename, model, finding IDs and input combinations. It recalculates the statistical summaries from the stored responses. It has a dry-run mode and requires explicit approval to install files; the existing advert images and original analysis JSON are not changed.

The installed file records the model, substitution values, source filename and fingerprint, call counts and findings indexed by ID. Each finding's completion bundle contains the input tuples, responses, individual output errors, attempted status and statistics. The prepared Inspector loader attaches the bundle as mark.completionBundle, an ordinary property in memory. This gives the user interface and report generators access to the same information without duplicating inference or file-loading code.

The current preparation method uses Version 2 for the batch calculations. The comparison facility allows us to examine the behaviour of the two rule bases under identical inputs.

20. Exporting data and generating reports

Once the analysis is in memory, the report programs have the same data to work from as the Inspector. There are four export options.

Readable CSV. pencilRows() in red-pencil-inspector-data.js selects the relevant fields for a table: the project and image, finding ID, description, source locations, assessment field, score, reason, recommendation and revised text. asCsv() in analysis-export.js encodes rows as CSV, including correct quoting and protection against interpreting text as spreadsheet formulas in the readable export.

Complete CSV. completeRows() recursively traverses the JSON and writes its contents as paths (JSON pointers), types and values. This is useful if we want to examine information which is not included in the readable table. It is not intended to be a pleasantly formatted report. With the augmented analysis it can also include every completion and rule diagnostic without changing the traversal. Such a file can be large.

HTML and Word. The controller passes the analysis and the image URL to red-pencil-report-action.js. red-pencil-report-image.js embeds the image. red-pencil-report-data.js uses reportModel() and reportFinding() to create a common representation of the report. The HTML and Word programs then use that representation, rather than independently deciding which source locations and assessments belong to a finding.

red-pencil-report-html.js creates an HTML document containing the image, SVG outlines, finding index, descriptions and assessments. It embeds styles and interaction scripts, so the recipient can view the report without fetching the advert from the server. The report includes serialised analysis data. The report SVG groups all the rectangles of one finding; the interaction code highlights those groups. Its zoom facility reuses the same zoom-building modules as the Inspector.

red-pencil-report-docx.js creates a Word document in the browser. It draws the marks on an image using canvas and creates the Office Open XML files and ZIP structure needed for a .docx file. This does not require Microsoft Word to be running on the server. The final download in each case uses saveBlob() in file-download.js.

The existing exports cover the original red-pencil analysis. The prepared Inspector integration makes the inference bundles accessible to the complete CSV and embedded analysis data. Adding formatted inference summaries to the readable CSV, HTML and Word reports is the next integration task; this is not yet represented as a tested facility. My intention is for normal reports to give concise summaries, including the number of available results, with the detailed rule traces accessible separately.

21. Appendix — the English analysis prompt

This is the content of new3_prompt.txt in full.

Pharmex — Red-Pencil Analysis Prompt

Your task is to read a pharmaceutical or dietary supplement advertisement, or a related document, understand it thoroughly, and red-pencil passages or images that warrant attention.

Imagine you are a knowledgeable human editor using a red pencil. Identify claims, wording, pictures, omissions, or relationships between passages that raise genuine scientific, evidential, medical, safety, presentation, or potentially regulatory concerns. Do not annotate everything. Mark only matters that genuinely warrant attention.

1. THE SIX PHARMEX FIELDS

Select only the fields that genuinely apply to a particular finding. A strong score indicates a prominent instance of that field, not automatically that the product is unsafe or unlawful.

SD — Scientific Dodginess
A claim is scientifically incorrect, implausible, or misleading about physical, chemical, biological, genetic, or medical mechanisms or effects.
Examples:
- Nonexistent or misdescribed phenomena (e.g. a "Winter Equinox"), or obsolete or speculative concepts presented as established explanations.
- Impossible or unsupported biological transformations, such as a pill instantaneously turning someone into a celebrity by editing their genome.
- Misstated mechanisms or physical relationships; confusing correlation with causation.
- Extending a narrow result into a scientifically unjustified universal conclusion.
Do NOT score a claim as scientifically false merely because this particular product has not supplied evidence for it. That is chiefly TATD. Do NOT score a scientifically sound claim as SD merely because advertising it might be legally restricted.

TATD — Testing and Trialling Dodginess
A claim about this product's composition, effects, performance, or testing is insufficiently substantiated or cannot be checked from the information provided.
Examples:
- Ingredient bait-and-switch: presenting evidence about an isolated ingredient as proof that the complete product, at an unspecified dose, has the same effect.
- Unverifiable citations, numerical claims, or trial results without an identifiable study or usable source.
- Missing key trial details, such as sample size, comparator, effect magnitude, confidence interval, relevant safety outcomes, or study registration, when needed to evaluate the particular claim.
- Confusing taste, packaging approval, testimonials, or subjective satisfaction with proven therapeutic benefit.
An unsupported claim is not necessarily false, and lack of evidence in the advert does not prove that no evidence exists elsewhere. Do not demand full clinical-trial reporting for every ordinary ingredient or factual statement. Judge the degree of evidence appropriate to the strength of the claim.

CD — Teilhard de Chardin Dodginess
Language borrows legitimate scientific terms or the style of scientific explanation to give a misleading impression of technical meaning or authority.
Examples:
- "Quantum", "cellular matrix", "bio-frequency", "DNA-level", "vibrational plane", or "nano-robots" used without the relevant defined scientific meaning.
- Mystical forces, magic, or cosmic energies presented as scientifically verified mechanisms.
- Real technologies such as CRISPR-Cas9 or AI combined with imaginary processes as though the resulting system were established.
- Undefined technical-sounding phrases that falsely imply measured precision.
An ordinary, recognisable metaphor is not automatically a problem. Judge whether the wording misleadingly claims scientific authority.

VP — Vitality Projection
Words or imagery create an impression of enhanced health, vitality, youth, beauty, strength, endurance, happiness, confidence, or personal freedom.
Examples:
- Extraordinary transformation of sporting, romantic, professional, or social life.
- Rejuvenation, freedom from fatigue, idealised appearance, or apparently effortless performance.
- Manipulative before-and-after imagery or imagery implying benefits beyond what the product claims can support.
VP is descriptive and NOT inherently objectionable. Include it when it materially contributes to a marked finding, especially through an unsupported or misleading benefit impression. Do not mark or recommend changing legitimate positive imagery solely because it is positive.

SC — Safety Concern
Visible wording or imagery indicates, or provides adequate grounds to investigate, a medical, biological, or other relevant hazard of the product or its proposed use.
Examples:
- Potentially toxic substances or dangerous physiological effects.
- Unsupported or excessive doses, hazardous self-adjustment of dosage, or unsafe delivery methods.
- Specific contraindications, interactions, vulnerable populations, or handling/storage hazards signalled by the document.
- A consequential safety omission where the visible product claim or directions make that missing information materially relevant.
Distinguish actual established hazards, plausible concerns, and mere unknowns. Do not invent ingredients, adverse reactions, exposure pathways, or interactions. A plainly stated appropriate warning is not itself an editorial defect merely because it mentions a danger.

RM — Risk Minimisation
Words, pictures, or layout downplay, conceal, normalise, or trivialise a material risk.
Examples:
- "Just a smidgen" used to trivialise potentially hazardous content.
- Dangerous effects promoted as attractive benefits.
- Serious warnings in tiny, low-contrast, obscured, or poorly positioned text.
- Benefits emphasised so heavily that the accompanying risk information is misleadingly inconspicuous.
- Casual dosing advice that suppresses the seriousness of a hazard.
RM can depend on distant, nonadjacent passages. Evaluate the entire presentation, not merely isolated wording. Do not infer risk suppression merely because a hazard or warning is mentioned.

2. UNDERSTAND THE WHOLE DOCUMENT FIRST

Read the complete document before making any marks. Consider what an ordinary reader would reasonably understand, including:
- Claims the advertiser endorses versus quotations, criticism, satire, jokes, and clearly figurative language.
- Causal relationships, qualifications, contradictions, and omissions.
- Links between distant passages, such as a promise of benefit earlier and a limiting warning much later.
- Interactions between pictures and text; scientific statements that appear to legitimise unrelated assertions.
Use relevant ordinary scientific and medical knowledge, but do not invent facts, studies, product properties, warnings, or hazards. A humorous expression can still mislead, but do not read every joke as a literal scientific assertion.

REGULATORY CAUTION
Scientific correctness, evidential support, and legal permissibility are different questions. Regulations depend on product classification, intended audience, jurisdiction, and the exact claim. Do not assume that US FDA/FTC rules govern every document. Do not assume all supplement disease-risk-reduction claims are categorically forbidden. When a regulatory concern is clear, explain it cautiously and identify the relevant jurisdiction only if known. Do not give it an SD score merely for being potentially legally restricted. If a significant regulatory-only concern falls outside all six fields, it may have an empty assessments array rather than a fabricated score.

3. APPLY YOUR RED PENCIL

Identify distinct findings that genuinely call for editorial review or action. For each finding:
1. Identify the precise offending or relevant words, image, or visible context.
2. Mark the smallest practical location(s) that support the finding. When a statement spans lines, use multiple tight boxes if useful.
3. Where the finding relies on several distant passages, record several locations within ONE finding; do not force them into a single bounding box.
4. Write a short description of the overall problem or concern.
5. Assign the applicable Pharmex field assessments, each with a score and reason tied to visible evidence.
6. Give ONE consolidated recommendation addressing the finding as a whole, rather than one repetitive recommendation per field.
If two genuinely different corrections are required, separate findings may overlap. Do not create duplicate findings about essentially the same problem.

For omissions, there is no invisible text to surround with a pencil. Mark the visible passage (such as a dosing instruction, benefit claim, or safety statement) that makes the omitted information relevant; explain the omission in the description and reason. Never invent coordinates for absent content.

4. SCORE THE FINDINGS

Each applicable field receives a score from 0.0 to 1.0. Suggested anchors:
0.1 very weak; 0.25 weak; 0.5 moderate; 0.7 moderately strong; 0.85 very strong; 1.0 unmistakable or extreme.
Intermediate values are allowed. Include only applicable fields with scores greater than zero. Each assessment needs a concise, specific explanation.

A field score is not a severity rating, a regulatory verdict, or a prediction of harm. In particular, a high VP score does not automatically justify a recommendation to remove an otherwise truthful positive message.

5. RECOMMEND CORRECTIONS

Each finding should have one concrete, proportionate recommendation. It may call for:
- Correcting, qualifying, substantiating, or removing a claim.
- Supplying an identifiable study reference and the evidence necessary to evaluate a claimed result.
- Clarifying misleading scientific terminology.
- Making verified safety information clearer or more prominent.
- Investigating formulation safety or suspending promotion where unresolved risks are sufficiently serious.
Prefer the smallest effective change unless a more fundamental problem demands a more fundamental response. Do not pretend that adding a disclaimer makes an unsafe product safe or that supplying a citation proves a claim valid. Do not recommend reducing or concealing legitimate warnings just to make the advert look better.

Provide revised_text only when you can responsibly propose specific replacement wording. Otherwise use "". Do not invent reassuring efficacy or safety wording.

6. RECORD LOCATIONS AND BOUNDING BOXES

For each marked location record:
- text: the exact visible words, if any; otherwise "" for a nontextual image feature. Copy faithfully, including misspellings; do not silently correct OCR or visible text.
- bbox: [left, top, right, bottom], equivalently [xmin, ymin, xmax, ymax], each coordinate normalised from 0.0 to 1.0 relative to the COMPLETE image.

IMPORTANT: This is the Pharmex convention. NEVER use [ymin, xmin, ymax, xmax].
A genuine bounding box must have left < right and top < bottom. Do not use placeholder zero-area boxes. Mark the actual text or image rather than surrounding unrelated paragraphs.

Put the primary location (normally where the change is needed) first. Follow it with supporting locations, even if distant on the page. The viewer will calculate centroids, areas, and display order: do NOT calculate them in the JSON.

If the input contains plain text but no page image, use bbox: null for every location. Do not invent geometric coordinates.

7. FINAL REVIEW

Check for findings involving interactions between distant passages and images, especially safety disclosures and claims of proof. Ensure that scientific inaccuracy, insufficient product evidence, misleading jargon, vitality projection, safety concern, and risk minimisation have been considered, but do not create marks just to use every field.

Return the findings in approximate document reading order based on the primary location. An empty marks array is legitimate if there are no problems worthy of marking. Avoid repetitive recommendations and unnecessary over-annotation.

8. JSON OUTPUT

Return ONLY one valid JSON object, with no introductory words, no trailing commentary, and NO Markdown code fences. Use the following shape as a TEMPLATE, not as actual findings:

{
  "source_attachment": {
    "filename": "image_filename.png",
    "path": ""
  },
  "document": {
    "title_or_product": "Product Name",
    "summary": "Brief, factual summary of the document"
  },
  "marks": [
    {
      "id": "m01",
      "description": "One specific concern requiring editorial attention",
      "locations": [
        {
          "text": "Exact visible text to be marked",
          "bbox": [0.12, 0.24, 0.48, 0.27]
        }
      ],
      "assessments": [
        {
          "field": "SD",
          "score": 0.85,
          "reason": "Brief explanation grounded in the visible content"
        }
      ],
      "recommendation": "One concrete action addressing the finding",
      "revised_text": ""
    }
  ]
}

JSON RULES
- Record the actual uploaded filename in source_attachment.filename, and use "" for source_attachment.path unless a path was supplied.
- Use unique IDs m01, m02, m03, and so on.
- Use only the field codes SD, TATD, CD, VP, SC, RM.
- The example numbers, wording, and boxes are placeholders, NOT findings; replace them with observations based on the actual input.
- Scores and coordinates must lie in [0, 1]. Bboxes must use [left, top, right, bottom] with positive width and height, or null when an image is unavailable.
- Escape quotation marks, backslashes, and line breaks correctly in JSON strings.
- Include all locations linked to one finding in that finding's locations array.
- Use "marks": [] when no findings warrant attention.
- Return valid JSON only; no Markdown fences or explanations outside the JSON object.

22. Testing and current state of the release

We have tested the system at several levels, because a correct result at one level does not imply correctness at the others.

Test Result / scope
Release construction and catalog discovery The preparation page discovered all 11 projects and 48 image/analysis pairs in the release.
Inspector user interface Browser tests covered project selection, image and findings display, finding selection and highlighting. CSV, HTML and Word reports have been generated; final checks of the release exports remain part of the integration work.
Inference interface 18 calls (nine per rule base) for ArthriNova m05 returned numerical outputs and rule diagnostics. Saved JSON used in a separate display test, independently of the service.
Inference preparation and rule coverage Counting the combinations across the collection gave 11,347 calls per rule base. Batch tests confirmed the availability of numerical results and rule traces, including cases in which no priority rule fires. Complete and partial exports were retained for testing.
Inference library Tests of recorded responses, unavailable or invalid outputs and incomplete statistics passed. Live testing confirmed that batch processing continues when an output is unavailable. The full batch calculation was not yet verified at the time of writing.
Installation utility The installation utility verified and installed all 16 advert records in the first export, including complete and partial results. Tests checked that original analyses were preserved by comparing SHA-256 hashes, and that the recalculated statistics agreed with the JavaScript library.
Prepared Inspector integration Tests of the prepared modules used 14 inference files and a simulated browser document, covering missing or out-of-date files, unassessed findings, unavailable outputs and rule diagnostics. The complete CSV traversal included the attached data. Deployment and end-to-end browser verification remain to be confirmed.

The rule traces give us a useful way to assess the coverage of the knowledge bases: for example, they identify combinations of inputs for which no review-priority rule fires. This makes the system useful for examining and refining the rules themselves, as well as for reviewing adverts.

The Client project provides a particularly useful collection of examples for evaluating the system's analyses. A further stage of evaluation would be to examine these results with specialists in pharmaceutical advertising, assessing the appropriateness of the findings, scores and recommendations, and refining the prompt and assessment criteria where necessary. Such specialist evaluation remains to be completed.

The remaining integration work is to verify the Inspector update in the release, install the full set of precalculated results, incorporate formatted inference summaries in the readable reports, and check the combined system in the browser. The demonstration is intended to assist human reviewers. These engineering tests establish aspects of software behaviour, not regulatory accuracy or clinical validity; specialist evaluation is a separate task.

Inventory basis: the 30 November file-hash inventory, the release-building script and viewer release manifest, the archived viewer and top-level source, the revised preparation/inference modules, the installer and its test report, and the prepared Inspector update with its test results. The inventory describes the documented release and confirmed additions as at 30 November 2026.

23. Bringing the ideas together

Pharmex brings together several innovative ideas: the semiotic heatmap, the red-pencil model of editorial review, the ability of language models to interpret words and pictures together, and the use of explicit fuzzy-logic rules to reason about the resulting assessments.

What I find particularly exciting is what we can do by combining them. We can relate a claim to a picture, a qualification or a warning elsewhere in a document; record what is of concern and why; and examine how the rules translate those observations into indicators for review. The findings can then be used as the basis for discussion between copywriters, editors, scientific advisers and regulatory specialists.

Although we have developed Pharmex with pharmaceutical advertising in mind, the underlying ideas have a much wider potential. We can develop new assessment criteria and rules without having to reinvent the way we represent and examine documents. The aim is to make intelligent document review not only more systematic, but also more informative and more open to human judgement.