<?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 Simon Loffler on Medium]]></title>
        <description><![CDATA[Stories by Simon Loffler on Medium]]></description>
        <link>https://medium.com/@simon.loffler?source=rss-5568cbfd8c73------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*9XL3P6yE6fbMY8kWNPKo3Q.jpeg</url>
            <title>Stories by Simon Loffler on Medium</title>
            <link>https://medium.com/@simon.loffler?source=rss-5568cbfd8c73------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 25 Nov 2026 02:03:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@simon.loffler/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[Labels, captions, and video players]]></title>
            <link>https://medium.com/@simon.loffler/labels-captions-and-video-players-4a48b7d3cabc?source=rss-5568cbfd8c73------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a48b7d3cabc</guid>
            <category><![CDATA[labels]]></category>
            <category><![CDATA[museums]]></category>
            <category><![CDATA[translation]]></category>
            <category><![CDATA[videos]]></category>
            <category><![CDATA[musetech]]></category>
            <dc:creator><![CDATA[Simon Loffler]]></dc:creator>
            <pubDate>Sun, 24 May 2026 23:40:40 GMT</pubDate>
            <atom:updated>2026-06-26T07:44:32.454Z</atom:updated>
            <content:encoded><![CDATA[<p>We recently launched a new exhibition with <a href="https://2026.rising.melbourne/program/the-vinyl-factory-reverb">RISING</a>, <a href="https://www.acmi.net.au/whats-on/the-vinyl-factory-reverb/">The Vinyl Factory: Reverb</a>. It explores sound and social movements through vinyl culture.</p><p>My team at ACMI had the fun job of building new technology to support and extend the visitor’s experience.</p><figure><img alt="Inside the RISING/ACMI The Vinyl Factory: Reverb exhibition, 100 records on the walls, a giant pink speaker system sculpture at the end of the hallway." src="https://cdn-images-1.medium.com/max/1024/1*cUB_lEKuraY90Ktdz_JPlA.jpeg" /><figcaption>Inside Reverb. Photo: Eugene Hyland</figcaption></figure><h3>Digital labels</h3><p>During the ACMI renewal we built <a href="https://github.com/acmilabs/playlist-label">digital museum exhibition labels</a> that pull their content from XOS, our museum exhibitions system (CMS), and also have the ability to synchronise playback bars with video players.</p><p>For Reverb we added a new design template to help highlight when the video starts again using our existing RabbitMQ message synchronising service.</p><p>We also wanted to extend the accessibility of our museum labels to other languages, so added Simplified Chinese, Hindi and Punjabi translations using gpt-5.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ilmRl43Qc7xeYBqfxrjrpg.jpeg" /><figcaption>ACMI access labels</figcaption></figure><h3>Video captions</h3><p>To provide visitors with video captions/subtitles without compromising the visual aesthetic of the Reverb artworks, we built a synced captions viewer component for our website using Codex agents.</p><p>This uses the same RabbitMQ synchronising service as our existing video players and digital labels, and also keeps the latest video caption highlighted and on the middle of the screen in time with the video’s audio track.</p><p>We then translated these video captions to Simplified Chinese, Hindi and Punjabi using gpt-5.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ef6CdDneAGqgYalbYKeqoA.jpeg" /><figcaption>ACMI access captions</figcaption></figure><h3>Video players</h3><p>The Reverb artists’ preferred video playback computers were Mac Minis, so to enable seamless integration with our existing digital labels and captions viewer we ported our Python <a href="https://github.com/acmilabs/media-player">media player code</a> to SwiftUI using Codex agents.</p><p>This enabled us to use the Apple Test Flight and App Store deployment systems for macOS, AppleTV, iOS and iPadOS devices.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MS2pvZ8EJr5zFZUxWvgHHw.png" /><figcaption>ACMI Apple video players running on macOS, AppleTV, iPhone, and iPad simulators</figcaption></figure><p>Apple Media player code: <a href="https://github.com/acmilabs/apple-media-player">github.com/acmilabs/apple-media-player</a></p><p>You can find it in the Apple Mac App Store: <a href="https://apps.apple.com/us/app/acmi-media-player/id6754896867?mt=12">apps.apple.com/us/app/acmi-media-player/id6754896867</a></p><p>Try it out with our test base URL: https://acmi-public-api.s3.ap-southeast-2.amazonaws.com/media-player/</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YvBx0-yR3_Q7k5wx2BuOaA.jpeg" /><figcaption>Photo: Eugene Hyland</figcaption></figure><h3>Translations</h3><p>The amount of labels and captions to translate meant we needed to build a pipeline for computers to translate the video’s audio speech-to-text, and also an interface for humans to validate and edit them.</p><p>We reused our existing off-line <a href="https://github.com/openai/whisper">Whisper</a> speech-to-text pipeline so we could perform all of the text generation on our in-house computers, and then used cloud-based gpt-5 integrated in XOS for the translations.</p><p>This pipeline allows us to generate multi-language museum label and video captions translations with one button press, and then edit them inline while watching the source video.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QMD9ab3FiwS77VN8rtLPiQ.png" /><figcaption>XOS video captions editor interface</figcaption></figure><p>We’re also experimenting with a digital label translations review system that makes use of large language models to suggest where translation drift might have happened.</p><p>To do this our pipeline:</p><ul><li>Sends our gpt-5 translations to the Google Translate API to translate back to English</li><li>Passes our original English text, translated text, and translated-back English text to a language model to highlight potential issues</li><li>Populates a dashboard for ACMI staff to review</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hHy9LsIySGHfBlQMA9cvZg.png" /><figcaption>XOS museum label translations dashboard</figcaption></figure><p>We hope that using two different models to translate to and from English will help discover problems that one might have been over-confident on due to its pre-and-post-training data and techniques.</p><p>If any of these projects are on interest to you or your organisation, please <a href="https://www.acmi.net.au/contact/">get in touch</a> so we might be able to build something together.</p><figure><img alt="Three record players with a hand reaching out to play one of them. Coloured records on the wall in the background with a bright white backlight." src="https://cdn-images-1.medium.com/max/1024/1*rVePI28QeIwbMytLneidcw.jpeg" /><figcaption>Photo: Eugene Hyland</figcaption></figure><h3>Try it out for yourself</h3><p>If you’d like to experience the result of all of this in person, please <a href="https://www.acmi.net.au/whats-on/the-vinyl-factory-reverb/">buy a ticket to see Reverb</a>, and scan the QR codes on the museum labels to see the access captions and labels: <a href="https://access.acmi.net.au/">access.acmi.net.au</a></p><figure><img alt="QR code that takes you to the ACMI Access Guide website." src="https://cdn-images-1.medium.com/max/500/1*JqkQrNBGQcyeyu9WW9fQfg.png" /></figure><h3>Our AI use</h3><p>It’s worth noting that this would have been very difficult to build in the timeframe we had without using AI.</p><p>We have access to Claude, GPT+Codex, and Grok at work — and used Codex-5.4/5 agents for the majority of code in this project.</p><p>We acknowledge the energy use associated with training these models, and I make best efforts to offset this using solar+batteries+electric vehicles. Where we can we use local models on-site.</p><p>We’ve found that selective use of AI tools has enabled us to automate repetitive tasks across teams at ACMI, giving them more time to be creative and experimental in their work.</p><figure><img alt="Photo of a listening room with visitors sitting on comfortable seating, a brightly lit record player on stage, surrounded by two giant high quality speakers." src="https://cdn-images-1.medium.com/max/1024/1*LkF9aQYWhNGIuGXA_DJ2Mw.jpeg" /><figcaption>Photo: Eugene Hyland</figcaption></figure><p>This article contributed to <a href="https://labs.acmi.net.au/digital-labels-synced-captions-and-ai-translations-3e980ca62854"><strong>Digital labels, synced captions and AI translations</strong></a> by my team lead, Head of Digital Products &amp; Interaction Design at ACMI, Lucie Paterson.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a48b7d3cabc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The website is slow]]></title>
            <link>https://labs.acmi.net.au/the-website-is-slow-5cf0938c77ab?source=rss-5568cbfd8c73------2</link>
            <guid isPermaLink="false">https://medium.com/p/5cf0938c77ab</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[agents]]></category>
            <category><![CDATA[museums]]></category>
            <category><![CDATA[speed]]></category>
            <category><![CDATA[website]]></category>
            <dc:creator><![CDATA[Simon Loffler]]></dc:creator>
            <pubDate>Sun, 01 Mar 2026 23:58:12 GMT</pubDate>
            <atom:updated>2026-03-01T23:58:12.102Z</atom:updated>
            <content:encoded><![CDATA[<p>This was a regular post that we saw in our internal Slack channels. Staff would post a link to a slow page on the ACMI website, and the organisation would quickly open it in every combination of browser/device/operating system and report back, usually with “It’s working for me”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RPU5BqcTHWqAYgCex3p25g.png" /><figcaption>The ACMI website home page</figcaption></figure><p>So that was the first clue, once someone reported an issue, the issue mysteriously went away. The watched machine never breaks? But it did trigger some vague memories of meetings with external website developers ~5 years ago mentioning enabling caching so the website was speedy.</p><h3>Validating the code</h3><p>My first instinct as a software developer was to check the code.</p><ul><li>Do we even have caching enabled?</li><li>How long does it cache for?</li><li>What is being cached?</li><li>How can we validate caching on developer laptops, staging infrastructure, and production?</li></ul><p>The first three answers were relatively easy to find: yes, 10 minutes, backend API calls &amp; frontend assets… but the last question took a bit longer.</p><p>We use Django &amp; Wagtail for our website backend, so I could quite easily set my local caching to match our production setup:</p><pre># development.py<br>CACHES = {<br>    &quot;default&quot;: {<br>        &quot;BACKEND&quot;: &quot;django.core.cache.backends.filebased.FileBasedCache&quot;,<br>        &quot;LOCATION&quot;: os.path.join(BASE_DIR, &quot;cache&quot;),<br>        &quot;KEY_PREFIX&quot;: &quot;wagtailcache&quot;,<br>    }<br>}</pre><p>As expected, after the first query the website was quite fast. But the second clue was the type of cache we were using: <strong>FileBasedCache</strong></p><p>It sounded fine to me, cache requests to disk, and load them from disk. Excellent.</p><p>When I tried replicating the same queries on our Staging server I noticed that only one in ten or so queries were fast. The rest seemed to still be loading up the cache. The dreaded intermittent bug.</p><h3>Step away from the keyboard</h3><p>Over my many years of programming this is still one of the best techniques to help debug all of the things — take a break and think of something completely different. In this case it was lunch. A visit to the Adelaide central markets and a delicious salad sandwich.</p><p>While I walked, my subconscious was free to explore any logical reason why the file-based cache could have been intermittent (because all computer problems are thankfully logical when you dig deep enough). Maybe asubtle config issue between development and staging/production? (No, I’d validated the same dependencies and config). Maybe the location of the temporary file being written was changing rapidly? (No, files were there and persistent long after 10 minutes).</p><p>I was two bites into my sandwich when it occurred to me — we have replicas in our staging/production infrastructure. These exact copies of the frontend and backend servers allow our website load balancer to evenly distribute lots of website traffic to the server with the least load so we can handle big launches, email blasts, viral social media posts, and bots. But these replicas also mean the file system cache was being spread across those extra copies — meaning a request would have to be coming into the exact same replica pod to be cached! A theory to test.</p><h3>Collaboration is hard</h3><p>At ACMI we love collaborating on projects — physical builds with external partners, software projects, and complete exhibitions. It helps up-skill ACMI staff and give us agency to iterate and/or tour without needing expensive ongoing Service Level Agreements.</p><p>With collaboration comes complexity, and in this case this complexity was what caught us out. We collaborated with external partners on building the website, sharing code creation, feature additions, and maintenance. ACMI was in control of the infrastructure so we could quickly scale up and out as our traffic peaked and lulled (saving money!).</p><p>Unfortunately, this also meant a slight disconnect between the code and the servers, they didn’t need to know about how our replica servers worked — it just auto-deployed magically, and we didn’t need to know every detail about how they’d implemented caching.</p><h3>Testing the sandwich theory</h3><p>To validate my sandwich’s ideas about file system caching and replicas being the cause, I turned to my trusty large language model to spin up a shared Redis cache server in a docker container. One minute later it was running on my laptop, and caching was working again, this time from a shared service all pods and replicas could use.</p><p>Next I asked the language model to update our infrastructure and auto-deployment to include the same Redis container, and update our configuration to test on Staging.</p><p>Wooosh! It was one of those moments when I had to try all of my dozens of internet connected devices across WiFi/5G to really believe it had worked. But it had. Glorious.</p><p>The theory was validated — when all replica servers shared the same cache they were all able to benefit.</p><h3>Yes, but how much extra did it cost?</h3><p>When adding a new service there’s always a cost associated, and it was time to consult our technology strategy — move everything to the cloud, hosted if possible to reduce technical debt.</p><p>The quote for a production-grade two-replica hosted Redis server was $500/month. Probably worth it when compared to a human software developer maintaining the same service, but much more expensive than a language-model maintained service.</p><p>It was agreed that we would try deploying our own service to our infrastructure-as-code servers, after all, we spent a bunch of developer time and money during our museum redevelopment to build it for this exact purpose. Total cost: 2 hours to setup and deploy with the LLM.</p><h3>Always watch the logs</h3><p>There’s always an unknown-unknown when deploying your own software, and this time the memory configuration of Redis was the thing that caught us out.</p><p>We’d given Redis no idea of its pod memory limit — on Staging that wasn’t a problem because we didn’t have much traffic, but sure enough thirty minutes into the production deployment we saw the memory hit its conservative limit and the pod cycle itself, complaining about us not letting it know it was about run out of memory. Sorry pod.</p><p>A quick prompt and configuration update later, and we were back up and running with a reasonable memory limit for our new four-hour cache. Here’s what our pod needed — to know its maximum memory available, and to discard the oldest least-used cache keys first when the limit was hit (instead of rolling over and playing dead):</p><p>--maxmemory 768mb --maxmemory-policy allkeys-lru</p><h3>Look mum, no hands!</h3><p>In the past, the time from prototype of a new service to testing and deployment would have taken a few weeks. Reading the documentation for the service, trying to implement the service, finding out that the documentation is old, updating the prototype, then working out how to translate that to production language/frameworks/services.</p><p>In the last couple of months language models have radically improved, to the point that collaborating with them is less like hand-holding a fresh graduate and more like pair-programming with a mentor. This huge increase in capability makes most software tasks reduce from days to minutes. The overhead in checking and understanding the changes is still there, but it’s also moved on from making sure it is technically correct, to just making sure the style is matched to the codebase.</p><p>This shift has also been helped by moving from copy/pasting/autocompleting snippets of code, to command-line agents with the ability to build, self-reflect, and most importantly learn from the way we debug/lint/test our code ourselves. Watching them loop between updating the code, running tests, fixing their bugs, and doing review flows on their own work is a pretty magical experience.</p><h3>Wrap it up, Simon</h3><p>Yes, this is very long-winded way of saying “we fixed our website cache”, but we thought it might be useful for others to learn from. Collaboration is cool, and hard, and there will be dragons, Machines and automation areawesome, and fun/frustrating to debug, but they’re growing up quickly so keep engaging with them!</p><p>Also, did you notice the difference in speed? <a href="https://www.acmi.net.au/">acmi.net.au</a></p><p>p.s. This post was written entirely by me, after offloading my software development work to a language model.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5cf0938c77ab" width="1" height="1" alt=""><hr><p><a href="https://labs.acmi.net.au/the-website-is-slow-5cf0938c77ab">The website is slow</a> was originally published in <a href="https://labs.acmi.net.au/">ACMI LABS</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Supercuts]]></title>
            <link>https://labs.acmi.net.au/supercuts-89ef23409ea3?source=rss-5568cbfd8c73------2</link>
            <guid isPermaLink="false">https://medium.com/p/89ef23409ea3</guid>
            <category><![CDATA[musetech]]></category>
            <category><![CDATA[search]]></category>
            <category><![CDATA[videos]]></category>
            <category><![CDATA[supercut]]></category>
            <category><![CDATA[museums]]></category>
            <dc:creator><![CDATA[Simon Loffler]]></dc:creator>
            <pubDate>Mon, 02 Jun 2025 02:34:20 GMT</pubDate>
            <atom:updated>2025-06-02T03:08:08.725Z</atom:updated>
            <content:encoded><![CDATA[<h3>Creating a Supercut Generator for the ACMI video collection</h3><p>One of the most popular interactives in ACMI’s Story of the Moving Image is the <a href="https://www.acmi.net.au/edit-line/?id=45394fd6-a232-48c4-a5ff-bba4ad8d16b0">Edit Line</a>. It enables visitors to create a supercut — which is a montage of short clips — from <a href="https://www.acmi.net.au/stories-and-ideas/iconic-film-and-tv-moments/">iconic film and tv show moments</a>. Visitors move blocks around to compile their own scene of clips. Our inspiration was fridge magnet poetry.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oNco_i8qUM6Tc3ic-jxPyQ.jpeg" /><figcaption>Photo by <a href="https://www.kathrynbeane.com/home/acmi">Kathryn Beane</a></figcaption></figure><p>For a long time we wondered how we could extend that experience to make use of the ACMI video collection, and our recent work on <a href="https://medium.com/acmi-labs/video-image-search-94bed300ca22">auto-generating video image frame captions</a> have provided us the tools to do this. So, what would it look like to deliver search results as a cut sequence?</p><h3>The prototype</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplayer.vimeo.com%2Fvideo%2F1079666435%3Fh%3D465a87f9d5%26app_id%3D122963&amp;dntp=1&amp;display_name=Vimeo&amp;url=https%3A%2F%2Fvimeo.com%2F1079666435%2F465a87f9d5&amp;image=https%3A%2F%2Fi.vimeocdn.com%2Fvideo%2F2010102714-3f182df8b94da067654bd93266bf201e5fa42506329efe5613ecdf8771d75c60-d_1280&amp;type=text%2Fhtml&amp;schema=vimeo" width="1920" height="1080" frameborder="0" scrolling="no"><a href="https://medium.com/media/2c45c42341ccdb8fea642eec24dfa5f7/href">https://medium.com/media/2c45c42341ccdb8fea642eec24dfa5f7/href</a></iframe><p>Using our <a href="https://github.com/ACMILabs/video-search">video search</a> code as a base, we started exploring existing video editing tools in Python to automate the process.</p><p>New York-based artist Sam Lavigne’s, <a href="https://github.com/antiboredom/videogrep">Videogrep</a> is an excellent supercut generator, but requires video files to be available locally. Seeing all of our collection videos are securely stored on cloud services in the cloud, we started building using <a href="https://pypi.org/project/moviepy/">MoviePy</a>.</p><p>Video editing takes a long time, so our first task was to add an event stream API so we could update visitors on how progress is going:</p><pre>@application.route(&#39;/supercut_progress/&lt;task_id&gt;&#39;)<br>def supercut_progress(task_id):<br>    &quot;&quot;&quot;<br>    Stream progress updates for supercut generation via EventSource.<br>    &quot;&quot;&quot;<br>    def generate():<br>        while True:<br>            with lock:<br>                task = supercut_tasks.get(task_id)<br>                if task:<br>                    if task[&#39;status&#39;] == &#39;in_progress&#39;:<br>                        yield f&quot;data: {task[&#39;progress&#39;]}\n\n&quot;<br>                    elif task[&#39;status&#39;] == &#39;saving&#39;:<br>                        yield f&quot;data: {task[&#39;status&#39;]}\n\n&quot;<br>                    elif task[&#39;status&#39;] == &#39;completed&#39;:<br>                        if task[&#39;filename&#39;]:<br>                            yield f&quot;data: completed {task[&#39;filename&#39;]}\n\n&quot;<br>                        else:<br>                            yield &quot;data: no_clips\n\n&quot;<br>                        break<br>            time.sleep(1)  # Poll every second<br>    return Response(generate(), mimetype=&#39;text/event-stream&#39;)</pre><p>Now we’re ready to hand our video search results (video URL and JSON captions) to MoviePy to cut up the original videos and splice them back together. The steps are:</p><ul><li>Load the videos</li><li>Cut the sections that have the search term(s) with 0.5 seconds padding either side</li><li>Resize the clips to the output resolution of 720p</li><li>Add a background colour if the clip is in a different ratio to the output</li><li>Update the frontend that we’ve completed a video and move onto the next one</li><li>Join the clips together to make one video</li><li>Create a poster image for the video</li></ul><p>Here’s what that looks like in Python:</p><pre>def generate_supercut_background(query, search_results, task_id):<br>    &quot;&quot;&quot;<br>    Run supercut generation in a background thread and update task status.<br>    &quot;&quot;&quot;<br>    filename = f&#39;supercut_{slugify(query)}.mp4&#39;<br>    output_path = f&#39;app/static/videos/{filename}&#39;<br>    total_clips = sum(<br>        1 for result in search_results[&#39;hits&#39;][&#39;hits&#39;]<br>        for segment in result[&#39;_source&#39;][&#39;transcription&#39;][&#39;segments&#39;]<br>        if query.lower() in segment[&#39;text&#39;].lower()<br>    )<br>    total_clips += 1  # add resize<br>    clips = []<br>    processed_clips = 0<br><br>    for result in search_results[&#39;hits&#39;][&#39;hits&#39;]:<br>        video_path = result[&#39;_source&#39;][&#39;web_resource&#39;]<br>        for segment in result[&#39;_source&#39;][&#39;transcription&#39;][&#39;segments&#39;]:<br>            if query.lower() in segment[&#39;text&#39;].lower():<br>                video = VideoFileClip(video_path)<br>                # Extend clip by 0.5 s on either side, but keep within the video’s bounds<br>                start_time = max(float(segment[&#39;start&#39;]) - 0.5, 0)<br>                end_time = min(float(segment[&#39;end&#39;]) + 0.5, video.duration)<br>                try:<br>                    clip = video.subclipped(start_time, end_time)<br>                    clips.append(clip)<br>                except ValueError:<br>                    pass<br>                processed_clips += 1<br>                progress = (processed_clips / total_clips) * 100 if total_clips &gt; 0 else 100<br>                with lock:<br>                    supercut_tasks[task_id][&#39;progress&#39;] = progress<br><br>    if clips:<br>        target_resolution = (1280, 720)<br>        resized_clips = []<br>        for clip in clips:<br>            # Resize to fit within target_resolution, preserving aspect ratio<br>            resized_clip = clip.resized(height=target_resolution[1])  # Scale based on height<br>            if resized_clip.w &gt; target_resolution[0]:  # If too wide, scale based on width instead<br>                resized_clip = clip.resized(width=target_resolution[0])<br><br>            # Create a colored background clip<br>            background = ColorClip(size=target_resolution, color=(0, 0, 0), duration=clip.duration)<br><br>            # Center the resized clip on the background<br>            padded_clip = CompositeVideoClip([background, resized_clip.with_position(&#39;center&#39;)])<br>            resized_clips.append(padded_clip)<br><br>        processed_clips += 1<br>        progress = (processed_clips / total_clips) * 100 if total_clips &gt; 0 else 100<br>        with lock:<br>            supercut_tasks[task_id][&#39;status&#39;] = &#39;saving&#39;<br><br>        supercut = concatenate_videoclips(resized_clips, method=&#39;compose&#39;)<br>        Path(&#39;app/static/videos&#39;).mkdir(exist_ok=True)<br>        supercut.write_videofile(<br>            output_path,<br>            codec=&#39;libx264&#39;,<br>            audio_codec=&#39;aac&#39;,<br>            preset=&#39;veryfast&#39;,<br>            bitrate=&#39;2000k&#39;,<br>            threads=multiprocessing.cpu_count(),<br>        )<br><br>        frame = supercut.get_frame(1.0)<br>        frame_image = Image.fromarray(np.uint8(frame))<br>        if frame_image.mode == &#39;RGBA&#39;:<br>            frame_image = frame_image.convert(&#39;RGB&#39;)<br>        frame_image.save(output_path.replace(&#39;.mp4&#39;, &#39;.jpg&#39;), &#39;JPEG&#39;)<br>        for clip in clips:<br>            clip.close()<br>        supercut.close()<br>        with lock:<br>            supercut_tasks[task_id][&#39;status&#39;] = &#39;completed&#39;<br>            supercut_tasks[task_id][&#39;filename&#39;] = filename<br>    else:<br>        with lock:<br>            supercut_tasks[task_id][&#39;status&#39;] = &#39;completed&#39;<br>            supercut_tasks[task_id][&#39;filename&#39;] = None</pre><h3>Demo to teams</h3><p>We presented the demo to teams that we thought might find this tool useful for their work — video teams, website editorial and collections. Their feedback was positive and that this is definitely something they would use for research and to create supercuts for different public outputs.</p><p>Some of the feedback and features they thought would make it more usable were:</p><ul><li>like the Edit Line interactive experience in the museum, the ability to choose multiple words to create one supercut.</li><li>have a selection tool before the supercut is generator that allows the user to choose the snippets and the videos — maybe using a simple checkbox.</li><li>ability to download the metadata of the videos in the supercut.</li></ul><h3>Next steps</h3><p>The supercuts are cached after they’ve been generated so subsequent requests for the same search terms are returned instantly, but the waiting time while the original request is generated on CPUs is very slow. So the next obvious step is to run the generation thread on cloud or locally hosted GPUs.</p><p>We’ll also start work on the other items teams raised at the team demo.</p><p>Something else we always have in the back of our minds is making this a public experience, online, in the museum or both. As we improve the tool and iron out any issues we’ll get closer to understanding what this could be and how it could further open up the collection for our visitors.</p><p>Watch the code evolve on GitHub: <a href="https://github.com/ACMILabs/video-search/pull/6">github.com/ACMILabs/video-search</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89ef23409ea3" width="1" height="1" alt=""><hr><p><a href="https://labs.acmi.net.au/supercuts-89ef23409ea3">Supercuts</a> was originally published in <a href="https://labs.acmi.net.au/">ACMI LABS</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building better access]]></title>
            <link>https://labs.acmi.net.au/building-better-access-5eab0217e0b0?source=rss-5568cbfd8c73------2</link>
            <guid isPermaLink="false">https://medium.com/p/5eab0217e0b0</guid>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[museums]]></category>
            <category><![CDATA[acces]]></category>
            <category><![CDATA[musetech]]></category>
            <category><![CDATA[collection]]></category>
            <dc:creator><![CDATA[Simon Loffler]]></dc:creator>
            <pubDate>Wed, 02 Apr 2025 03:51:55 GMT</pubDate>
            <atom:updated>2025-04-02T04:05:46.462Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This post is a technical deep dive into how we invested in our existing technology to enable automated collection access. It follows on from </em><a href="https://medium.com/u/5a4689a85cbd"><em>Lucie Paterson</em></a><em>’s </em><a href="https://labs.acmi.net.au/automating-collection-access-e0845cb4df9a"><em>post</em></a><em> about the project from a product and UX perspective.</em></p><p>Our <a href="https://labs.acmi.net.au/extending-the-museum-xos-technology-for-researcher-access-needs-cf35af22622a">previous work</a> extending <a href="https://www.acmi.net.au/lens/">The Lens</a> to allow researcher access to our collection proved popular enough that it was time to expand it to include more types of access requests.</p><p>The ACMI collections and registrations team suggested these additions:</p><ul><li>Viewing ACMI Collection materials</li><li>Footage for use — licensed</li><li>Public Screening</li><li>Exhibition Loans</li><li>First Nations Access</li><li>Family Access</li><li>ACMI staff assisted research</li><li>Donating items to the ACMI collection</li><li>Accepting payments to allow access to download films</li></ul><p>To determine when to show the access request form on our works pages, and which form fields are relevant for different types of access, we make use of our existing metadata workflow.</p><p>This consists of importing metadata from Vernon (our collection management system) into XOS (our museum management pipeline) which then calculates whether to show the form and which fields to show.</p><p>Here’s an example of XOS checking the Vernon objects API field user_sym_200 to mark a work’s public_domain field True for the website:</p><pre>def _add_public_domain(self, work):<br>    &quot;&quot;&quot;<br>    Determine whether this work is in the public domain.<br>    &quot;&quot;&quot;<br>    try:<br>        public_domain = self.vernon_object.get_single_field(&#39;user_sym_200&#39;, None)<br>        if public_domain.lower() == &#39;full use - public domain&#39;:<br>            work.public_domain = True<br>            return<br>    except MissingVernonObjectField:<br>        pass<br><br>    work.public_domain = False</pre><p>When a visitor loads a works page on our website, it then checks with XOS before displaying the form links, which are first generalised down to two options:</p><ul><li>“Submit a request to download this work”</li><li>“Submit a request to access or loan this work”</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QUApQEv-AaNaoMkV9KAviQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VZ0HR2TCE4-6wFHtTGzL3Q.png" /><figcaption>Access request links on our website works pages</figcaption></figure><p>The access request form then shows the minimal number of fields, so we don’t overwhelm the visitor, before they select the type of request they’d like to make.</p><figure><img alt="A screenshot of an ACMI website works page with the Access request form presented. The form includes fields for viewing or loading a work." src="https://cdn-images-1.medium.com/max/1024/1*Da5WtQ-VzZEWR7glppIaZw.png" /><figcaption>An access request form showing the request types available</figcaption></figure><p>Behind the scenes ACMI uses Jira to respond to visitor queries and internal staff requests, so our IT, collections, and registrations teams were keen for us to make use of that system for all access requests.</p><p>To make this happen we use the Jira API to send and store all of the request data. This has the added bonus of allowing us to continue to avoid storing any customer data in our website or XOS databases.</p><p>Here’s what our Jira API client looks like:</p><pre>class Client:<br>    &quot;&quot;&quot;Client for sending data to Jira.&quot;&quot;&quot;<br><br>    def __init__(self):<br>        &quot;&quot;&quot;Initialise arguments.&quot;&quot;&quot;<br>        self.server = settings.JIRA_API_URL<br>        self.username = settings.JIRA_USERNAME<br>        self.token = settings.JIRA_TOKEN<br>        self.project_id = settings.JIRA_PROJECT_ID<br>        self.issue_type = &#39;Collections access&#39;<br><br>    def request(self, url, data=None, method=None, params=None):<br>        &quot;&quot;&quot;Send a request to the Jira API.<br><br>        :param url: str - URL to post to<br>        :param data: dict - data to post<br>        :param method: str - get or post method<br>        :param params: dict - params to add to the request<br>        :return: json response from Jira<br>        :rtype: dict<br>        &quot;&quot;&quot;<br>        try:<br>            if not method:<br>                method = &#39;get&#39;<br>            auth = HTTPBasicAuth(self.username, self.token)<br>            if data:<br>                data = json.dumps(data)<br>            headers = {<br>                &#39;Accept&#39;: &#39;application/json&#39;,<br>                &#39;Content-Type&#39;: &#39;application/json&#39;,<br>            }<br>            full_url = urljoin(self.server, url)<br>            response = getattr(requests, method)(<br>                url=full_url,<br>                auth=auth,<br>                data=data,<br>                headers=headers,<br>                params=params,<br>            )<br>            response.raise_for_status()<br>        except (<br>                requests.exceptions.HTTPError,<br>                requests.exceptions.Timeout,<br>                requests.exceptions.ConnectionError):<br>            raven_client.captureException()<br>            return None<br>        if method == &#39;put&#39; and response.status_code == 204:<br>            # Jira API doesn&#39;t return any JSON for a successful update<br>            return {&#39;message&#39;: f&#39;Updated issue: {url}&#39;}<br>        return response.json()<br><br>    def get_issue(self, issue_id):<br>        &quot;&quot;&quot;<br>        Get a Jira issue.<br><br>        :param issue_id: int - Jira Issue ID<br>        :rtype: dict<br>        &quot;&quot;&quot;<br>        return self.request(url=f&#39;rest/api/2/issue/{issue_id}&#39;)<br><br>    def update_issue(self, issue_id, data):<br>        &quot;&quot;&quot;<br>        Update a Jira issue with new data.<br><br>        :param issue_id: int - Jira Issue ID<br>        :param data: dict - JSON data to save to the Jira issue<br>        :rtype: dict<br>        &quot;&quot;&quot;<br>        jira_issue = self.get_issue(issue_id)<br>        description = json.loads(jira_issue[&#39;fields&#39;][&#39;description&#39;])<br>        description.update(data)<br>        payload = {<br>            &#39;fields&#39;: {<br>                &#39;description&#39;: json.dumps(description),<br>            },<br>        }<br>        return self.request(url=f&#39;rest/api/2/issue/{issue_id}&#39;, method=&#39;put&#39;, data=payload)</pre><p>To make the Jira data interoperable easily with other systems we store the data as a JSON blob in the description field.</p><p>This means we can build dashboards to interact with our collections access requests in XOS, and automated Slack bots to post when new access requests are received:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*6EFgLOuMY6JTqgpDu6Tbgg.png" /></figure><figure><img alt="A screenshot of the ACMI XOS access request dashboard, showing an example request ready to be approved or denied by collection staff." src="https://cdn-images-1.medium.com/max/1024/1*YtcU3RI7ERKAj-Kz5x1WYg.png" /><figcaption>XOS Slack bot, and access requests dashboard</figcaption></figure><p>For download requests that require an upfront payment we use the <a href="https://github.com/stripe/stripe-python">Python</a> and <a href="https://github.com/vue-stripe/vue-stripe">Vuejs Stripe</a> modules to allow us to include inline-payment fields on our access request form, all without leaving our website.</p><p>The first step is for our website backend server to create a “payment intent” which returns a special identifier to be used by the website frontend to know where to send the payment, and how much it is for:</p><pre>class Client:<br>    &quot;&quot;&quot;Client for creating payments with Stripe.&quot;&quot;&quot;<br><br>    def __init__(self):<br>        &quot;&quot;&quot;Initialise arguments.&quot;&quot;&quot;<br>        self.stripe = stripe<br>        self.stripe.api_key = settings.STRIPE_SECRET_KEY<br><br>    def create_payment_intent(self, amount, currency=&quot;aud&quot;):<br>        &quot;&quot;&quot;Create a payment intent for an amount.&quot;&quot;&quot;<br>        response = None<br>        try:<br>            response = self.stripe.PaymentIntent.create(<br>                amount=amount,<br>                currency=currency,<br>                automatic_payment_methods={&quot;enabled&quot;: True},<br>            )<br>        except stripe.InvalidRequestError as exception:<br>            sentry_sdk.capture_exception(exception)<br><br>        if response and response.get(&#39;error&#39;):<br>            sentry_sdk.capture_message(response.get(&#39;error&#39;))<br>            return None<br><br>        return response</pre><p>Next we display the Stripe payment fields inline on the website:</p><pre>// Vuejs PaymentForm.vue component<br>&lt;stripe-element-payment<br>  v-if=&quot;!loading&quot;<br>  ref=&quot;paymentRef&quot;<br>  data-test=&quot;payment-form&quot;<br>  class=&quot;py-16 min-h-96&quot;<br>  :pk=&quot;publishableKey&quot;<br>  :elements-options=&quot;elementsOptions&quot;<br>  :confirm-params=&quot;confirmParams&quot;<br>  redirect=&quot;if_required&quot;<br>  @error=&quot;handleError&quot;<br>  @confirmed=&quot;handlePaymentConfirmed&quot;<br>  @element-change=&quot;handleUpdate&quot;<br>/&gt;<br>&lt;Button<br>  class=&quot;h-56 text-left mb-0 mt-8&quot;<br>  text=&quot;Pay now&quot;<br>  button-style<br>  @click.native=&quot;pay&quot;<br>/&gt;<br><br>// Dynamically import the StripeElementPayment and generate a payment intent for the payment amount<br>async mounted() {<br>  if (process.client) {<br>    this.loading = true;<br>    const { StripeElementPayment } = await import(&#39;@vue-stripe/vue-stripe&#39;);<br>    axios<br>      .get(`${process.env.adminUrl}/payments/${this.amount}/`)<br>      .then((response) =&gt; {<br>        this.$options.components.StripeElementPayment = StripeElementPayment;<br>        this.elementsOptions.clientSecret = response.data.client_secret;<br>        this.loading = false;<br>      })<br>      .catch((error) =&gt; {<br>        this.$sentry.captureException(error);<br>      });<br>  }<br>},</pre><p>After an ACMI collections or registrations team member<strong> </strong>approves a request with a one-button press, XOS updates the Jira ticket, sends an <a href="https://mjml.io/">MJML</a> formatted email to the requester, and generates an Access Lens code for the visitor to view or download the work directly on our website.</p><p>The requester can then tap the link in their email to be automatically logged in with 14-day access to that work from their computer, tablet, or phone.</p><figure><img alt="A screenshot of the ACMI works page for “Private eye”, highlighting an approved access request box showing when access to this film expires." src="https://cdn-images-1.medium.com/max/1024/1*cK7aruSDw5llkJfWl9hr1A.png" /><figcaption>A logged in Access Lens session showing when access to this film expires.</figcaption></figure><p>To recap, the software we re-used to make this work:</p><ul><li><a href="https://vernonsystems.com/">Vernon</a> — collection management system</li><li><a href="https://www.djangoproject.com/">XOS</a> — pipeline for the automation</li><li><a href="https://www.atlassian.com/software/jira">Jira</a> — store access requests as tickets with email history</li><li><a href="https://slack.com/">Slack</a> — automated notifications for new access requests</li><li><a href="https://www.mailgun.com/">Mailgun</a> — send automated access request emails</li><li><a href="https://mjml.io/">MJML</a> — to style the emails for popular email clients</li><li><a href="https://stripe.com/">Stripe</a> — accept payments for film download requests</li><li><a href="https://www.acmi.net.au/collection-preservation/access/">ACMI Website</a> — where visitors make requests</li></ul><p>See examples of the forms on our website, and perhaps:</p><ul><li><a href="https://www.acmi.net.au/works/82390--australias-anti-war-movement-1965-1972/">Access request form example</a></li><li><a href="https://www.acmi.net.au/works/109006--tomatoes-for-processing/">Download request form example</a></li><li><a href="https://www.acmi.net.au/donations/">Donation proposal form</a></li></ul><p>Read more about accessing ACMI collections: <a href="https://www.acmi.net.au/collection-preservation/access/">https://www.acmi.net.au/collection-preservation/access/</a></p><p>If you’re interested in the product &amp; visitor experience perspective, read Lucie Paterson’s <a href="https://labs.acmi.net.au/automating-collection-access-e0845cb4df9a">Labs post</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5eab0217e0b0" width="1" height="1" alt=""><hr><p><a href="https://labs.acmi.net.au/building-better-access-5eab0217e0b0">Building better access</a> was originally published in <a href="https://labs.acmi.net.au/">ACMI LABS</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The anecdote machine]]></title>
            <link>https://labs.acmi.net.au/the-anecdote-machine-1d5c2554a0bd?source=rss-5568cbfd8c73------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d5c2554a0bd</guid>
            <category><![CDATA[anecdotes]]></category>
            <category><![CDATA[text-to-speech]]></category>
            <category><![CDATA[collection]]></category>
            <category><![CDATA[museums]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Simon Loffler]]></dc:creator>
            <pubDate>Wed, 12 Feb 2025 03:33:13 GMT</pubDate>
            <atom:updated>2025-02-12T03:58:49.647Z</atom:updated>
            <content:encoded><![CDATA[<p>We’re always considering new ways of engaging with the ACMI collection, using legible technology, with interfaces that require minimal thinking for the user and retain visitor attention.</p><p>An observation from the museum floor is that visitors are really engaged when our Visitor Experience staff give short talks about the objects they are looking at. These talks involve our staff doing deep-dives into the history of our collection items, summarising them into bite-sized pieces that are easy to understand and digest.</p><p>We wondered whether we might be able to scale this up for all of our collection items with the help of a language model, such as gpt-4o-mini, using an artificially generated human voice.</p><p>This work builds on our previous explorations of <a href="https://labs.acmi.net.au/language-model-explorations-with-our-collection-707a74daaef8">language models and our collection</a>, sharing the same codebase and extending it with new APIs. It is also shaped by our parallel work on a museum audio guide — which may also be influenced by the anecdote machine’s simplicity of interactivity with museum labels.</p><p>Back to the anecdote machine. We built a single button web browser interface, using a visitor story template that can be summarised as: “I don’t know what I’m looking at, and I don’t want to read too much”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ln3oj0OQYdA2hUT1mpkLBw.png" /></figure><p>Pressing “I’m feeling lucky” does these things:</p><ol><li>Gets a random selection of six works from our collection database</li><li>Asks a language model, gpt-4o-mini, to summarise the results, and generate an <strong>anecdote</strong> from the data of one of the items</li><li>Asks a text-to-speech model, ElevenLabs Eleven Flash v2.5, to use ACMI CEO’s voice to speak the results back to the visitor</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TZkGZd6Jj2ov57Q1vBRQYg.png" /></figure><p>If one of the collection items is particularly intriguing, tapping on it will generate another request:</p><ol><li>The selected work’s metadata is converted to an embedding (a series of numbers that represents the work)</li><li>The embedding algorithm, text-embedding-ada-002, returns a work similar to the selected item</li><li>A language model, gpt-4o-mini, summarises the <strong>connection</strong> between those two works</li><li>The text-to-speech model, ElevenLabs Eleven Flash v2.5, speaks the result back to the visitor</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VfyBCDtZi3fA7qBDb8LmcQ.png" /></figure><p>What do you think of the result? Does it emulate the experience of a personal museum guide?</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplayer.vimeo.com%2Fvideo%2F1053268488%3Fh%3Da71d3a0f72%26app_id%3D122963&amp;dntp=1&amp;display_name=Vimeo&amp;url=https%3A%2F%2Fvimeo.com%2F1053268488%2Fa71d3a0f72&amp;image=https%3A%2F%2Fi.vimeocdn.com%2Fvideo%2F1978406375-215cab63942c80c1c7194f7e9053c34d8526c59908f1bf375a052e15064a325c-d_1280&amp;type=text%2Fhtml&amp;schema=vimeo" width="1920" height="1248" frameborder="0" scrolling="no"><a href="https://medium.com/media/71e9ddad5ea29c09fb5ae9044b7c6b54/href">https://medium.com/media/71e9ddad5ea29c09fb5ae9044b7c6b54/href</a></iframe><p>Here’s a look at the language model prompt that generates the anecdote:</p><pre>@app.post(&#39;/summarise&#39;)<br>async def summarise(request: Request):<br>    &quot;&quot;&quot;Returns a summary of the visitor&#39;s query vs the results, including an anecdote.&quot;&quot;&quot;<br>    body = await request.body()<br>    body = body.decode(&#39;utf-8&#39;)<br>    llm_prompt = f&quot;&quot;&quot;<br>        System: You are an ACMI museum guide. Please compare the visitor&#39;s question to the museum<br>        collection items in the response and provide a brief summary as if you were talking<br>        to the visitor in a short one sentence form suitable for text-to-speech as it will be<br>        converted to audio and read back to the visitor.<br><br>        Provide an anecdote about the data in one or more of the collection records.<br><br>        Example: Did you know &lt;summary&gt;. &lt;anecdote&gt;<br><br>        User&#39;s query and context:<br><br>        {body}<br>    &quot;&quot;&quot;<br>    return llm.invoke(llm_prompt).content.replace(&#39;\&quot;&#39;, &#39;&quot;&#39;)</pre><p>And this is how we generate the connection description:</p><pre>@app.get(&#39;/connection&#39;)<br>async def connection(work_id: str):<br>    &quot;&quot;&quot;Returns a description of the connection between a Work ID and its next similar item.&quot;&quot;&quot;<br>    # 1. Retrieve the specific document by ID<br>    doc_dict = docsearch.get(<br>        where={&#39;source&#39;: f&#39;https://api.acmi.net.au/works/{work_id}&#39;},<br>        include=[&#39;embeddings&#39;, &#39;documents&#39;],<br>    )<br>    if not doc_dict.get(&#39;documents&#39;):<br>        raise HTTPException(status_code=404, detail=f&#39;Document not found for ID {work_id}&#39;)<br><br>    # 2. Run a similarity search on the retrieved document<br>    results = docsearch.similarity_search_by_vector(doc_dict[&#39;embeddings&#39;], k=4)<br>    # The first result in &#39;results&#39; is the same doc, so the next most similar is at index 1<br>    # Let&#39;s use the 3th most similar so they&#39;re not identical<br>    if len(results) &lt; 2:<br>        raise HTTPException(<br>            status_code=404,<br>            detail=&#39;No similar document found for ID {work_id}&#39;<br>        )<br><br>    first_doc = results[0]<br>    second_doc = results[-1]<br>    try:<br>        doc1_json = json_parser.loads(first_doc.page_content)<br>    except json_parser.JSONDecodeError:<br>        doc1_json = {&#39;text&#39;: first_doc.page_content}<br>    try:<br>        doc2_json = json_parser.loads(second_doc.page_content)<br>    except json_parser.JSONDecodeError:<br>        doc2_json = {&#39;text&#39;: second_doc.page_content}<br><br>    # 4. Now pass both documents to the LLM (or any other logic)<br>    llm_prompt = f&quot;&quot;&quot;<br>        System: You are an ACMI museum curator. Please compare the two collection records provided<br>        and come up with a short 50 word description of how the two are connected.<br><br>        You are welcome to use outside knowledge to help formulate your reason.<br><br>        The two works for context:<br><br>        {doc1_json}<br>        {doc2_json}<br>    &quot;&quot;&quot;<br>    description = llm.invoke(llm_prompt).content.replace(&#39;\&quot;&#39;, &#39;&quot;&#39;)<br><br>    return {<br>        &#39;work&#39;: work_id,<br>        &#39;works&#39;: [doc1_json, doc2_json],<br>        &#39;connection&#39;: description,<br>    }</pre><p><strong>Code</strong>: <a href="https://github.com/ACMILabs/collection-chat">github.com/ACMILabs/collection-chat</a></p><p>We would like to know what our users think so the next stage is to add in a way for you to give us feedback about if you think the anecdote is correct or not and if there are edits you might suggest. We can then use this to try to fine-tune the model to improve the output, or use it as extra context to help guide it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d5c2554a0bd" width="1" height="1" alt=""><hr><p><a href="https://labs.acmi.net.au/the-anecdote-machine-1d5c2554a0bd">The anecdote machine</a> was originally published in <a href="https://labs.acmi.net.au/">ACMI LABS</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Image embeddings and audio captions]]></title>
            <link>https://labs.acmi.net.au/image-embeddings-and-audio-captions-036ecd84acc7?source=rss-5568cbfd8c73------2</link>
            <guid isPermaLink="false">https://medium.com/p/036ecd84acc7</guid>
            <category><![CDATA[videos]]></category>
            <category><![CDATA[collection]]></category>
            <category><![CDATA[image]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[museums]]></category>
            <dc:creator><![CDATA[Simon Loffler]]></dc:creator>
            <pubDate>Tue, 01 Oct 2024 00:54:56 GMT</pubDate>
            <atom:updated>2024-10-01T00:54:56.042Z</atom:updated>
            <content:encoded><![CDATA[<p>This month we released an iteration on two of our collection exploration tools — our <a href="https://www.acmi.net.au/videos/">video search</a> and <a href="https://www.acmi.net.au/works/explore/?embedding=images">works explorer</a>.</p><p>These iterations came out of a meet and greet we had with the Oxford University <a href="https://www.robots.ox.ac.uk/~vgg/">Visual Geometry Group</a> while chatting about our machine learning explorations and their <a href="https://gitlab.com/vgg/wise/wise/-/tree/wise2/">Wise2</a> video search engine.</p><p>They mentioned using <a href="https://github.com/mlfoundations/open_clip">OpenCLIP</a> to generate image embeddings to compare similar images, and <a href="https://github.com/microsoft/CLAP">CLAP</a> to describe what an audio track sounded like to find things like a dog barking.</p><p>We’re very excited to try Wise2 on our collection videos, but while we get that project organised we thought it might be good to prototype audio captions and image embeddings in XOS (our museum operating system).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KQBvvXYwahXoml9Dq2FHuA.png" /><figcaption>ACMI video search — now with audio descriptions</figcaption></figure><h3>What does this video sound like?</h3><p>That’s the question that Microsoft’s <a href="https://github.com/microsoft/CLAP">CLAP</a> algorithm attempts to answer — so we asked it exactly that every 100 frames of video.</p><p>First we use ffmpeg to split up the video’s audio track into segments:</p><pre>segment_number = 0<br>segment_start = 0<br><br>while segment_start &lt; audio_length * 1000:<br>    segment_path_name = f&#39;{output_dir}/{video_file_name}_segment_{segment_number}.wav&#39;<br>    command = [<br>        &#39;ffmpeg&#39;,<br>        &#39;-y&#39;,<br>        &#39;-i&#39;, audio_file_path,<br>        &#39;-ss&#39;, str(segment_start / 1000),<br>        &#39;-t&#39;, str(segment_duration / 1000),<br>        segment_path_name<br>    ]<br>    subprocess.run(command, stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT, check=True)<br>    segments.append(segment_path_name)<br>    segment_number += 1<br>    segment_start += segment_duration</pre><p>Then we generate captions for each segment using CLAP:</p><pre># Every sample_frequency (default 100) frames let&#39;s predict what&#39;s in it<br>for index, audio_file_path in enumerate(audio_file_paths):<br>    captions = self.model.generate_caption([audio_file_path])<br>    predictions = []<br>    for caption in captions:<br>        predictions.append({<br>            &#39;prediction&#39;: caption,<br>        })<br><br>    seconds = index * self.sample_frequency * fps / 1000<br>    self.predictions.append({<br>        &#39;timestamp&#39;: seconds,<br>        &#39;predictions&#39;: predictions,<br>    })<br>    print(f&#39;Prediction at {index * self.sample_frequency} ({seconds:.1f} secs): {predictions}&#39;)</pre><p>The output looks like this:</p><pre>Prediction at 100 (1.8 secs): [{&#39;prediction&#39;: &#39;A radio station is playing a radio station. &#39;}]<br>Prediction at 200 (3.6 secs): [{&#39;prediction&#39;: &#39;Water is flowing through a stream and splashing in the water. &#39;}]<br>Prediction at 300 (5.4 secs): [{&#39;prediction&#39;: &#39;The wind is blowing and a car is driving by. &#39;}]]</pre><p>One of the quirks of this model is that it recognises background noise as A radio station is playing a radio station. So we’ll need to keep that in mind when presenting this data, perhaps suppressing that output if there are more false positives than actual positives of radio stations in our videos.</p><p>We kept the same data format for the output, which meant that indexing these audio captions for Elasticsearch didn’t need any code changes. This also meant minimal updates were necessary to add this to our website video search.</p><pre>if search_type == &#39;audioDescription&#39;:<br>   field = &#39;classification.captions.clap.predictions.prediction&#39;</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplayer.vimeo.com%2Fvideo%2F1012964610%3Fh%3D22ab8ee355%26app_id%3D122963&amp;dntp=1&amp;display_name=Vimeo&amp;url=https%3A%2F%2Fvimeo.com%2F1012964610%2F22ab8ee355&amp;image=https%3A%2F%2Fi.vimeocdn.com%2Fvideo%2F1930846940-48a68d652e016e717918e514da5c36766544e3449d04e7399c83990f7ca889ad-d_1280&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=vimeo" width="1920" height="1248" frameborder="0" scrolling="no"><a href="https://medium.com/media/2e0b034d97ae65899aabad52b6afd0ed/href">https://medium.com/media/2e0b034d97ae65899aabad52b6afd0ed/href</a></iframe><p>Try it out for yourself: <a href="https://www.acmi.net.au/videos/search/?search=water&amp;type=audioDescription"><strong>acmi.net.au/videos/</strong></a></p><p>Code: <a href="https://github.com/ACMILabs/video-search"><strong>github.com/ACMILabs/video-search</strong></a></p><figure><img alt="A screenshot of the ACMI works explorer, showing images similar to a sketch of an arcade game cabinet." src="https://cdn-images-1.medium.com/max/1024/1*HSBOz3E2YrG_jxnIw5RSnQ.png" /><figcaption>ACMI works explorer, now with images!</figcaption></figure><h3>What does this image look like?</h3><p>The first iteration of our works explorer attempted to show visitors items from our collection when they didn’t know what they were looking for — ideal for those who enjoy doom scrolling and following rabbit holes.</p><p>To enhance this further we wanted to show related collection items by comparing their images.</p><p><a href="https://github.com/mlfoundations/open_clip">OpenCLIP</a> allows us to generate image embeddings (see our <a href="https://labs.acmi.net.au/embeddings-and-our-collection-afa815b8406e">recent post to understand more about embeddings</a>) of each collection item, which we can then use to index in a vector database and retrieve similar images.</p><p>Here’s what the image embedding creation looks like:</p><pre>model_name = &#39;ViT-g-14&#39;<br>pretrained = &#39;laion2b_s34b_b88k&#39;<br>model, _, preprocess = open_clip.create_model_and_transforms(<br>    model_name,<br>    pretrained=pretrained,<br>)<br>sample_frequency = 100<br>embeddings = None<br>tokens = 0<br><br>if image_path:<br>    preprocessed_image = preprocess(Image.open(image_path)).unsqueeze(0)<br>elif image:<br>    preprocessed_image = preprocess(image).unsqueeze(0)<br>tokens = model.visual.positional_embedding.shape[0] - 1<br>with torch.no_grad(), torch.cuda.amp.autocast():<br>    tensors = model.encode_image(preprocessed_image)<br>    embeddings = tensors.cpu().numpy().tolist()[0]<br><br># Return OpenAI Embeddings format<br>return {<br>    &#39;data&#39;: [{<br>        &#39;index&#39;: 0,<br>        &#39;object&#39;: &#39;embedding&#39;,<br>        &#39;embedding&#39;: embeddings,<br>    }],<br>    &#39;model&#39;: f&#39;{model_name} {pretrained}&#39;,<br>    &#39;usage&#39;: {<br>        &#39;total_tokens&#39;: tokens,<br>        &#39;prompt_tokens&#39;: tokens,<br>    },<br>    &#39;object&#39;: &#39;list&#39;,<br>}</pre><p>Because they’re in the same format as our works metadata we indexed previously, adding them to our Chroma vector database is relatively straightforward:</p><pre>prefix = &#39;image_&#39;<br>item_id = f&quot;{embeddings_json[&#39;image&#39;][&#39;id&#39;]}_{embeddings_json[&#39;image&#39;][&#39;work_id&#39;]}&quot;<br>suffix = &#39;0.0&#39;<br>self.collections[collection_name].add(<br>    embeddings=[embedding_item[&#39;embedding&#39;]],<br>    documents=[f&quot;{prefix}{item_id}{suffix}&quot;],<br>    metadatas=[{&#39;source&#39;: &#39;embeddings&#39;}],<br>    ids=[f&quot;{prefix}{embeddings_json[&#39;id&#39;]}{suffix}&quot;],<br>)</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplayer.vimeo.com%2Fvideo%2F1012964561%3Fh%3D441fea7594%26app_id%3D122963&amp;dntp=1&amp;display_name=Vimeo&amp;url=https%3A%2F%2Fvimeo.com%2F1012964561%2F441fea7594&amp;image=https%3A%2F%2Fi.vimeocdn.com%2Fvideo%2F1930846800-d58ec1c474ca6cb4d2dd74d30bf067674d6bc3dd294aff6973309bf134d62afa-d_1280&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=vimeo" width="1920" height="1248" frameborder="0" scrolling="no"><a href="https://medium.com/media/acc8c89a0549537462887989a16a1574/href">https://medium.com/media/acc8c89a0549537462887989a16a1574/href</a></iframe><p>Try it out for yourself: <a href="https://www.acmi.net.au/works/explore/?embedding=images"><strong>acmi.net.au/works/explore/</strong></a></p><ul><li><a href="https://www.acmi.net.au/works/explore/?work=image_33995_121855_0.0&amp;embedding=images">Arcade game cabinets</a></li><li><a href="https://www.acmi.net.au/works/explore/?work=image_30625_109509_0.0&amp;embedding=images">Eyes</a></li></ul><p>Code: <a href="https://github.com/ACMILabs/works-embeddings"><strong>github.com/ACMILabs/works-embeddings</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=036ecd84acc7" width="1" height="1" alt=""><hr><p><a href="https://labs.acmi.net.au/image-embeddings-and-audio-captions-036ecd84acc7">Image embeddings and audio captions</a> was originally published in <a href="https://labs.acmi.net.au/">ACMI LABS</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Machines looking back at us]]></title>
            <link>https://medium.com/@simon.loffler/the-machines-looking-back-at-us-e27fbe71d2eb?source=rss-5568cbfd8c73------2</link>
            <guid isPermaLink="false">https://medium.com/p/e27fbe71d2eb</guid>
            <category><![CDATA[reflections]]></category>
            <category><![CDATA[museums]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Simon Loffler]]></dc:creator>
            <pubDate>Wed, 25 Sep 2024 00:33:20 GMT</pubDate>
            <atom:updated>2024-09-25T00:33:20.308Z</atom:updated>
            <content:encoded><![CDATA[<p>Reflections on the <a href="https://www.acmi.net.au/whats-on/fact-2024/">FACT 2024</a> symposium</p><p>On the panel with us were two large institutions with excellent research teams, so we felt the best contribution we could make would be to demystify machine learning as best we could and show what we’ve been focusing on with the limited resources we have.</p><h3>Our talk</h3><p>We took the title of our section of FACT quite literally and decided to ask the machines for observations of the data that they’d generated watching and listening to thousands of hours of ACMI’s collection videos.</p><p>To do this we collected the most common words from the transcriptions and captions, and sent the top one hundred to GPT-4 together with the number of times they occurred in our data.</p><pre># Code to print the 100 most common words<br># from our video audio transcriptions<br># created by OpenAI Whisper<br><br>import re<br>from collections import Counter<br><br>import nltk<br>from nltk.corpus import stopwords<br>from assets.models import Video<br><br>nltk.download(&#39;stopwords&#39;)<br>stop_words = set(stopwords.words(&#39;english&#39;))<br><br># Initialize a counter for word frequencies<br>word_counter = Counter()<br><br># Retrieve and process video transcriptions<br>for video in Video.objects.filter(transcription__isnull=False).distinct().iterator():<br>    transcription = video.transcription.get(&#39;text&#39;, &#39;&#39;).lower()<br>    # Clean and tokenize the transcription text<br>    words = re.findall(r&#39;\b\w+\b&#39;, transcription)<br>    # Filter out stop words<br>    filtered_words = [word for word in words if word not in stop_words]<br>    # Update word counter<br>    word_counter.update(filtered_words)<br><br># Get the 100 most common words<br>most_common_words = word_counter.most_common(100)<br><br># For the machines (GPT-4)<br>print(most_common_words)<br><br># For the humans to read<br>for word_set in most_common_words:<br>    print(f&#39;{word_set[0]}, ({word_set[1]} times)&#39;)<br><br># Example output:<br># he, (31,443 times)<br># like, (23,681 times)<br># know, (23,639 times)</pre><p>We then sent the list of most_common_words to GPT-4 with the prompt:</p><blockquote>What observations can you make from the resulting list of most common words from our ACMI video collection transcriptions?</blockquote><p>We made similar lists for the video actions and captions and then sent the summaries to OpenAI’s text-to-speech API:</p><pre>from openai import OpenAI<br><br><br>client = OpenAI()<br>response = client.audio.speech.create(<br>  model=&#39;tts-1&#39;,<br>  voice=&#39;alloy&#39;,<br>  input=&#39;GPT-4 summary text goes here.&#39;,<br>)<br>response.write_to_file(&#39;video-transcription-summary.mp3&#39;)</pre><p>OpenAI has a great example for <a href="https://github.com/openai/openai-cookbook/blob/main/examples/Clustering.ipynb">clustering and graphing their Embeddings</a> vectors from 1,536 dimensions to 2 dimensions, so we used that as a base to see what observations the machines had of our collection when in the form of Embeddings.</p><p>The first step was to export our vectors into a JSONL file so we could use it in our notebook:</p><pre>import json<br><br>from collection.models import Work<br><br><br>works = Work.objects.filter(embeddings__isnull=False)<br><br>with open(&#39;embeddings.jsonl&#39;, &#39;w&#39;, encoding=&#39;utf-8&#39;) as open_file:<br>    for work in works:<br>        work_json = {}<br>        work_json[&#39;id&#39;] = work.id<br>        work_json[&#39;title&#39;] = work.get_title_for_label_content()<br>        work_json[&#39;embedding&#39;] = work.embeddings.first().data<br>        open_file.write(f&#39;{json.dumps(work_json)}\n&#39;)</pre><p>Here’s our Jupyter Notebook with the modified example code to use our JSONL export: <a href="https://colab.research.google.com/drive/1dUNustXtn_sYRUNxpJsJdmkxlz3BT5lJ?usp=sharing"><strong>Google Colab</strong></a></p><figure><img alt="A 2D plot of the ACMI collection when clustered into four distinct groups represented by the colours red, blue, green, and purple. The red and blue clusters are quite large, the green and purple clusters much smaller." src="https://cdn-images-1.medium.com/max/554/1*3SLe0Y1WNMevMBO4JlwDrg.png" /><figcaption>ACMI embeddings clustered in 2D using t-SNE</figcaption></figure><p>Our next step was to send the top 100 words to GPT-4 from the titles of each cluster from the notebook:</p><pre>from sklearn.feature_extraction.text import TfidfVectorizer<br>from sklearn.metrics import pairwise_distances_argmin_min<br>from collections import Counter<br>import numpy as np<br><br># Step 1: Find Closest Points to Each Cluster&#39;s Centroid<br>centroids = kmeans.cluster_centers_<br>closest, _ = pairwise_distances_argmin_min(centroids, embeddings_matrix)<br>representative_texts = df.iloc[closest][[&#39;title&#39;, &#39;Cluster&#39;]]<br><br>print(&quot;Representative texts for each cluster:&quot;)<br>print(representative_texts)<br><br># Step 2: Analyze Most Frequent Words or Topics in Each Cluster<br>def get_top_keywords(n_terms):<br>    df[&#39;text_data&#39;] = df[&#39;title&#39;]<br>    tfidf = TfidfVectorizer(stop_words=&#39;english&#39;)<br>    tfidf_matrix = tfidf.fit_transform(df[&#39;text_data&#39;])<br>    terms = tfidf.get_feature_names_out()<br><br>    for cluster in range(n_clusters):<br>        # Calculate the mean TF-IDF vector for each cluster<br>        tfidf_mean = np.mean(tfidf_matrix[df.Cluster == cluster], axis=0)<br>        tfidf_mean = np.array(tfidf_mean).flatten()  # Ensure it&#39;s a flat array<br><br>        # Sort indices in descending order of tfidf values<br>        sorted_indices = np.argsort(tfidf_mean)[::-1]<br><br>        # Extract the top terms for each cluster<br>        top_terms = [terms[i] for i in sorted_indices[:n_terms]]<br><br>        print(f&quot;Cluster {colours[cluster]}: {&#39;, &#39;.join(top_terms)}&quot;)<br><br>get_top_keywords(n_terms=100)  # Get top 100 words for each cluster</pre><p>One question I had for our collections team while look at the data of the green cluster was what tefc meant?</p><blockquote><strong>Green cluster</strong>: tefc, life, world, people, work, children, new, living, water, story, time, history, learning, tomorrow, film, man, making, earth, child, power</blockquote><p>Our collections team confirmed TEFC was theTertiary Education Film Collection which consists of 750 works, so it makes sense that it would appear top of the most common words.</p><p>It also hints that we should probably be looking through not only the title, but also all fields we used to generate the embeddings so that we could pass a better quality list of the top terms to GPT-4.</p><h3>Reflections</h3><p>It has been really lovely to hear from other organisations wanting to do similar experiments with their collections. It’d be especially great if we could all use a standardised way of generating embeddings from our collection records, and release these on our public APIs. This would enable some amazing cross-museum searching tools for visitors, and internal exhibition planning tools for museum staff.</p><p>If you need help getting your collection data in the right format, or setting up your automation pipeline, please get in touch!</p><h3>Ethics and the pace of change</h3><p>Another lovely response has been from artists concerned about the ethics of the companies running the machine learning models, and our responsibility as a publicly funded museum when using their tools. Some of their concerns are:</p><ol><li>Copyright infringement</li><li>Energy use of training large machine learning models</li><li>Use of closed source models</li><li>Inherent bias in the training data and programmers (racial, political, gender etc)</li><li>Funding/connections to the military industrial complex</li><li>Low paid labour of the <a href="https://en.wikipedia.org/wiki/Human-in-the-loop">humans in the loop</a></li><li>Billionaires in control of widely used tools</li><li>Rapid deployment with no regulation</li></ol><p>These are all concerns we share and talk about within ACMI often — we are fortunate to have a balanced team of technology optimists/pessimists, so this tends to self-limit our use of problematic tools for public facing work.</p><p>We do have a strategy of trying all tools to understand what they do, how they work, and what their biases might be — and this includes closed source tools. But our priority is to use open source tools where possible, release our code as open source, and contribute to help rebalance biases where we can.</p><p>This doesn’t answer some of the concerns above, which we’ll save for a follow-up labs post.</p><h3>Links</h3><ul><li>Slides from our presentation: <a href="https://sighmon.com/acmi-fact"><strong>The Machines looking back at us</strong></a></li><li>Try our video search: <a href="https://www.acmi.net.au/videos/"><strong>acmi.net.au/videos/</strong></a></li><li>Try our collection explorer: <a href="https://embeddings.acmi.net.au/?json=false"><strong>embeddings.acmi.net.au</strong></a></li><li>Code for our experiments: <a href="https://github.com/acmilabs"><strong>github.com/ACMILabs</strong></a></li><li>Notebook with the code for this presentation: <a href="https://colab.research.google.com/drive/1dUNustXtn_sYRUNxpJsJdmkxlz3BT5lJ?usp=sharing"><strong>Google Colab</strong></a></li></ul><figure><img alt="The cover of our presentation The Machines looking back at us featuring a confused yet friendly optimistic humanoid robot who cannot understand your message." src="https://cdn-images-1.medium.com/max/1024/1*nPedX5ItcjILrtH8eiHpyQ.jpeg" /><figcaption>Image: psmyrdek/Midjourney</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e27fbe71d2eb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Language model explorations with our collection]]></title>
            <link>https://labs.acmi.net.au/language-model-explorations-with-our-collection-707a74daaef8?source=rss-5568cbfd8c73------2</link>
            <guid isPermaLink="false">https://medium.com/p/707a74daaef8</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[vector-embeddings]]></category>
            <category><![CDATA[museums]]></category>
            <category><![CDATA[retrieval-augmented]]></category>
            <category><![CDATA[chat]]></category>
            <dc:creator><![CDATA[Simon Loffler]]></dc:creator>
            <pubDate>Thu, 27 Jun 2024 05:05:36 GMT</pubDate>
            <atom:updated>2024-06-27T05:05:36.169Z</atom:updated>
            <content:encoded><![CDATA[<p>Each month ACMI teams meet for a talk and play session with the latest machine learning tools. With a mix of critical thinking and imagination we try to choose which tools might be most useful to our visitors to provide better access and interactivity with our museum collection.</p><p>Below are some experiments that have come out of these sessions focusing on how large language models might help improve searching and asking questions of our collection data.</p><p>A traditional search engine uses unique words to match those in a collection of documents. This is great when we know exactly which words we’d like results for, but what if we don’t know what we’re looking for, or want to search for words or documents adjacent to our search? What if the language we use doesn’t match the language and/or vocabulary of the collection we’re searching?</p><p>Large language models help us resolve these problems by learning from billions of documents to predict the probability of words appearing next to each other. This allows us to ask questions using sentences and have results shown to us that are similar.</p><p>With the advent of the <a href="https://en.wikipedia.org/wiki/Transformer_(deep_learning_architecture)">transformer</a>, (the Deep Learning architecture developed by Google), large language models allow us to build almost-perfect interfaces for entering text or speech in our own language and style, which they can interpret, returning extraordinary general knowledge results.</p><p>These models process many billions of input parameters from their training data — the higher the number of parameters the bigger data pattern complexity they can understand. Generally speaking the more training data you give a high parameter model, the better it will be. For example a llama3:7b model has 7 billion parameters, whereas a llama3:70b model has 70 billion parameters. Each were trained on 15 trillion tokens, which roughly equates to 11 trillion words. So they both have a lot of <strong>general</strong> knowledge, but the 70b model will be able to answer much more nuanced questions and be much better at matching patterns.</p><p>Unfortunately computation isn’t yet free from financial or environmental cost, and the higher the number of parameters the more computing power is needed both in training, and in answering questions. It becomes necessary to find the smallest model that gives us the most truthful results.</p><p>You might have noticed I’ve highlighted the word <strong>general</strong> a lot, and that’s because large language models by default don’t care about the ownership of knowledge (which I personally adore!). This is great for asking general questions of all human knowledge, but terrible if you’re asking questions about, for example, a specific museum’s collection.</p><h3>Fine-tuning</h3><p>One of the ways we can help a large language model understand more about specific collections of data is by <a href="https://en.wikipedia.org/wiki/Fine-tuning_(deep_learning)">fine-tuning</a> them. This involves taking a pre-trained model like llama3:7b and then showing it new training examples to learn from to try and teach it to return more truthful answers in a similar pattern to the new data.</p><p>Our first attempt to do this was with gpt-3.5 from OpenAI. Following <a href="https://platform.openai.com/docs/guides/fine-tuning">their guide</a> we generated an ACMI training dataset from XOS (our museum data hub):</p><pre>def create_works_training_file(self):<br>    &quot;&quot;&quot;<br>    Create a training file to fine-tune ChatGPT based on XOS Works.<br>    &quot;&quot;&quot;<br>    file_path = f&#39;/tmp/{datetime.datetime.now().date().isoformat()}-acmi-works.jsonl&#39;<br>    works = Work.objects.filter(unpublished=False)<br>    with open(file_path, &#39;w&#39;, encoding=&#39;utf-8&#39;) as open_file:<br>        for work in works:<br>            work_description = work.description_for_label_override \<br>                or work.description_for_label \<br>                or work.description_override \<br>                or work.description<br>            if work_description:<br>                work_features = [<br>                    work.work_type,<br>                    f&#39;Creators: {work.creator_credit()}&#39;,<br>                    work.headline_credit(),<br>                ]<br>                work_features = list(filter(None, work_features))<br>                work_features_string = &#39;\n&#39;.join(work_features)<br>                data = {&#39;messages&#39;: []}<br>                lines = [<br>                    {&#39;role&#39;: &#39;system&#39;, &#39;content&#39;: &#39;You are an eloquent ACMI museum visitor guide.&#39;},<br>                    {<br>                        &#39;role&#39;: &#39;user&#39;,<br>                        &#39;content&#39;: f&#39;Tell me about the ACMI museum in Australia collection item {work.id}, &#39;<br>                                    f&#39;with the title: {work.get_title_for_label_content()}&#39;,<br>                    },<br>                    {&#39;role&#39;: &#39;assistant&#39;, &#39;content&#39;: f&#39;{work_description}\n{work_features_string}&#39;},<br>                ]<br>                data[&#39;messages&#39;] += lines<br>                open_file.write(f&#39;{json.dumps(data)}\n&#39;)<br>    return file_path</pre><p>This code generates a jsonl file which contains a line of json for each of our collection records formatted in a system/user/assistant message format. We include the title and id of the item in the question, and the description, type, creators, and country/year in the response.</p><p>Here’s an example of the output of record 107893 which you can compare to the data on our <a href="https://api.acmi.net.au/works/107893/">API</a> and <a href="https://www.acmi.net.au/works/107893--english-mahogany-and-brass-bi-unial-magic-lantern/">website</a>:</p><pre>{<br>  &quot;messages&quot;: [<br>    {<br>      &quot;role&quot;: &quot;system&quot;,<br>      &quot;content&quot;: &quot;You are an eloquent ACMI museum visitor guide.&quot;<br>    },<br>    {<br>      &quot;role&quot;: &quot;user&quot;,<br>      &quot;content&quot;: &quot;Tell me about the ACMI museum in Australia collection item 107893, with the title: English mahogany and brass bi-unial magic lantern&quot;<br>    },<br>    {<br>      &quot;role&quot;: &quot;assistant&quot;,<br>      &quot;content&quot;: &quot;Biunial lantern projector with wooden body, metal chimney dome and cowl repainted in black, brass double lenses and diffusers/gas fittings, circa 1880-1910.\nObject\nCreators: Maker not documented\nUnited Kingdom, c. 1880&quot;<br>    }<br>  ]<br>}</pre><p>We then split this file into 80% for training, and 20% for validation. Running this completed successfully in ~2 hours 20 minutes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xfQHotqvBxu798zxlwdszw.png" /><figcaption>OpenAI fine-tuning output</figcaption></figure><p>We then tested our fine-tuned model in the OpenAI playground and compared it to the base gpt-3.5 model:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MakrxGzDdi8oDfiz9byyTA.png" /><figcaption>ACMI fine-tuned model on the left vs gpt-3.5 on the right</figcaption></figure><p>We can see that our fine-tuned model is trying to match the training data output we specified:</p><pre>Description<br>Type<br>Creators<br>Country / Year</pre><p>But then when we follow up with the question: Is it in the ACMI Collection?, they both hallucinate in different ways.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oyFxIa94e0RxfQQPBNcJBg.png" /><figcaption>Follow-up answers are not very truthful at all.</figcaption></figure><p>The fine-tuned model doesn’t even attempt to answer our question, and the standard model starts saying yes, but then continues to say no.</p><h3>Open source models</h3><p>Next we wanted to verify these results against fine-tuned open source models to see if they would give similar results.</p><p>Apple released their mlx framework which makes use of all of the CPU and GPU cores of a Mac computer with an M series arm chipset, and so we thought we’d try that out for fast fine-tuning.</p><p>Using their mlx-lm <a href="https://github.com/ml-explore/mlx-examples/blob/main/llms/mlx_lm/LORA.md">example code</a> we tried fine-tuning llama3:</p><pre># Create a virtual environment<br>python3 -m venv venv<br><br># Activate that environment<br>source venv/bin/activate<br><br># Install mlx<br>pip install mlx-lm<br><br># Copy our training and validation data<br>mkdir data<br>cp acmi-training.jsonl data/train.jsonl<br>cp acmi-validation.jsonl data/valid.jsonl<br>cp acmi-test.jsonl data/test.jsonl<br><br># Start training<br>mlx_lm.lora \<br>  --model mlx-community/Meta-Llama-3-8B-8bit \<br>  --train \<br>  --data data \<br>  --iters 600 \<br>  --grad-checkpoint \<br>  --batch-size 2<br><br># Output<br>Training<br>Starting training..., iters: 600<br>Iter 1: Val loss 4.113, Val took 58.688s<br>Iter 10: Train loss 4.295, Learning Rate 1.000e-05, It/sec 0.263, Tokens/sec 88.842, Trained Tokens 3375, Peak mem 10.337 GB<br>...<br>Iter 600: Train loss 2.276, Learning Rate 1.000e-05, It/sec 0.307, Tokens/sec 92.152, Trained Tokens 208745, Peak mem 15.295 GB<br>Iter 600: Val loss 2.255, Val took 68.449s<br>Iter 600: Saved adapter weights to adapters/adapters.safetensors and adapters/0000600_adapters.safetensors.<br>Saved final adapter weights to adapters/adapters.safetensors.</pre><p>Once that finished we could evaluate it:</p><pre># Generate some output from our model<br>mlx_lm.generate \<br>  --model mlx-community/Meta-Llama-3-8B-8bit \<br>  --adapter-path adapters \<br>  --prompt &quot;Tell me about the English mahogany and brass bi-unial magic lantern in the ACMI collection&quot;<br><br># Output<br>Special tokens have been added in the vocabulary, make sure the associated word embeddings are fine-tuned or trained.<br>==========<br>Prompt: &lt;|begin_of_text|&gt;&lt;|start_header_id|&gt;user&lt;|end_header_id|&gt;<br><br>Tell me about the English mahogany and brass bi-unial magic lantern in the ACMI collection&lt;|eot_id|&gt;&lt;|start_header_id|&gt;assistant&lt;|end_header_id|&gt;<br><br><br>Magic lanterns are optical devices used to project images onto a screen. The term &quot;magic lantern&quot; was first used around 1659, when lanterns were used to create illusions of light and shadow. These early devices were hand-held and were used to project images on walls and ceilings. The first lanterns were made of wood, but as the technology improved, lanterns were made of metal, such as brass or steel. Lanterns have been used for entertainment, education, and religious purposes.<br>==========<br>Prompt: 59.822 tokens-per-sec<br>Generation: 17.261 tokens-per-sec</pre><p>Quite a general response, so let’s try a bit harder:</p><pre># Prompt<br>mlx_lm.generate \<br>  --model mlx-community/Meta-Llama-3-8B-8bit \<br>  --adapter-path adapters \<br>  --prompt &quot;You are an eloquent ACMI museum visitor guide. Are there any Biunial lanterns in the collection?&quot;<br><br># Output<br>Special tokens have been added in the vocabulary, make sure the associated word embeddings are fine-tuned or trained.<br>==========<br>Prompt: &lt;|begin_of_text|&gt;&lt;|start_header_id|&gt;user&lt;|end_header_id|&gt;<br><br>You are an eloquent ACMI museum visitor guide. Are there any Biunial lanterns in the collection?&lt;|eot_id|&gt;&lt;|start_header_id|&gt;assistant&lt;|end_header_id|&gt;<br><br><br>No, there are no Biunial lanterns in the collection. The ACMI museum has a variety of lanterns, including Biunial and more.<br><br>A bird has a great deal of trouble trying to reach a bird feeder 50 feet above the ground. However, the bird quickly finds that if it climbs up a nearby tree, it can easily reach the feeder. The bird can climb at a rate of 1 foot per second, and can fly at a rate of 10 feet per<br>==========<br>Prompt: 41.280 tokens-per-sec<br>Generation: 17.838 tokens-per-sec<br><br><br># Prompt<br>mlx_lm.generate \<br>  --model mlx-community/Meta-Llama-3-8B-8bit \<br>  --adapter-path adapters \<br>  --prompt &quot;You are an eloquent ACMI museum visitor guide. Tell me about the ACMI museum in Australia collection item 107893, with the title: English mahogany and brass bi-unial magic lantern&quot;<br><br># Output<br>Special tokens have been added in the vocabulary, make sure the associated word embeddings are fine-tuned or trained.<br>==========<br>Prompt: &lt;|begin_of_text|&gt;&lt;|start_header_id|&gt;user&lt;|end_header_id|&gt;<br><br>You are an eloquent ACMI museum visitor guide. Tell me about the ACMI museum in Australia collection item 107893, with the title: English mahogany and brass bi-unial magic lantern&lt;|eot_id|&gt;&lt;|start_header_id|&gt;assistant&lt;|end_header_id|&gt;<br><br><br>The item shows the construction of a magic lantern. This was a device used to project pictures through a lens onto a screen. Two lenses are used in this model. The film is placed between the two lenses and the light shines through the film onto the screen. The lenses are adjustable to allow the image to be focussed on the screen. The device is made of wood and brass.<br>Film<br>Creators: <br>United Kingdom, 1925&lt;|reserved_special_token_196|&gt;&lt;|reserved_special_token_40|&gt;assistant&lt;|reserved_special_token_155|&gt;<br><br>![](https://img.shields<br>==========<br>Prompt: 84.701 tokens-per-sec<br>Generation: 17.737 tokens-per-sec</pre><p>Unfortunately we’re still seeing the system failing to answer usefully, and even when we ask it with the precise example from the training data, it still hallucinates the type and the year and adds a strange link at the end — though it does try its hardest to match the output we trained it on.</p><h3>Retrieval Augmented Generation (RAG)</h3><p>Accepting that we’re not able to get reliable or truthful answers about our collection items we moved onto another workflow — <a href="https://en.wikipedia.org/wiki/Large_language_model#Tool_use">Retrieval Augmented Generation</a> or RAG for short.</p><p>This method includes multiple steps to generate an answer to a question:</p><ol><li>Takes your question and searches a vector database for collection items that are similar to the question</li><li>Sends your question to the large language model together with the collection items it found as context — telling it to <strong>only</strong> use the context provided to answer the question</li><li>Generates a response in the format you requested</li></ol><p>To make this possible we first need to generate a vector representation of our collection data — think of this as something like turning the letter A into the number 1, B into the number 2, and so on. But instead of just looking at letters, it takes into account words, and the context of the words next to other words around it. The format of these vectors are known as Embeddings. (related: <a href="https://labs.acmi.net.au/embeddings-and-our-collection-afa815b8406e">collection explorer</a>)</p><p>Seeing we want to evaluate different language models and different embeddings models it makes sense to use a framework that makes switching them out easy — <a href="https://www.langchain.com/">LangChain</a> is the Python-based framework we chose.</p><p>Creating a vector database from our <a href="https://api.acmi.net.au/works/">Public API works JSON data</a> using LangChain and <a href="https://platform.openai.com/docs/guides/embeddings">OpenAI Embeddings</a> looks like this:</p><pre>import json<br><br>from langchain_community.document_loaders import JSONLoader<br>from langchain_community.vectorstores import Chroma<br>from langchain_openai import ChatOpenAI, OpenAIEmbeddings<br><br><br>TMP_FILE_PATH = &#39;acmi-works.json&#39;<br><br>llm = ChatOpenAI(temperature=0, model=&#39;gpt-4o&#39;)<br>embeddings = OpenAIEmbeddings(model=&#39;text-embedding-ada-002&#39;)<br><br>docsearch = Chroma(<br>    collection_name=&#39;works&#39;,<br>    embedding_function=embeddings,<br>    persist_directory=&#39;works_db&#39;,<br>)<br><br># We loop through our Public API to merge all pages into one &#39;results&#39; list<br># Then save that to an `acmi-works.json` file<br><br>with open(TMP_FILE_PATH, &#39;r&#39;, encoding=&#39;utf-8&#39;) as tmp_file:<br>    json_data = json.load(tmp_file)<br><br>json_loader = JSONLoader(<br>    file_path=TMP_FILE_PATH,<br>    jq_schema=&#39;.results[]&#39;,<br>    text_content=False,<br>)<br>data = json_loader.load()<br><br># Add source metadata<br>for i, item in enumerate(data):<br>    item.metadata[&#39;source&#39;] = f&#39;https://api.acmi.net.au/works/{json_data[&quot;results&quot;][i][&quot;id&quot;]}&#39;<br><br>def chunks(input_list, number_per_chunk):<br>    &quot;&quot;&quot;Yield successive chunks from the input_list.&quot;&quot;&quot;<br>    for idx in range(0, len(input_list), number_per_chunk):<br>        yield input_list[idx:idx + number_per_chunk]<br><br># Add to the vector database in chunks to avoid OpenAI rate limits<br>for i, sublist in enumerate(chunks(data, 10)):<br>    docsearch.add_documents(<br>        sublist,<br>    )<br>    print(f&#39;Added {len(sublist)} items to the database... total {(i + 1) * len(sublist)}&#39;)<br>print(f&#39;Finished adding {len(data)} items to the database&#39;)</pre><p>Now we’re ready to <a href="https://js.langchain.com/v0.1/docs/use_cases/question_answering/">create a chat chain</a> using that database — again making use of the LangChain framework:</p><pre># Extending the code block above...<br><br>qa_chain = create_qa_with_sources_chain(llm)<br>doc_prompt = PromptTemplate(<br>    template=&#39;Content: {page_content}\nSource: {source}&#39;,<br>    input_variables=[&#39;page_content&#39;, &#39;source&#39;],<br>)<br>final_qa_chain = StuffDocumentsChain(<br>    llm_chain=qa_chain,<br>    document_variable_name=&#39;context&#39;,<br>    document_prompt=doc_prompt,<br>)<br><br>memory = ConversationBufferMemory(memory_key=&#39;chat_history&#39;, return_messages=True)<br>TEMPLATE = &quot;&quot;&quot;Given a chat history and the latest user question<br>which might reference context in the chat history,<br>formulate a standalone question which can be understood<br>without the chat history. Do NOT answer the question,<br>just reformulate it if needed and otherwise return it as is.<br><br>Chat History:<br>{chat_history}<br>Follow Up Input: {question}<br>Standalone question:&quot;&quot;&quot;<br>CONDENSE_QUESTION_PROMPT = PromptTemplate.from_template(TEMPLATE)<br>condense_question_chain = LLMChain(<br>    llm=llm,<br>    prompt=CONDENSE_QUESTION_PROMPT,<br>)<br><br>retrieval_qa = ConversationalRetrievalChain(<br>    question_generator=condense_question_chain,<br>    retriever=docsearch.as_retriever(),<br>    memory=memory,<br>    combine_docs_chain=final_qa_chain,<br>)<br><br>print(&#39;=========================&#39;)<br>print(&#39;ACMI collection chat v0.1&#39;)<br>print(&#39;=========================\n&#39;)<br><br>while True:<br>    try:<br>        query = input(&#39;Question: &#39;)<br>        response = retrieval_qa.invoke({&#39;question&#39;: query}).get(&#39;answer&#39;)<br><br>        try:<br>            print(f&#39;Answer: {json.loads(response)[&quot;answer&quot;]}&#39;)<br>            print(f&#39;Sources: {json.loads(response)[&quot;sources&quot;]}\n&#39;)<br>        except TypeError:<br>            print(f&#39;Answer: {response}\n&#39;)<br>    except KeyboardInterrupt:<br>        print(&#39;\n\nNice chatting to you.\n&#39;)<br>        break<br>    except openai.BadRequestError:<br>        print(&#39;\n\nSorry, something went wrong with the OpenAI request.\n&#39;)<br>        break</pre><p>Let’s run this and see if our responses are any better:</p><pre>$ python chat.py <br><br>=========================<br>ACMI collection chat v0.1<br>=========================<br><br>Question: Are there any bi-unial lanterns in the collection?                                            <br>Answer: Yes, there is an English mahogany and brass bi-unial magic lantern in the collection. It is a biunial lantern projector with a wooden body, metal chimney dome, and brass double lenses, dating from around 1880-1910.<br>Sources: [&#39;https://api.acmi.net.au/works/107893&#39;]</pre><p>Success! Not only does it give us a truthful response, but also responds with a link to the <a href="https://api.acmi.net.au/works/107893">ACMI data source</a> it found the answer in.</p><p>Let’s try a follow-up question:</p><pre>=========================<br>ACMI collection chat v0.1<br>=========================<br><br>Question: Are there any animated cats in the collection?<br>Answer: Yes, there are several animated cats in the collection. These include:<br>1. &#39;Scribbling Kitten&#39; by Toei Animation, featuring a kitten named Miaow.<br>2. &#39;The Cat Came Back&#39; by Cordell Barker, Ches Yetman, Richard Condie, and the National Film Board of Canada, featuring a little yellow cat.<br>3. &#39;The Aristocats&#39; by Wolfgang Reitherman, Winston Hibler, and Walt Disney Productions, featuring Duchess and her three kittens.<br>4. &#39;Felix the Cat: The Movie&#39; by Tibor Hernadi, Christian Schneider, Don Oriolo, James Schenk, Animation Film Cologne, and Felix the Cat Creations, featuring Felix the Cat.<br>Sources: [&#39;https://api.acmi.net.au/works/72552&#39;, &#39;https://api.acmi.net.au/works/80100&#39;, &#39;https://api.acmi.net.au/works/84891&#39;, &#39;https://api.acmi.net.au/works/93746&#39;]<br><br>Question: Which would be best for my 10 year old?<br>Answer: The best animated cat movie from the collection for a 10-year-old would be &quot;The Aristocats.&quot; This Disney animated film is filled with lovable characters and engaging music, making it suitable for children. It follows the adventure of Duchess and her three kittens as they try to return to Paris after being abandoned in the countryside. The film is classified as &#39;G&#39; for general audiences, making it appropriate for a 10-year-old.<br>Sources: [&#39;https://api.acmi.net.au/works/84891&#39;]</pre><h3>Open source options</h3><p>LangChain makes it easy to test open source options for both embeddings and language model responses. We can now try different models changing environment variablesMODEL=llama3:7b and EMBEDDINGS_MODEL=nomic-embed-text. Here are the different combinations we’ve tried:</p><p><strong>Embeddings</strong>:</p><ol><li><a href="https://blog.nomic.ai/posts/nomic-embed-text-v1">Nomic Embed</a> (nomic-embed-text)</li><li><a href="https://www.mixedbread.ai/docs/embeddings/mxbai-embed-large-v1#model-description">Mixed Bread mxbai</a> (mxbai-embed-large)</li></ol><p><strong>LLMs:</strong></p><ol><li><a href="https://llama.meta.com/llama3/">Llama3</a> by Meta (8b and 70b)</li><li><a href="https://azure.microsoft.com/en-us/products/phi-3">Phi3</a> by Microsoft (14b)</li><li><a href="https://qwenlm.github.io/blog/qwen2/">Qwen2</a> by Alibaba (7b and 72b)</li></ol><p>Our embeddings tests have been disappointing, with both open source models returning inconsistent documents for questions that OpenAI excel at. This hasn’t been helped by <a href="https://github.com/ollama/ollama/issues/4207">Ollama embeddings bugs</a>, so we will continue to test this in the future.</p><p>Our LLM tests have been similarly disappointing, with small open source models unable to return valid HTML in their responses, and both small and large models hallucinating the IDs provided to them in ACMI documents when they attempt to generate HTML links to those documents.</p><h3>A visitor focused interface</h3><p>As we learnt from the <a href="https://www.acmi.net.au/lens/">Lens</a>, technology is most successful when it’s super simple to use and invisible to the person using it. So the next part of this puzzle is going to be how to integrate natural language chatting into our website, our physical museum, and perhaps our visitor’s ears.</p><p>To enable these experiments we built a Chat API server using <a href="https://www.langchain.com/langserve">LangServe</a>. This makes it as easy as this command to enable the conversation with the ACMI collection data:</p><pre>curl https://chat.acmi.net.au/invoke \<br>  -d &#39;{&quot;input&quot;: {&quot;question&quot;: &quot;Are there any animated cats in the collection?&quot;, &quot;chat_history&quot;: []}}&#39;</pre><p>This calls the <a href="https://python.langchain.com/v0.1/docs/use_cases/question_answering/#retrieval-and-generation">RAG chain</a> we built earlier to generate the answer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FWdkso0icP0nLYgE.png" /><figcaption>The RAG workflow as a diagram</figcaption></figure><p><strong>Code</strong>: <a href="https://github.com/acmilabs/collection-chat">github.com/acmilabs/collection-chat</a></p><p>We’ll be writing more about these visitor focused experiments soon!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*cSg01t6DxK0XfJrSNhFzDQ.gif" /><figcaption>A screencast of the chat playground that LangServe generates for testing your chat server.</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=707a74daaef8" width="1" height="1" alt=""><hr><p><a href="https://labs.acmi.net.au/language-model-explorations-with-our-collection-707a74daaef8">Language model explorations with our collection</a> was originally published in <a href="https://labs.acmi.net.au/">ACMI LABS</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Embeddings and our collection]]></title>
            <link>https://labs.acmi.net.au/embeddings-and-our-collection-afa815b8406e?source=rss-5568cbfd8c73------2</link>
            <guid isPermaLink="false">https://medium.com/p/afa815b8406e</guid>
            <category><![CDATA[explore]]></category>
            <category><![CDATA[embedding]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[museums]]></category>
            <category><![CDATA[recommendations]]></category>
            <dc:creator><![CDATA[Simon Loffler]]></dc:creator>
            <pubDate>Fri, 27 Oct 2023 04:54:43 GMT</pubDate>
            <atom:updated>2023-10-27T04:54:43.872Z</atom:updated>
            <content:encoded><![CDATA[<p>We’re always looking for new ways to increase discoverability and access to our collection. The recent development of large language models has created new ways of doing this, encoding human language into a format that’s easy for computers to work with. One of those formats are embeddings.</p><p><a href="https://en.wikipedia.org/wiki/Word_embedding">Embeddings</a> are a way of representing words as a list of numbers.</p><p>It means that you can encode a human readable word like <strong>hello</strong> into something that a computer can use to quickly compare to lots of other words and show you similar words.</p><pre># Using OpenAI&#39;s API to encode `hello` into an embedding<br><br>client = openai<br>response = client.Embedding.create(<br>    input=&#39;hello&#39;,<br>    model=&#39;text-embedding-ada-002&#39;,<br>)<br><br>print(response[&#39;data&#39;][0])<br><br>&quot;embedding&quot;: [<br>    -0.025058425962924957,<br>    -0.019388560205698013,<br>    -0.027781018987298012,<br>    ...<br>    -0.005283283535391092,<br>    -0.014802445657551289,<br>    -0.0033189859241247177,<br>]</pre><blockquote>If you’d like to read or listen to more about embeddings, open <a href="https://simonwillison.net/2023/Oct/23/embeddings/">Simon Willison’s talk</a> in another tab.</blockquote><p>Because embeddings are great at returning similar things, we wanted to explore how useful they might be at uncovering similar items in our <a href="https://www.acmi.net.au/works/">ACMI collection</a>.</p><h3>Prototyping</h3><p>To get started we read up on how to use the <a href="https://platform.openai.com/docs/guides/embeddings">OpenAI Embeddings API</a>. There are great Python examples there, so getting a prototype working was relatively painless.</p><p>In the future it’d be great to compare OpenAI Embeddings with <a href="https://python.langchain.com/docs/integrations/text_embedding/">other text embedding APIs</a>, and also try a <a href="https://ai.meta.com/blog/imagebind-six-modalities-binding-ai/">multi-modal embedding API</a> so we can encode images and audio.</p><p>We decided on an in-memory <a href="https://www.trychroma.com/">Chroma vector database</a> to store the Embeddings for the prototype to keep things simple. Chroma is available as a Python module, meaning we could re-use our <a href="https://github.com/acmilabs/acmi-api">Public API Flask server code</a> for the prototype to get up and running really quickly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*heeiA_IOMUcDUnGwEo5tqQ.gif" /><figcaption>Works embeddings prototype</figcaption></figure><p>Flask/Chroma code on GitHub: <a href="https://github.com/ACMILabs/works-embeddings">github.com/ACMILabs/works-embeddings</a></p><h3>Creating the embeddings</h3><p>One of the difficult decisions to make when encoding embeddings from collections records is which fields to include. As always <a href="https://chat.openai.com/share/cc8ee6ac-c546-456d-9300-3a0420075872">there’s a tradeoff</a> between amount of data, quality of data, speed of response, computational resource use, and quality of results. Here’s our first pass at the collection record fields we’re including:</p><ul><li>title</li><li>description</li><li>type e.g. film, tv show, videogame, artwork</li><li>creator name</li><li>place/date e.g. Australia, 1991</li></ul><p>And here’s what the code looks like:</p><pre>def create_embeddings(self, work):<br>    &quot;&quot;&quot;<br>    Create an Embedding from an ACMI collection Work record.<br>    &quot;&quot;&quot;<br>    embedding = None<br><br>    # The fields from the Work record we include<br>    work_features = [<br>        work.get_title_display(),<br>        work.description_override or work.description,<br>        work.work_type,<br>        work.creator_credit(),<br>        work.headline_credit(),<br>    ]<br><br>    work_features = list(filter(None, work_features))<br>    text_string = &#39;\n&#39;.join(work_features)<br>    embeddings_json = self.get_embeddings(text_string)<br>    if embeddings_json:<br>        embedding, _ = Embedding.objects.get_or_create(<br>            work=work,<br>            defaults={&#39;data&#39;: embeddings_json},<br>        )<br>        embedding.data = embeddings_json<br>        embedding.save()<br>    return embedding</pre><h3>Saving the embeddings to a vector database</h3><p>Because there’s a time and cost involved in generating embeddings we decided to save the JSON data returned from OpenAI to our XOS Postgres database. This allows us to re-expose it via our private XOS APIs so we can use it for prototyping different vector databases without needing to re-generate it every time.</p><p>Here’s what the code looks like to import the embeddings data from our internal APIs to a Chroma vector database:</p><pre>def add_embedding(self, embeddings_json):<br>    &quot;&quot;&quot;<br>    Add an embedding to Chroma from an individual XOS embeddings JSON.<br>    &quot;&quot;&quot;<br>    return self.collection.add(<br>        embeddings=[embeddings_json[&#39;data&#39;][0][&#39;embedding&#39;]],<br>        documents=[str(embeddings_json[&#39;work&#39;])],<br>        metadatas=[{&#39;source&#39;: &#39;works&#39;}],<br>        ids=[str(embeddings_json[&#39;id&#39;])],<br>    )</pre><p>We store our ACMI collection work_id in the documents field, and the embedding_id that is saved in XOS in the ids field. We did this to minimise the amount of data stored in the vector database so it could run on minimal infrastructure, but it does mean we need to make an extra API call to retrieve the full record data for a work_id when our Chroma query returns results.</p><p>It takes us about 20 minutes to add our 45,000 public works embeddings to a fresh Chroma vector database, so to avoid doing this each time we start the app we use Chroma’s persistent client to save data to the filesystem so we can compress it and save it as a cached blob.</p><pre># Chroma db persistent client option<br>chromadb.PersistentClient(path=&#39;works_db&#39;)<br><br># entrypoint.sh<br># Bash script to download the cached blob and decompress it<br>mkdir -p &quot;$DATABASE_PATH&quot; &amp;&amp; \<br>cd &quot;$DATABASE_PATH&quot; &amp;&amp; \<br>curl -O &quot;${CACHE_URL}works_db.tar.gz&quot; &amp;&amp; \<br>tar -xvzf works_db.tar.gz</pre><p>Happily loading all of those 45,000 records from the filesystem back into memory for querying only takes about 15 seconds which is very tolerable for both development and deployment systems.</p><h3>Querying the database</h3><p>Now that we’ve got a Flask API with a Chroma vector database full of embeddings we’re ready to query for results! This is as simple as passing in a work_id we’d like similar records for: <a href="http://localhost:8081/?work=118023">http://localhost:8081/?work=118023</a></p><p>The response we get back includes the original work we selected, plus a list of other works that are most similar including the distance they are away from the original work. The higher the distance, the less similar it is.</p><pre>[<br>  {<br>    &quot;distance&quot;: 0.0,<br>    &quot;id&quot;: &quot;43143&quot;,<br>    &quot;work&quot;: &quot;118023&quot;<br>  },<br>  {<br>    &quot;distance&quot;: 0.21819035708904266,<br>    &quot;id&quot;: &quot;46309&quot;,<br>    &quot;work&quot;: &quot;82181&quot;<br>  },<br>  ...<br>  {<br>    &quot;distance&quot;: 0.3344864845275879,<br>    &quot;id&quot;: &quot;35670&quot;,<br>    &quot;work&quot;: &quot;109984&quot;<br>  }<br>]</pre><h3>Putting it all together</h3><p>The output from our first attempt was pretty solid — so we decided to build it into our ACMI website so we could improve the visitor experience and allow you to beta test it with us.</p><p>Try it out for yourself: <a href="https://www.acmi.net.au/works/explore/"><strong>https://www.acmi.net.au/works/explore/</strong></a></p><ul><li>When the page loads it’ll show a selection of works from our collection</li><li>Tap show related under any of those works to see similar works from the collection</li><li>You can then keep tapping show related to keep burrowing down the rabbit hole</li><li>Tap clear to start again, and refresh if you&#39;d like more starting works</li></ul><p>Enjoy — and add a comment if you find some exciting gems in our collection!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mCozBVV7zJI7XvVK6RnjMg.png" /><figcaption>ACMI works explorer focusing on the selected work <a href="https://www.acmi.net.au/works/explore/?work=118023">Treaty — Yothu Yindi</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=afa815b8406e" width="1" height="1" alt=""><hr><p><a href="https://labs.acmi.net.au/embeddings-and-our-collection-afa815b8406e">Embeddings and our collection</a> was originally published in <a href="https://labs.acmi.net.au/">ACMI LABS</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Search inside our videos — Part 2: content discovery]]></title>
            <link>https://labs.acmi.net.au/video-image-search-94bed300ca22?source=rss-5568cbfd8c73------2</link>
            <guid isPermaLink="false">https://medium.com/p/94bed300ca22</guid>
            <category><![CDATA[videos]]></category>
            <category><![CDATA[search]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[image]]></category>
            <category><![CDATA[collection]]></category>
            <dc:creator><![CDATA[Simon Loffler]]></dc:creator>
            <pubDate>Fri, 04 Aug 2023 01:16:41 GMT</pubDate>
            <atom:updated>2023-09-07T05:52:25.516Z</atom:updated>
            <content:encoded><![CDATA[<h3>Seeing inside ACMI’s collection — part 2</h3><p>Our <a href="https://labs.acmi.net.au/search-inside-our-videos-d63aab921ca2">audio transcription search</a> works well when searching inside videos that have audible speech in them, but what about the rest of our collection videos that don’t have speech, or any audio at all? Or what about just finding all the scenes that have a particular [noun] in them?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*okVA77AP-g2xQgHSAGnwxA.png" /><figcaption>Video search, now searching inside image frame content — <a href="https://www.acmi.net.au/videos/">ACMI website</a></figcaption></figure><p>ACMI’s collection of digitised video consists of ~20% silent/musical content, so a large portion of our videos weren’t being indexed by Whisper auto-transcriptions. We also have a sizable collection of homemade films, often on reels without much metadata for cataloguing. So any help that machine vision software can give us is useful.</p><h3>Prototyping vision algorithms</h3><p>Back in 2017 ACMI’s Renewal CTO Greg Turner did some early work at using the computer vision tools of that era to explore what was possible with identifying objects and people within the films in our collection. This early classification work used tools from Google, Microsoft, and Amazon with varying results. The tools were slow and generated unsatisfactory experiences, although were a cool tech demo.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F-MsM2Ynn1XM%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D-MsM2Ynn1XM&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/9ba47fdabbaa2ce259ce07a6e7713db1/href">https://medium.com/media/9ba47fdabbaa2ce259ce07a6e7713db1/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FXdBrOI30_mY%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DXdBrOI30_mY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FXdBrOI30_mY%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/641c14bf129d735d2f11bbc9691efb53/href">https://medium.com/media/641c14bf129d735d2f11bbc9691efb53/href</a></iframe><p>With recent advancements, we built on this work and started researching newer open source image and video machine vision algorithms to prototype and chose these based on their relatively high accuracy:</p><ul><li><a href="https://huggingface.co/docs/transformers/main/model_doc/videomae">VideoMAE</a> — to classify the actions of people or objects in videos</li><li><a href="https://github.com/ultralytics/ultralytics">YOLOv8</a> &amp; <a href="https://huggingface.co/google/vit-base-patch16-224">Google ViT</a> — to classify the objects that appear in image frames of our videos</li><li><a href="https://huggingface.co/docs/transformers/main/model_doc/blip-2">BLIP-2</a> — to auto-caption the image frames of our videos</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1jDF5aj6PPnjIkKGJneD6Q.jpeg" /><figcaption>VideoMAE debug output — Google Colab Notebook</figcaption></figure><h3>Describing Actions</h3><p><a href="https://huggingface.co/docs/transformers/main/model_doc/videomae#transformers.VideoMAEForVideoClassification">VideoMAE</a> works by examining 16 consecutive image frames every 100 frames of a video to try and determine what actions are happening in them. It then tries to classify those actions into one of 600 human action classes from the <a href="https://opendatalab.com/Kinetics-400">Kinetics-400</a> list. An example of the JSON output we’re saving to XOS from VideoMAE shows the timestamp (at 84 seconds), action predicted (watering plants), and the confidence it has in its prediction (14%):</p><pre>{<br>    &quot;timestamp&quot;: 84.0,<br>    &quot;predictions&quot;: [<br>        {<br>            &quot;confidence&quot;: 0.14264445006847382,<br>            &quot;prediction&quot;: &quot;watering plants&quot;<br>        }<br>    ]<br>}</pre><p>This output might be useful data for auto-generating a description of what the video is about, and what happens inside it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0D8oj682YAlI9UOIrrbezA.jpeg" /><figcaption>A video frame image at timecode 12.5 seconds referenced by the Object and Caption vision models below.</figcaption></figure><h3>Identifying Objects</h3><p><a href="https://github.com/ultralytics/ultralytics">YOLOv8</a> &amp; <a href="https://huggingface.co/google/vit-base-patch16-224">Google ViT</a> work by examining individual frames once every 100 frames of a video to try and determine which and how many objects appear in a video. An example of the JSON output we’re saving to XOS from these two models:</p><pre>&quot;yolo&quot;: [<br>    {<br>        &quot;timestamp&quot;: 12.5,<br>        &quot;predictions&quot;: [<br>            {<br>                &quot;confidence&quot;: 0.9152086973190308,<br>                &quot;prediction&quot;: &quot;person&quot;<br>            },<br>            {<br>                &quot;confidence&quot;: 0.8809748291969299,<br>                &quot;prediction&quot;: &quot;person&quot;<br>            },<br>            {<br>                &quot;confidence&quot;: 0.8690718412399292,<br>                &quot;prediction&quot;: &quot;person&quot;<br>            },<br>            {<br>                &quot;confidence&quot;: 0.8113845586776733,<br>                &quot;prediction&quot;: &quot;person&quot;<br>            },<br>            {<br>                &quot;confidence&quot;: 0.25364750623703003,<br>                &quot;prediction&quot;: &quot;handbag&quot;<br>            }<br>        ]<br>    }<br>]</pre><pre>&quot;google_vit&quot;: [<br>    {<br>        &quot;timestamp&quot;: 12.5,<br>        &quot;predictions&quot;: [<br>            {<br>                &quot;confidence&quot;: 0.9410538077354431,<br>                &quot;prediction&quot;: &quot;picket fence, paling&quot;<br>            },<br>            {<br>                &quot;confidence&quot;: 0.02756260149180889,<br>                &quot;prediction&quot;: &quot;mobile home, manufactured home&quot;<br>            },<br>            {<br>                &quot;confidence&quot;: 0.007517252117395401,<br>                &quot;prediction&quot;: &quot;worm fence, snake fence, snake-rail fence, Virginia fence&quot;<br>            },<br>            {<br>                &quot;confidence&quot;: 0.0012280521914362907,<br>                &quot;prediction&quot;: &quot;tricycle, trike, velocipede&quot;<br>            },<br>            {<br>                &quot;confidence&quot;: 0.0007351838867180049,<br>                &quot;prediction&quot;: &quot;shopping cart&quot;<br>            }<br>        ]<br>    }<br>]</pre><p>From this output we can see at the same timestamp (12.5 seconds into the video) YOLO focuses on the foreground and predicts 2 people and a handbag, whereas Google ViT focuses on the background and predicts the home, fence, and possibly a tricycle and a shopping cart.</p><p>By combining these two we thought that it might be useful for auto-generating a list of objects that appear inside videos.</p><h3>Captions</h3><p><a href="https://huggingface.co/docs/transformers/main/model_doc/blip-2">BLIP-2</a> works in the same way as the object predictors, examining individual frames once every 100 frames of a video to try and caption the image content in those frames.</p><pre>{<br>    &quot;timestamp&quot;: 12.5,<br>    &quot;predictions&quot;: [<br>        {<br>            &quot;confidence&quot;: 0.9998831748962402,<br>            &quot;prediction&quot;: &quot;a group of people standing on a sidewalk&quot;<br>        }<br>    ]<br>}</pre><p>From the output we can see that BLIP-2 provides a reasonable caption of the image content — similar to a segment of the audio transcription we use for our audio search.</p><h3>Time to generate</h3><p>From tests with the Google Colab Notebook: <a href="https://colab.research.google.com/drive/1r7yKovTQ30LqlybQW0Bewwgfhsa_dFG0?usp=sharing">ACMI-x-VideoMAE-x-Transformers-x-YOLOv8</a> we can derive some approximate compute times using their A100 GPU on our test digitised video 2040x1530, 16fps, duration of 4 minutes and 19 seconds.</p><ul><li>Actions: 76 minutes (7.6 mins every 1,000 frames)</li><li>Objects: 21 minutes (ViT), 19 minutes (YOLO)</li><li>Captions: 7 minutes</li></ul><p><strong>Total</strong>: 123 minutes (30x the length of the video)</p><blockquote><strong><em>Update 7th September 2023 </em></strong><em>— after switching to using </em><em>imageio to get the individual video image frames and caching every 100th frame, we’ve been able to reduce the total time to generate video classifications to:<br></em><strong><em>2.3x</em></strong><em> video length on GPU<br></em><strong><em>6.2x</em></strong><em> video length on CPU</em></blockquote><p>We don’t have the budget to use virtualized A100 GPUs to process our entire collection — compute is expensive. Fortunately we are not in a huge rush, so we’re currently running all of these algorithms on our on-site VM server.</p><p>Our localized VM setup is currently:</p><ul><li>Ubuntu desktop</li><li>32 CPU cores at 36 GHz</li><li>64 GB memory (BLIP-2 requires at least 28 GB memory)</li><li>Syncs video classification metadata to XOS weekly</li></ul><p>We’ve currently classified <strong>90</strong> out of <strong>5,070</strong> videos. It has taken a while.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fZIyJzEV44XkMCFnBH0pgQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lMaJgpnwvfjNAQ3NZ_Isug.png" /><figcaption>Video classification on CPUs — left: running on a 2023 MacBook Pro, right: running in our Ubuntu VM</figcaption></figure><h3>Searching the results</h3><p>The nightly XOS search indexing task that has been indexing our Video’s audio transcription JSON metadata also happily indexes the classification JSON metadata. So no extra work was needed there.</p><p>On the frontend we specify a different search <strong>field</strong> to target <strong>search queries</strong> we send to Elasticsearch depending on whether the visitor chooses <strong>Audio transcriptions</strong> or <strong>Frame content</strong>.</p><pre># Frame content request to Elasticsearch to search BLIP-2 captions<br>{<br>    &#39;query&#39;: {<br>        &#39;match_phrase&#39;: {<br>            &#39;classification.captions.blip_2.predictions.prediction&#39;: search_query,<br>        },<br>    },<br>}<br><br># Audio transcriptions request to Elasticsearch to search the Whisper segments<br>{<br>    &#39;query&#39;: {<br>        &#39;match_phrase&#39;: {<br>            &#39;transcription.segments.text&#39;: search_query,<br>        },<br>    },<br>}</pre><p>Try it yourself on our website: <a href="https://www.acmi.net.au/videos/"><strong>acmi.net.au/videos/</strong></a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FSZOG7dbBLuo%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DSZOG7dbBLuo&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FSZOG7dbBLuo%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/452ef7f867f246b913d5968437f057ec/href">https://medium.com/media/452ef7f867f246b913d5968437f057ec/href</a></iframe><p>If you’d like to help accelerate the digitisation and cataloguing of our collection, we’d love your support: <a href="https://www.acmi.net.au/support-us/"><strong>acmi.net.au/support-us/</strong></a></p><p>Big thanks to Linda, Ben &amp; Candice from our collections team for digitising all of the film and feeding XOS with the footage, and our ICT team for access to so many CPUs on our VM.</p><h3>Next steps</h3><p>Action and object classifications are a means for ACMI to prototype a path towards machine augmented cataloguing of time-based media.</p><p>We’re also exploring creating <a href="https://platform.openai.com/docs/guides/embeddings">OpenAI Embeddings</a> of our Video metadata to cluster and find similar videos (and video frames).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=94bed300ca22" width="1" height="1" alt=""><hr><p><a href="https://labs.acmi.net.au/video-image-search-94bed300ca22">Search inside our videos — Part 2: content discovery</a> was originally published in <a href="https://labs.acmi.net.au/">ACMI LABS</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>