<?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 MPyK on Medium]]></title>
        <description><![CDATA[Stories by MPyK on Medium]]></description>
        <link>https://medium.com/@sopheaktra-yong?source=rss-8279bf0635d3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*XzcDxvFWbToZfQ1ZhhcOzQ.jpeg</url>
            <title>Stories by MPyK on Medium</title>
            <link>https://medium.com/@sopheaktra-yong?source=rss-8279bf0635d3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 20:47:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sopheaktra-yong/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[Stop Pasting Your Documents Into Someone Else’s Chatbot]]></title>
            <link>https://sopheaktra-yong.medium.com/stop-pasting-your-documents-into-someone-elses-chatbot-5c0d31d7f122?source=rss-8279bf0635d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c0d31d7f122</guid>
            <category><![CDATA[pdf]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[free]]></category>
            <category><![CDATA[ollama]]></category>
            <category><![CDATA[open-source]]></category>
            <dc:creator><![CDATA[MPyK]]></dc:creator>
            <pubDate>Wed, 26 Aug 2026 09:13:44 GMT</pubDate>
            <atom:updated>2026-08-26T09:13:44.100Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rCCtx0Q9nQi9uK3J9Cs34w.png" /></figure><p>You know the folder. Staff handbook, a couple of contracts, last year’s technical spec, meeting notes nobody has opened since, the PDF someone emailed round in March. Somewhere in there is the answer to the question you have right now, and there are two unappealing ways to find it: open files one at a time and skim until something looks familiar, or paste chunks into a chatbot and let a company you’ve never met read your handbook.</p><p>I’ve done both. The second bothers me more than it seems to bother most people. It isn’t only that the documents get uploaded — it’s what’s in them. A staff handbook has your salary bands. A contract has your client’s terms. Meeting notes have the thing that was said before it was decided. Those are exactly the documents you’d never email to a stranger, and pasting them into a text box is emailing them to a stranger with extra steps.</p><p>There’s a third option now, and it’s finally good enough to bother with. A model that can read a folder of your documents and answer questions about them, with citations, runs on an ordinary laptop, offline, for nothing. No account, no API key, no upload. This post is the build.</p><h3>What you get</h3><p>A page in your browser with a sidebar and a chat box. The sidebar is your knowledge base — every document the app can see, and buttons to add or remove them. The chat box answers questions using those documents and nothing else.</p><p>Two things in that screenshot matter more than the answer itself.</p><p>The first is [2]. Every claim carries a marker pointing at the passage it came from, and the Sources panel underneath shows those passages verbatim, so you can check the answer against the document in about four seconds.</p><p>The second is the reply below it. “What is the company’s parental leave policy?” is a perfectly reasonable question that these documents happen not to answer, and the model says so instead of writing three confident paragraphs about parental leave from whatever it absorbed during training. That refusal is the feature. A tool that answers everything is worse than useless for this job, because you can’t tell the real answers from the invented ones.</p><p>Setup takes about 15 minutes. After that it’s two or three seconds a question.</p><p>Worth saying plainly up front: this replaces the searching, not the reading. It finds the paragraph and tells you what it says. For anything that matters you open the source and read it yourself, which is what the citations are for.</p><h3>What you need first</h3><ul><li>A Mac or Windows laptop from the last four years or so. Both models run locally, which is the only real requirement here.</li><li>8 GB of RAM. The model that reads your documents is tiny; the one that writes the answers is the one that wants memory.</li><li>About 5 GB of free disk for the two downloads.</li></ul><h3>Two things to get out of the way</h3><p>This was built on a Mac. Ollama, Python and Streamlit all run on Windows perfectly well, so I expect the whole thing works there too. Where something differs on Windows I’ve put in a note:</p><blockquote><em>On Windows: notes like this one.</em></blockquote><p>Take those as the Windows equivalents as far as I know them, not as steps I’ve verified end to end.</p><p>Check the licence before you use this for paid work. Free to download and free to use in a business are two different things, and it’s easy to conflate them because nothing in the process ever asks you to agree to anything. ollama pull just downloads. Every model in the library comes with its own terms and they vary a lot. Some are permissive, some are research-only, some are fine until you cross a revenue or user threshold, some put conditions on what you&#39;re allowed to do with the output.</p><p>This app pulls two models, so that’s two licences to read, and they are not the same licence. Sizes within one family don’t necessarily match either, so check the tag you actually pulled rather than the family name. Locally:</p><pre>ollama show llama3:8b --license<br>ollama show nomic-embed-text --license</pre><p>Read those and the model cards on the vendors’ own sites before you point this at a client’s contracts.</p><h3>Step 1: Install Ollama</h3><p>Ollama runs AI models on your computer. After the initial model download it doesn’t talk to the internet.</p><p>Get it from <a href="https://ollama.com/">ollama.com</a>, install it like anything else, and open it once. A small llama shows up in your menu bar on a Mac or the system tray on Windows, which means the engine is running. No signup, no account, no card.</p><blockquote><em>On Windows: you get a single </em><em>OllamaSetup.exe, and it installs into your own user folder rather than </em><em>Program Files, so it won&#39;t ask for an admin password. It does add </em><em>ollama to your </em><em>PATH, but a terminal window you already had open won&#39;t have picked that up. Close it and open a fresh one before Step 2, or you&#39;ll get </em><em>&#39;ollama&#39; is not recognized as an internal or external command and assume something went wrong with the install.</em></blockquote><h3>Step 2: Get the two models</h3><p>Open a terminal. On a Mac, Cmd+Space, type Terminal, Enter. On Windows, Start key, type Command Prompt, Enter.</p><blockquote><em>On Windows: PowerShell works just as well as Command Prompt and pastes with </em><em>Ctrl+V like a normal application, where the old Command Prompt may want a right-click instead. Either is fine for everything in this post. The one thing to avoid is WSL. Ollama installed inside WSL is a separate engine from Ollama installed on Windows, and you&#39;ll download the models twice before working out why the app can&#39;t see them.</em></blockquote><p>This is the one real difference from a normal chatbot setup: you need two models, and they do completely different jobs.</p><pre>ollama pull nomic-embed-text</pre><p>274 MB, and it never writes a word of English. Its only job is to turn a chunk of text into a list of 768 numbers, positioned so that two chunks about the same thing end up near each other. That’s what makes “how much holiday do I get?” find a paragraph headed “## Holiday” that never uses the word “get”.</p><pre>ollama pull llama3:8b</pre><p>4.7 GB, and this is the one that writes the answers. It never sees your library — only the five passages the first model picked out, plus your question.</p><blockquote><em>On Windows: models go to </em><em>C:\Users\&lt;you&gt;\.ollama\models, so the 5 GB has to be free on </em><em>C: specifically. A spacious </em><em>D: drive won&#39;t help you. The Mac equivalent is </em><em>~/.ollama/models.</em></blockquote><p>Any chat model in Ollama will work here — the dropdown in the app lists whatever you have — but see the table at the end before you assume they’re interchangeable. They are not, and the way they differ is not the way I expected.</p><h3>Step 3: Five Python libraries</h3><p>Same terminal:</p><pre>pip install streamlit ollama numpy pypdf python-docx</pre><p>streamlit makes the web page, ollama talks to the engine, numpy does the maths that finds the right passage, and pypdf and python-docx pull the text out of PDFs and Word files.</p><p>If pip isn&#39;t recognised, get Python from <a href="https://python.org/">python.org</a> and tick &quot;Add Python to PATH&quot; while installing.</p><blockquote><em>On Windows: Python isn’t preinstalled, so you’ll almost certainly need that download, and “Add Python to PATH” on the first installer screen is the checkbox everyone skips. Avoid the Microsoft Store version of Python too; its sandboxed file permissions produce strange Streamlit failures that are no fun to debug. Once it’s in, use:</em></blockquote><blockquote><em>py -m pip install streamlit ollama numpy pypdf python-docx</em></blockquote><blockquote><em>py -m pip rather than plain </em><em>pip makes sure you&#39;re installing into the same Python that ends up running the app.</em></blockquote><p>On a Mac you may get error: externally-managed-environment instead. That&#39;s a Python safety guard, not something you broke. Either use pip3 install --user streamlit ollama numpy pypdf python-docx, or set up a virtual environment in the project folder with python3 -m venv .venv &amp;&amp; source .venv/bin/activate and install inside that.</p><h3>Step 4: Get the app</h3><p>Copying a few hundred lines out of a blog post is a great way to lose a bracket somewhere on line 300, so download it instead:</p><pre>cd ~/Desktop<br>git clone https://github.com/yong-asial/DocumentQA.git<br>cd DocumentQA</pre><p>If you don’t have git, open <a href="https://github.com/yong-asial/DocumentQA">the repository</a> in your browser, click the green Code button, choose Download ZIP, and unzip it onto your Desktop. GitHub names the unzipped folder DocumentQA-main, so rename it to DocumentQA and the commands in the next step will match.</p><p>The repo pins the same five libraries from Step 3 in app/requirements.txt, so pip install -r app/requirements.txt from inside the folder does the whole of Step 3 in one line.</p><blockquote><em>On Windows: </em><em>cd %USERPROFILE%\Desktop first, and if OneDrive is syncing your Desktop the real path is </em><em>%USERPROFILE%\OneDrive\Desktop. Run </em><em>dir %USERPROFILE% to see which of the two you have. The ZIP route works the same; right-click the download and choose Extract All.</em></blockquote><p>You don’t need to read the code to use it. But the part people expect to be complicated is worth showing, because it isn’t.</p><p>Turning text into numbers is one call to Ollama and a little tidying after it:</p><pre>reply = ollama.embed(model=model, input=window)<br>vectors.extend(reply[&quot;embeddings&quot;])</pre><pre>array = np.asarray(vectors, dtype=np.float32)<br>norms = np.linalg.norm(array, axis=1, keepdims=True)<br>return array / np.maximum(norms, 1e-12)</pre><p>That last line scales every vector to length 1. It looks like housekeeping and it’s actually the whole reason the next part is one line.</p><p>Finding the right passage is a multiplication:</p><pre>query = embed([question], embed_model, is_query=True)[0]<br>scores = index[&quot;vectors&quot;] @ query</pre><p>index[&quot;vectors&quot;] is every chunk of every document, stacked. That @ compares the question against all of them at once and hands back a score for each. Take the best five and you&#39;re done — 9 milliseconds across 300 passages on my laptop.</p><p>This is the part I’d tell anyone building something similar. Retrieval-augmented generation has an industry of vector databases around it, and at this size you don’t need one. A dot product over a numpy array is the same maths, it’s instant, and it’s a dependency you never have to maintain.</p><p>Getting the answer is the same seven lines any chatbot uses, with the retrieved passages pasted into the prompt. The prompt is the interesting half, and it’s just English:</p><pre>ANSWER_PROMPT = &quot;&quot;&quot;You are answering questions about a private collection of \<br>documents. The numbered sources below are the only knowledge you have.</pre><pre>Rules:<br>- Answer using ONLY the sources. Do not use anything you know from training.<br>- Read every source before you answer. A source can hold the answer while<br>  wording it completely differently from the question, and some questions need<br>  a figure in the question compared against a figure in a source.<br>- Cite the sources you used inline, like [1] or [2][3], right after the claim<br>  they support.<br>- Only when you have read all of them and none covers the question, reply<br>  exactly: &quot;I couldn&#39;t find that in your documents.&quot; Then say in one sentence<br>  what the documents do cover that is closest. Never guess and never fill a gap<br>  from general knowledge.<br>- If the sources disagree with each other, say so and cite both.<br>- Quote figures, names and dates exactly as they appear. Do not round or<br>  convert them.<br>- Answer in the language of the question.</pre><pre>Sources:<br>{context}</pre><pre>Question: {question}&quot;&quot;&quot;</pre><p>The second rule is there because of a bug I spent an afternoon on. My first version of this prompt was shorter and stricter, and the app kept refusing questions whose answers were sitting right there in the context. Ask “how many unused holiday days can I carry over?” and it would say it couldn’t find that, while source [2] plainly read <em>“Up to 5 unused days carry over into the next year.”</em> Ten of twelve test questions answered, two refused for no reason.</p><p>The model wasn’t failing to retrieve. It was failing to read. Adding <em>“Read every source before you answer”</em> — and, importantly, moving the refusal from a rule it could reach for immediately to one gated behind <em>“only when you have read all of them”</em> — took it to eleven of twelve.</p><p>I also tried the obvious fix of softening the refusal rule generally. That answered both missing questions and broke something worse: asked about a parental leave policy the documents don’t contain, the model replied <em>“I’m ready to answer your question. Please go ahead and ask it!”</em> Refusing well and answering well pull against each other, and the wording above is the balance I landed on. If you change one rule, re-run tests/test_qa.py before you trust it.</p><h3>Step 5: Run it</h3><p>Back in the terminal:</p><pre>cd ~/Desktop/DocumentQA<br>streamlit run app/app.py</pre><p>On a Mac you can also just double-click run.command in the folder, which starts Ollama first if it isn&#39;t already running.</p><blockquote><em>On Windows: backslashes, and it’s safest to spell the path out:</em></blockquote><blockquote><em>cd %USERPROFILE%\Desktop\DocumentQA py -m streamlit run app\app.py</em></blockquote><blockquote><em>In PowerShell, use </em><em>cd $HOME\Desktop\DocumentQA instead. If bare </em><em>streamlit isn&#39;t recognised, </em><em>py -m streamlit always works; it&#39;s the same program found a more reliable way. </em><em>run.command is a Mac double-click launcher and won&#39;t do anything useful on Windows. You may also get a firewall prompt the first time, which you can safely cancel, since nothing here needs to accept connections from anywhere.</em></blockquote><p>The browser opens by itself, and the first time it will be empty:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FW7ZnNkIjApbtbxt.png" /></figure><p>Your knowledge base is the documents folder inside the project. Two ways to fill it: drop files straight into that folder in Finder or Explorer, or use Add documents in the sidebar, which copies them into the same place. Either way they&#39;re still there tomorrow. It reads .txt, .md, .csv, .log, .json, .pdf and .docx.</p><p>No documents to hand? Click Load example documents and it copies in the three I used for testing — an English staff handbook, an English technical spec and some Japanese meeting notes — so you have something to ask about immediately.</p><p>Then ask. The first question takes about six seconds while the model loads into memory; after that it’s two to three seconds each. Open the Sources panel under any answer and you get the passages it actually used, with a match score:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*soMvA-pNVjUU5AL_.png" /></figure><p>That screenshot shows something worth understanding. The top-scoring passage, [1] at 0.71, is about <em>expenses</em> — it doesn&#39;t contain the answer at all. The answer came from [2] at 0.62. Similarity search gets you close, not exact, and that&#39;s precisely why five passages go to the model instead of one. If you ever build this yourself and find it retrieving one chunk to save tokens, this is the failure you&#39;ll get.</p><p>To remove a document, click the ✕ next to it. It asks first, because it deletes the actual file from the actual folder — this is a file manager as well as a chat window, and I’d rather it were annoying than surprising.</p><p>Ctrl+C in the terminal stops it. Tomorrow, same two commands. (That&#39;s Ctrl and not Cmd, even on a Mac.)</p><h3>What it gets wrong</h3><p>I’d rather you hear these from me than find them at the wrong moment.</p><p>Ask in the language the document is written in. nomic-embed-text is English-centric. Asked in Japanese, the Japanese meeting notes come first with a score of 0.70. Asked the same thing in English — &quot;how much is the monthly rent for the new office?&quot; — the <em>English</em> handbook wins at 0.59 and the answer is missed entirely. Same-language questions are fine in either language; it&#39;s crossing over that fails. If your folder mixes languages, ollama pull bge-m3 and pick it in the Models dropdown.</p><p>Questions that need a comparison get declined. “Do I need a receipt for a £20 taxi?” requires noticing that £20 is under the £25 threshold in the handbook. An 8B model usually says it can’t find the answer instead. Ask for the rule — “what’s the receipt threshold?” — rather than the verdict. This is the twelfth question that prompt fix didn’t rescue.</p><p>Scanned PDFs don’t work. A PDF with no text layer is listed as skipped, with a note saying why. There’s no OCR here.</p><p>The match score is a hint, not a guarantee. I measured relevant questions at 0.57–0.70 and irrelevant ones at 0.41–0.63. Those ranges overlap, so there’s no threshold that separates them, and the app doesn’t pretend otherwise — the score is displayed, and the refusal rule in the prompt does the actual work.</p><h3>So, was it worth it?</h3><p>You now have something that reads a folder of your own documents and answers questions about them, with citations, for nothing per question, on a plane, with no subscription and no data processing agreement to read. The documents never leave the folder they’re already in.</p><p>An answer you can’t trace isn’t much use in the situation this tool exists for — you’re asking because you don’t already know, which means you can’t tell a good answer from a plausible one without opening the source. Citations aren’t a nice touch on top of a document Q&amp;A tool. They’re the part that makes it a tool rather than a party trick, and they’re the first thing I’d check on any model you swap in.</p><p>The code is on <a href="https://github.com/yong-asial/DocumentQA">GitHub</a>. It’s two files — a Streamlit page and a retrieval module you can read in a sitting — and the answer prompt is English you can edit in a text editor — point it at your own folder, change the rules to suit your own documents, or lift the dot product into something of your own. The same pattern works for a wiki export, a codebase, a year of meeting notes, or any other pile of text you’d rather ask than search.</p><p>Happy Coding.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c0d31d7f122" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A receipt-to-spreadsheet tool that never leaves your laptop]]></title>
            <link>https://medium.com/the-web-tub/a-receipt-to-spreadsheet-tool-that-never-leaves-your-laptop-29be0ff18c94?source=rss-8279bf0635d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/29be0ff18c94</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[privacy]]></category>
            <category><![CDATA[ollama]]></category>
            <category><![CDATA[free]]></category>
            <dc:creator><![CDATA[MPyK]]></dc:creator>
            <pubDate>Wed, 26 Aug 2026 07:47:46 GMT</pubDate>
            <atom:updated>2026-08-26T07:50:01.315Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YgyveQG40tHfAiSNRReNDg.png" /></figure><p>If you run a small business you already know this routine. There’s a shoebox of receipts, a month-end deadline, and two unappealing ways through it: type every line into a spreadsheet yourself, or find one of those free “invoice converter” sites and hand your company’s financial records to a stranger.</p><p>I’ve done both. The second one bothers me more than it seems to bother most people. Those sites are free for a reason, and the reason is that your documents are worth something, whether as training data, as marketing signal, or just as files sitting on a server you have no control over. A receipt tells you who a company buys from, what its margins look like, which staff member expensed lunch, and the last four digits of a card.</p><p>There’s a third option now, and it’s finally good enough to bother with. Vision models that can read a crumpled thermal receipt will run on an ordinary laptop, offline, for nothing. No account, no API key, no upload. This post is the build.</p><h3><strong>What you get</strong></h3><p>A page in your browser with a file picker. Drag in receipt images, press one button, get a table you can download as a CSV and open in Excel or Spreadsheets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZB_TfcUKxPORKrluK3--bw.png" /><figcaption>The app when you first open it</figcaption></figure><p>Behind that page, a vision model on your own machine reads each image and pulls out vendor, date, invoice number, subtotal, tax, total, currency and payment method.</p><p>Setup takes about 15 minutes. After that it’s roughly 5 seconds a receipt, depending on your PC or laptop specification.</p><p>Worth saying plainly up front: this replaces the typing, not the checking. You still read the numbers before they go into your books. What you’re buying is maybe 90% of the tedium, not an accountant.</p><h3><strong>What you need first</strong></h3><ul><li>A Mac or Windows laptop from the last four years or so. The model runs locally, which is the only real requirement here.</li><li>8 GB of RAM, though 16 is more comfortable. There’s a smaller model below if you’re on 8.</li><li>About 7 GB of free disk for the download.</li></ul><h3><strong>Two things to get out of the way</strong></h3><p><strong>This was built on a Mac.</strong> Ollama, Python and Streamlit all run on Windows perfectly well, so I expect the whole thing works there too. Where something differs on Windows I’ve put in a note:</p><blockquote><strong>On Windows: </strong>notes like this one.</blockquote><p>Take those as the Windows equivalents as far as I know them, not as steps I’ve verified end to end.</p><p><strong>Check the licence before you use this for paid work.</strong> Free to download and free to use in a business are two different things, and it’s easy to conflate them because nothing in the process ever asks you to agree to anything. `<strong><em>ollama pull</em></strong>` just downloads. Every model in the library comes with its own terms and they vary a lot. Some are permissive, some are research-only, some are fine until you cross a revenue or user threshold, some put conditions on what you’re allowed to do with the output.</p><p>The part that catches people is that sizes within one family don’t necessarily share a licence. `<strong><em>qwen2.5vl:3b</em></strong>` and `<strong><em>qwen2.5vl:7b</em></strong>` are separate releases, so check the tag you actually pulled rather than the family name. Locally:</p><pre>ollama show qwen2.5vl:7b - license</pre><p>Read that and the model card on the vendor’s own site before you point this at a client’s books.</p><h3><strong>Step 1: Install Ollama</strong></h3><p>Ollama runs AI models on your computer. After the initial model download it doesn’t talk to the internet.</p><p>Get it from <a href="https://ollama.com/">ollama.com</a>, install it like anything else, and open it once. A small llama shows up in your menu bar on a Mac or the system tray on Windows, which means the engine is running. No signup, no account, no card.</p><blockquote><strong>On Windows:</strong> you get a single `<strong>OllamaSetup.exe</strong>`, and it installs into your own user folder rather than `<strong>Program Files</strong>`, so it won’t ask for an admin password. It does add `<strong>ollama</strong>` to your `<strong>PATH</strong>`, but a terminal window you already had open won’t have picked that up. Close it and open a fresh one before Step 2, or you’ll get `’<strong>ollama</strong>’ <strong>is not recognized as an internal or external command</strong>` and assume something went wrong with the install.</blockquote><h3><strong>Step 2: Get the model</strong></h3><p>Open a terminal. On a Mac, `<strong><em>Cmd+Space</em></strong>`, type <strong><em>Terminal</em></strong>, Enter. On Windows, Start key, type<em> </em><strong><em>Command Prompt</em></strong>, Enter.</p><blockquote><strong>On Windows:</strong> PowerShell works just as well as Command Prompt and pastes with `<strong>Ctrl+V</strong>` like a normal application, where the old Command Prompt may want a right-click instead. Either is fine for everything in this post. The one thing to avoid is WSL. Ollama installed inside WSL is a separate engine from Ollama installed on Windows, and you’ll download six gigabytes twice before working out why the app can’t see your model.</blockquote><p>Then:</p><pre>ollama pull qwen2.5vl:7b</pre><p>That’s about 6 GB, so go and make coffee. It’s a one-time thing.</p><blockquote>&gt; <strong>On Windows:</strong> models go to `<strong>C:\Users\&lt;you&gt;\.ollama\models</strong>`, so the 7 GB has to be free on `<strong>C:</strong>` specifically. A spacious `<strong>D:</strong>` drive won’t help you. The Mac equivalent is `<strong>~/.ollama/models</strong>`.</blockquote><p>Only 8 GB of RAM? Take the small one instead:</p><pre>ollama pull qwen2.5vl:3b</pre><h3><strong>Step 3: Three Python libraries</strong></h3><p>Same terminal:</p><pre>pip install streamlit pandas ollama pillow</pre><p>streamlit makes the web page, pandas makes the spreadsheet, ollama talks to the engine, and pillow tidies up the images before the model sees them.</p><p>If `<strong><em>pip</em></strong>` isn’t recognised, get Python from <a href="https://python.org/">python.org</a> and tick “<strong><em>Add Python to PATH</em></strong>” while installing.</p><blockquote><strong>On Windows:</strong> Python isn’t preinstalled, so you’ll almost certainly need that download, and “<strong>Add Python to PATH</strong>” on the first installer screen is the checkbox everyone skips. Avoid the Microsoft Store version of Python too; its sandboxed file permissions produce strange Streamlit failures that are no fun to debug. Once it’s in, use the command below.</blockquote><pre>py -m pip install streamlit pandas ollama pillow</pre><blockquote>`<strong>py -m pip</strong>` rather than plain `<strong>pip</strong>` makes sure you’re installing into the same Python that ends up running the app.</blockquote><p>On a Mac you may get `<strong><em>error: externally-managed-environment</em></strong>` instead. That’s a Python safety guard, not something you broke. Either use `<strong><em>pip3 install — user streamlit pandas ollama pillow</em></strong>`, or set up a virtual environment in the project folder with `<strong><em>python3 -m venv .venv &amp;&amp; source .venv/bin/activate</em></strong>` and install inside that.</p><h3><strong>Step 4: Get the app</strong></h3><p>The app is five short Python files, and it already lives on GitHub. Copying a few hundred lines out of a blog post is a great way to lose a bracket somewhere on line 300, so download it instead:</p><pre>cd ~/Desktop<br>git clone https://github.com/yong-asial/ReceiptExtractor.git<br>cd ReceiptExtractor</pre><p>If you don’t have `<strong>git</strong>`, open <a href="https://github.com/yong-asial/ReceiptExtractor">the repository</a> in your browser, click the green <strong>Code</strong> button, choose <strong>Download ZIP</strong>, and unzip it onto your Desktop. GitHub names the unzipped folder `<strong><em>ReceiptExtractor-main</em></strong>`, so rename it to `<strong><em>ReceiptExtractor</em></strong>` and the commands in the next step will match.</p><p>The repo pins the same four libraries from Step 3 in `<strong><em>app/requirements.txt</em></strong>`, so if you skipped ahead — or want them in a virtual environment rather than system-wide — `<strong><em>pip install -r app/requirements.txt</em></strong>` from inside the folder does the whole of Step 3 in one line.</p><blockquote><strong>On Windows:</strong> `<strong><em>cd %USERPROFILE%\Desktop</em></strong>` first, and if OneDrive is syncing your Desktop the real path is `<strong>%USERPROFILE%\OneDrive\Desktop`. Run `dir %USERPROFILE%</strong>` to see which of the two you have. The ZIP route works the same; right-click the download and choose <strong>**Extract All**</strong>.</blockquote><p>You don’t need to read the code to use it. But if you want to, it’s split so that you can open the one file you care about and ignore the rest. Each is a couple of hundred lines at most, and each says at the top what it’s for:</p><ul><li><strong>`settings.py`</strong> — the columns, the prompt, the size limits. <strong>**Start here.**</strong></li><li><strong>`uploads.py`</strong> — checking the dropped-in files, and preparing an image.</li><li><strong>`reader.py`</strong> — asking the local model, and reading its reply.</li><li><strong>`tidy.py`</strong>— turning that reply into figures you could put in a ledger.</li><li><strong>`app.py`</strong> — the page itself: what you see, and in what order.</li></ul><p>Underneath the file handling and the table, the piece that actually reads a receipt is seven lines of `<strong><em>reader.py</em></strong>`:</p><pre>response = ollama.chat(<br>    model=model,<br>    messages=[{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: PROMPT, &quot;images&quot;: [image_bytes]}],<br>    # temperature 0 keeps repeated runs on the same receipt consistent.<br>    options={&quot;temperature&quot;: 0},<br>)<br>return normalise(parse_json(response[&quot;message&quot;][&quot;content&quot;]))</pre><p>That’s the entire trick: hand the image and a prompt to a model running on your own machine, and read the JSON back.</p><p>The `<strong><em>PROMPT</em></strong>` is the other half of it, and it’s just English. It lives in `<strong><em>settings.py</em></strong>` next to the field list, and asks for eight named fields and nothing else:</p><pre>FIELDS = [<br>    &quot;Vendor Name&quot;,<br>    &quot;Date&quot;,<br>    &quot;Invoice Number&quot;,<br>    &quot;Subtotal&quot;,<br>    &quot;Tax&quot;,<br>    &quot;Total Amount&quot;,<br>    &quot;Currency&quot;,<br>    &quot;Payment Method&quot;,<br>]<br><br># Which of the FIELDS above hold money, and which one holds a date. These are<br># cleaned up differently from ordinary text, so if you add or rename a field,<br># check that it is listed here when it should be. Everything else in FIELDS is<br># copied across as plain text.<br>AMOUNT_FIELDS = (&quot;Subtotal&quot;, &quot;Tax&quot;, &quot;Total Amount&quot;)<br>DATE_FIELD = &quot;Date&quot;<br><br># What we write in a column when the value simply isn&#39;t on the document.<br>NOT_FOUND = &quot;Not Found&quot;<br><br># What we say to the model. It is just English — edit it to suit your business:<br># add a purchase order number, drop the payment method, ask for line items, or<br># write the rules in your own language. Keep the JSON-only instruction, though;<br># the rest of the app expects a JSON object back.<br>PROMPT = f&quot;&quot;&quot;You are a bookkeeping assistant reading a receipt or invoice.<br><br>Return ONLY a JSON object with exactly these keys:<br>{json.dumps(FIELDS, indent=2)}<br><br>Rules:<br>- &quot;Date&quot; is the date the receipt or invoice was ISSUED, not a due date or a<br>  service period. Return it as YYYY-MM-DD, converting from whatever format the<br>  document uses (including Japanese 2024年11月5日 style).<br>- Copy &quot;Vendor Name&quot; and &quot;Payment Method&quot; exactly as printed, in the document&#39;s<br>  own language and script. Do not translate or romanise them.<br>- Amounts must be plain numbers with no currency symbols and no thousands<br>  separators, e.g. 1234.56<br>- &quot;Currency&quot; is the 3-letter code, e.g. USD, JPY, EUR.<br>- Use the string &quot;Not Found&quot; for anything you cannot read on the receipt.<br>- Never guess or invent a value. Never do arithmetic to fill a blank.<br>- Output no markdown, no code fences, no commentary. JSON only.<br>&quot;&quot;&quot;</pre><p>Feel free to change that prompt to suit your own requirements and business needs — add a purchase order number, drop the payment method, ask for line items, or write the rules in your own language. `<strong><em>FIELDS</em></strong>` drives the CSV columns, and right below it `<strong><em>AMOUNT_FIELDS</em></strong>` and `<strong><em>DATE_FIELD</em></strong>` say which of those columns hold money and which holds a date, because those get cleaned up differently from plain text. Keeping all three in `<strong><em>settings.py</em></strong>` means a new field is usually a one-file change.</p><p>The one thing that doesn’t follow you automatically is the <strong>**Needs Review**</strong> check in `<strong><em>tidy.py</em></strong>`, which assumes subtotal plus tax should equal the total. If you rework the money columns, read that function too.</p><p>Cleaning up the answer is what `<strong><em>tidy.py</em></strong>` is for, and the whole file is about not trusting the model blindly. It strips currency symbols, converts `<strong><em>1.725,50</em></strong>` to `<strong><em>1725.50</em></strong>`, turns `<strong><em>2024年11月5日</em></strong>` into `<strong><em>2024–11–05</em></strong>`, throws away anything that doesn’t end up looking like a number, and refuses to invent a date that doesn’t exist. Where a value is genuinely ambiguous — `<strong><em>06/07/2024</em></strong>` could be June 7th or July 6th, `<strong><em>1.234</em></strong>` could be 1234 or 1.234 — it keeps what was printed and flags the row instead of guessing. Those details are worth a read in the file itself if you plan to point this at real books; they’re the difference between a demo and something you’d trust.</p><h3><strong>Step 5: Run it</strong></h3><p>Back in the terminal:</p><pre>cd ~/Desktop/ReceiptExtractor<br>streamlit run app/app.py</pre><blockquote><strong>On Windows:</strong> backslashes, and it’s safest to spell the path out, as below. In PowerShell, use `<strong>cd $HOME\Desktop\ReceiptExtractor</strong>` instead.</blockquote><pre>cd %USERPROFILE%\Desktop\ReceiptExtractor<br>py -m streamlit run app\app.py</pre><blockquote>Two gotchas here. If bare `<strong>streamlit</strong>` isn’t recognised, `<strong>py -m streamlit</strong>` always works; it’s the same program found a more reliable way. And if OneDrive is syncing your Desktop, the real path is `<strong>%USERPROFILE%\OneDrive\Desktop\…</strong>`, so run `<strong>dir %USERPROFILE%</strong>` to see which of the two you’ve got. You may also get a firewall prompt the first time, which you can safely cancel, since nothing here needs to accept connections from anywhere.</blockquote><p>The browser opens by itself. Drag in some receipts, click <strong>**Extract data**</strong>, and watch the bar.</p><p>No receipts to hand? The repo ships the six test documents I used, in <a href="https://github.com/yong-asial/ReceiptExtractor/tree/main/tests/receipts">tests/receipts</a>. Drag those in first to see what the output looks like. Their correct values are in <a href="https://github.com/yong-asial/ReceiptExtractor/blob/main/tests/receipts/ground_truth.json">ground_truth.json</a> in the same folder, so you can check the table against them field by field. The first one takes 10–20 seconds while the model loads into memory, then it settles down to about 5 seconds each.</p><p>When it finishes you get a green <strong>**Read 6 receipts.**</strong> line, the table, and a download button:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YgyveQG40tHfAiSNRReNDg.png" /><figcaption>Six receipts extracted into a table, ready to download as CSV</figcaption></figure><p>That run is six documents in three languages and three currencies — a US cafe receipt, a German invoice with `<strong><em>1.725,50</em></strong>` written the European way, a blurry photo of a fuel receipt taken at an angle, and three Japanese documents — and every field on every one of them is correct. The Japanese vendor names come back as 株式会社サクラマート rather than a romanised guess, and the dates are all normalised to `<strong><em>YYYY-MM-DD</em></strong>` no matter how the original was written.</p><p><strong>**Download as spreadsheet (CSV)**</strong> gives you a file that opens straight into Excel or Spreadsheets. One warning: spreadsheet apps like to strip the leading zeros off invoice numbers such as `000517`, so set that column to Text on import if it matters to you.</p><p>`<strong><em>Ctrl+C</em></strong>` in the terminal stops it. Tomorrow, same two commands. (That’s `<strong><em>Ctrl</em></strong>` and not `<strong><em>Cmd</em></strong>`, even on a Mac.)</p><h3><strong>So, was it worth it?</strong></h3><p>You now have a receipt reader that costs nothing per scan, works on a plane, and never sends a client’s bank details to a server you can’t name. No subscription, no per-page pricing, no data processing agreement to read.</p><p>The honest limits are worth stating. It’s roughly five seconds a receipt, so this is a tool for a shoebox of receipts at the end of a quarter, not for thousands at a time. It needs about 6 GB of free memory for the 7B model, though the 3B one scored identically on my tests and fits comfortably on an 8 GB machine. And it is a model reading an image, which means it will eventually misread something — that’s why the app checks whether subtotal plus tax equals the total and flags the row when it doesn’t. Look at the <strong>**Needs Review**</strong> column before you trust a number.</p><p>What surprised me most was how good the small local models have got. I expected to be writing a post about a clever-but-flawed weekend hack, and instead `qwen2.5vl` read all 48 fields across all six test documents correctly, including the deliberately bad phone photo and the Japanese invoice. Two years ago this needed a cloud API and a per-page fee. Now it runs on a laptop, in five files short enough to read in one sitting.</p><p>The code is on <a href="https://github.com/yong-asial/ReceiptExtractor">GitHub</a>. Change the field list, point it at your own documents, or lift the seven lines that matter into something of your own — the same pattern works for business cards, ID documents, handwritten notes, or any other pile of paper you’d rather not type up by hand.</p><p>Happy Coding.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29be0ff18c94" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-web-tub/a-receipt-to-spreadsheet-tool-that-never-leaves-your-laptop-29be0ff18c94">A receipt-to-spreadsheet tool that never leaves your laptop</a> was originally published in <a href="https://medium.com/the-web-tub">The Web Tub</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Monaca Expands Support to Capacitor Projects]]></title>
            <link>https://medium.com/the-web-tub/monaca-expands-support-to-capacitor-projects-804dd0863c6a?source=rss-8279bf0635d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/804dd0863c6a</guid>
            <category><![CDATA[cordova]]></category>
            <category><![CDATA[capacitor]]></category>
            <category><![CDATA[mobile]]></category>
            <category><![CDATA[ionic]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[MPyK]]></dc:creator>
            <pubDate>Wed, 26 Jun 2024 02:03:56 GMT</pubDate>
            <atom:updated>2024-06-26T02:03:56.519Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*3LMWEV7pPJKD3wGxKoDsAw.png" /></figure><p>Monaca, a leading platform known for creating and building Cordova projects, has now expanded its support to include Capacitor projects. This development opens new opportunities for developers looking to leverage modern web technologies in their mobile applications.</p><h3>About Monaca</h3><p>Monaca is a robust platform designed to streamline the development process for hybrid mobile applications. It offers:</p><ul><li>A comprehensive suite of tools for creating, debugging, and building Cordova-based projects</li><li>A cloud-based IDE that simplifies the build process</li><li>Particular benefits for beginners and those looking to quickly deploy their apps</li></ul><p>For more details about Monaca, you can visit:</p><ul><li><a href="https://en.docs.monaca.io/products_guide/monaca_intro">Monaca Introduction</a></li><li><a href="https://monaca.io/">Monaca Official Website</a></li></ul><h3>Introducing Capacitor</h3><p>Capacitor is a cross-platform app runtime that allows developers to build web apps that run natively on iOS, Android, and the web. Capacitor aims to modernize the hybrid app development experience by providing a more flexible and powerful framework.</p><p>Key features of Capacitor include:</p><ul><li>Seamless integration with modern web development tools and libraries.</li><li>Enhanced plugin system with easier management and custom plugin development.</li><li>Support for native functionality with a straightforward API.</li></ul><p>For more information on Capacitor, visit the <a href="https://capacitorjs.com/docs">Capacitor Documentation</a>.</p><h3>What This Means for Developers</h3><p>The inclusion of Capacitor support in Monaca represents a significant upgrade for developers. Now, they can choose between Cordova and Capacitor based on their project requirements and preferences. This flexibility ensures that developers can leverage the strengths of both platforms, whether they need the traditional stability of Cordova or the modern capabilities of Capacitor.</p><p>By supporting both frameworks, Monaca continues to enhance its value proposition, making it an even more attractive choice for hybrid mobile app development. Whether you’re a beginner or an experienced developer, Monaca’s expanded support provides the tools you need to succeed in creating powerful, cross-platform applications.</p><h3>Create a Capacitor Project in Monaca</h3><h4>Step 1: Access the Monaca Dashboard</h4><ol><li><strong>Log in to Monaca</strong>: Go to the <a href="https://console.monaca.mobi/dashboard">Monaca Cloud IDE</a> dashboard.</li><li><strong>Create a New Project</strong>: Click on the “Create New Project” button.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j6UXyLtD4nRLDsR5SpRj3w.png" /></figure><h4>Step 2: Select Project Type</h4><ol><li><strong>Choose Capacitor</strong>: On the “Create New Project” page, select “Capacitor” under the “Project Type” section.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iO7SgXUgKEMNehAS0xbzew.png" /></figure><p><strong>2. Choose Framework and Template</strong>:</p><ul><li>Ensure “Capacitor Core Framework” is selected under “Capacitor Framework”.</li><li>Choose “Capacitor Basic” as the template.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WdxGSJgMsmQ2bjFxXpI38g.png" /></figure><p><strong>3. Project Information</strong>:</p><ul><li>Enter a name for your project and a description if desired.</li><li>Click on the “Create Project” button to finalize your new Capacitor project.</li></ul><p>Your new Capacitor project is now set up in Monaca, and you can start developing your hybrid mobile application with ease.</p><h3>Start the Project</h3><p>On the dashboard, find your project in the project list. You should see your newly created project, for example, “My First Capacitor Project”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jdvviUeUnK4ZVxkvPOwK1g.png" /></figure><p>Click on the project name and click on “Open in Cloud IDE” to open it in the Monaca Cloud IDE.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*keX0kRJ4HSQQ-zMBgOJsCQ.png" /></figure><h3>Configuring App Settings</h3><p>Click on the “Configure” menu at the top of the IDE.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/1*7GMJXmcYeJ30Kh4LApmOlw.png" /></figure><p>You can configure various settings, including the application name, ID, version, icon, and splash screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f03Fwy85VUWQvRnJNU-DDA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CSCt292Nyza9rbyuxgG9nw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PCLtd4YGjaXwufG9aIBTlQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GgGfT0KC0UkZFVV87RK4Ww.png" /></figure><h3>Start the Build</h3><p>Click on the “Build” menu at the top of the IDE.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*WG6LjfbNUVo6tmIXqZvTtA.png" /></figure><p>You can easily start the build process with a single click on the “Start Build” button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p7cEQbLnIW7huu-NF_HpWA.png" /></figure><h3>Conclusion</h3><p>With Monaca’s new support for Capacitor projects, developers now have a powerful and flexible platform for creating cross-platform mobile applications. By following the straightforward steps outlined above, you can quickly set up and configure your Capacitor projects within the Monaca Cloud IDE. The process of creating a new project, accessing app settings, and configuring essential details such as icons and splash screens has been simplified to enhance your development experience.</p><p>Monaca continues to be an excellent choice for both beginners and experienced developers, offering robust tools and a seamless development environment. The integration with Capacitor expands its capabilities, allowing you to leverage modern web technologies to build high-quality mobile apps. Start your journey with Monaca and Capacitor today and bring your app ideas to life with ease.</p><p>Happy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=804dd0863c6a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-web-tub/monaca-expands-support-to-capacitor-projects-804dd0863c6a">Monaca Expands Support to Capacitor Projects</a> was originally published in <a href="https://medium.com/the-web-tub">The Web Tub</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Let AIs do the Jobs with CrewAI]]></title>
            <link>https://medium.com/the-web-tub/let-ais-do-the-jobs-with-crewai-cfdbcd7eabaa?source=rss-8279bf0635d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/cfdbcd7eabaa</guid>
            <category><![CDATA[ollama]]></category>
            <category><![CDATA[gpt]]></category>
            <category><![CDATA[crew-ai]]></category>
            <category><![CDATA[embedding]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[MPyK]]></dc:creator>
            <pubDate>Fri, 12 Apr 2024 05:31:16 GMT</pubDate>
            <atom:updated>2024-04-12T05:46:21.808Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Uv6WuI6grnsUQ1Iyhl5pxg.jpeg" /></figure><p>In this tutorial, we’ll demonstrate how to leverage CrewAI to create and deploy multiple AI agents that can perform a variety of tasks for us. While there are countless tutorials showcasing the capabilities of GPT-4 models, this time we’ll be utilizing a free, open-source model that you can download to your local machine. This will allow you to explore the concept without incurring any costs, and you’ll find that it works remarkably well.</p><p>The application we’re creating will task our AI agents with thinking like humans and generating a well-written blog post on any topic we provide. This approach allows us to harness the power of AI to streamline the content creation process, freeing up valuable time and resources that can be devoted to other priorities.</p><h3>Setting the Stage: Tools and Technologies</h3><p>Before we dive into the code, let’s take a moment to understand the key components that will power our AI-driven blog.</p><ol><li><a href="https://ollama.com/"><strong>Ollama</strong></a>: Ollama is a tool to run LLM model locally. It offers a range of pre-trained models, each with its own unique capabilities, which we’ll leverage in our project.</li><li><a href="https://python.langchain.com/docs/get_started/introduction/"><strong>LangChain</strong></a>: LangChain is a framework that simplifies the development of applications powered by large language models. It provides a set of abstractions and tools that make it easier to build complex AI systems.</li><li><a href="https://docs.trychroma.com/"><strong>Chroma</strong></a>: Chroma is a high-performance vector database that integrates seamlessly with LangChain. It allows us to efficiently store and retrieve text embeddings, which are crucial for our question-answering functionality.</li><li><a href="https://docs.crewai.com/"><strong>crewai</strong></a>: The crewai library is a powerful tool that enables the creation of collaborative AI agents. In our project, we&#39;ll use it to build a team of AI &quot;agents&quot; that work together to generate engaging blog content.</li></ol><blockquote>The blog cover image picture is credit <a href="https://www.theforage.com/blog/careers/what-jobs-will-ai-replace">Forage</a>.</blockquote><p>Let’s dive into the step-by-step process of building our conversational AI-powered blog.</p><h3>Setting up the Environment</h3><ol><li>Ensure you have <a href="https://www.python.org/downloads/">Python</a> 3.10 installed on your system.</li><li>Install the required Python packages: langchain, crewai, bs4, and chromadb.</li></ol><pre>pip install langchain<br>pip install crewai<br>pip install bs4<br>pip install chromadb</pre><p>3. Pull the required Ollama models from the cloud</p><pre>ollama pull gemma:7b<br>ollama pull mistral:7b<br>ollama pull nomic-embed-text</pre><ul><li><a href="https://ollama.com/library/gemma:7b">gemma</a>: Gemma is a family of lightweight, state-of-the-art open models built by Google DeepMind.</li><li><a href="https://ollama.com/library/mistral:7b">mistral</a>: Cost-efficient reasoning for low-latency workloads.</li><li><a href="https://ollama.com/library/nomic-embed-text:latest">nomic-embed-text</a>: A high-performing open embedding model with a large token context window. This model will be used later in the second part of the blog.</li></ul><h3>AI Agents</h3><p>Now, it’s time for the coding part.</p><p>First, we’ll create a file called blog.py and add the following content:</p><pre>from langchain_community.llms import Ollama<br>from crewai import Agent, Task, Crew<br>import sys<br><br>ollama_gemma = Ollama(model=&#39;gemma:7b&#39;)<br>ollama_mistral = Ollama(model=&#39;mistral:7b&#39;)</pre><p>We’ve just imported all the required libraries. Then, we’ve initialized two AI models that we downloaded from Ollama.</p><pre>def write_blog(topic):<br>  # Create Researcher agent<br>  researcher = Agent(<br>      role=&#39;Senior Research Analyst&#39;,<br>      goal=f&quot;Uncover research in {topic}&quot;,<br>      backstory=&quot;&quot;&quot;You work at a leading research company.<br>      Your expertise lies in identifying emerging trends, research and discover.<br>      You have a knack for dissecting complex data and presenting actionable insights.&quot;&quot;&quot;,<br>      verbose=True,<br>      allow_delegation=False,<br>      llm=ollama_gemma<br>  )<br><br>  # Create Writer agent<br>  writer = Agent(<br>      role=&#39;Content Strategist&#39;,<br>      goal=f&quot;Craft compelling content on {topic}&quot;,<br>      backstory=&quot;&quot;&quot;You are a renowned Content Strategist, known for your insightful and engaging articles.<br>      You transform complex concepts into compelling narratives.&quot;&quot;&quot;,<br>      verbose=True,<br>      allow_delegation=False,<br>      llm=ollama_mistral<br>  )<br><br>  # Create tasks for your agents<br>  task1 = Task(<br>    description=f&quot;Conduct a comprehensive analysis of {topic}.&quot;,<br>    expected_output=&quot;Full analysis report in bullet points&quot;,<br>    agent=researcher<br>  )<br><br>  task2 = Task(<br>    description=f&quot;&quot;&quot;Using the insights provided, develop an engaging blog<br>    post that highlights the topic of {topic}.<br>    Your post should be informative yet accessible, catering to any audience, easy to understand.<br>    Make it sound cool, avoid complex words so it doesn&#39;t sound like AI.&quot;&quot;&quot;,<br>    expected_output=&quot;Full blog post of at least 4 paragraphs&quot;,<br>    agent=writer<br>  )<br><br>  # Instantiate your crew with a sequential process<br>  crew = Crew(<br>      agents=[researcher, writer],<br>      tasks=[task1, task2],<br>      verbose=2, # You can set it to 1 or 2 to different logging levels<br>  )<br><br>  # Get your crew to work!<br>  result = crew.kickoff()<br>  return result</pre><p>Alright, let’s dive into this step-by-step and see how we can use AI to streamline the blog post creation process.</p><blockquote>All we need are: 1) Agent to oversee operations, 2) a Task tailored for the Agent’s expertise, 3) to assemble a Crew and delegate tasks accordingly, and 4) to allow the Crew to execute the assigned tasks. That’s all it takes.</blockquote><p>First, we define a function called write_blog that takes a topic parameter. This will be the subject of the blog post we want to generate.</p><p>Inside the function, we create two AI agents: a researcher agent and a writer agent. The researcher agent is tasked with conducting a comprehensive analysis of the given topic, while the writer agent is responsible for crafting an engaging and informative blog post based on the insights provided by the researcher.</p><p>Now that we have our two agents, we define the tasks they’ll be working on. The first task is assigned to the researcher agent, and it involves conducting a comprehensive analysis of the topic and producing a detailed report in bullet point form.</p><p>The second task is assigned to the writer agent. This task requires the agent to use the insights provided by the researcher and develop an engaging, informative, and accessible blog post of at least 4 paragraphs. The key here is to ensure the content is easy to understand, avoids complex jargon, and caters to a wide audience.</p><p>With the agents and tasks defined, we create a Crew object that brings everything together. The Crew object manages the workflow, ensuring the tasks are executed in the correct order (research first, then writing) and providing the necessary coordination between the agents.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*1VRMKn2hgHa4Qk6Pe6MX3g.png" /><figcaption>A Powerful Crew — Credit to <a href="https://twitter.com/OPfandom/status/1410877547538231301">OPFandom</a></figcaption></figure><p>Finally, we call the crew.kickoff() method, which triggers the AI agents to get to work. The result of this process is the completed blog post, which we return from the write_blog function.</p><p>This approach allows us to leverage the strengths of different AI models (the ollama_gemma and ollama_mistral models) to handle the research and writing tasks, respectively. By dividing the work and allowing the agents to focus on their specific strengths, we can streamline the content creation process and produce high-quality blog posts efficiently.</p><blockquote>Absolutely, the concept of “CrewAI” makes sense, drawing parallels between a diverse crew with various expertise and an AI model library offering specialized capabilities. With CrewAI, users can leverage the strengths of different AI models tailored to specific tasks, similar to how a crew with diverse skills can tackle different aspects of a project. It’s a fitting analogy that highlights the versatility and adaptability of AI models to address a wide range of challenges effectively.</blockquote><p>Finally, let’s add a main function to accept the topic from the command line and execute the program.</p><pre>def main():<br>  if len(sys.argv) &lt; 2:<br>    print(&quot;Please provide a topic as an argument.&quot;)<br>    print(&#39;Usage: python blog.py &quot;AI and data science trends in 2024&quot;&#39;)<br>    sys.exit(1)<br><br>  # Get the first command-line argument after the script name<br>  topic = sys.argv[1]<br><br>  # Now you can use &#39;argument&#39; in your script<br>  print(&quot;\n\n#### Topic ####&quot;)<br>  print(topic)<br><br>  if topic == &#39;&#39;:<br>    print(&quot;Topic is empty.&quot;)<br>    sys.exit(1)<br><br>  result = write_blog(topic)<br><br>  print(&quot;\n\n#### Result ####&quot;)<br>  print(result)<br><br>if __name__ == &#39;__main__&#39;:<br>  main()</pre><p>Say, you want to write a blog about “AI and data science trends in 2024”, you open the terminal and write following</p><pre>python blog.py &quot;AI and data science trends in 2024&quot;</pre><p>You might get the output as following</p><pre><br>#### Topic ####<br>AI and data science trends in 2024<br><br> [DEBUG]: == Working Agent: Senior Research Analyst<br> [INFO]: == Starting Task: Conduct a comprehensive analysis of AI and data science trends in 2024.<br><br><br>&gt; Entering new CrewAgentExecutor chain...<br>**Thought:**<br><br>I am well-positioned to provide a comprehensive analysis of AI and data science trends in 2024. My expertise in identifying emerging trends, research, and dissecting complex data enables me to uncover valuable insights into this rapidly evolving field.<br><br>**Final Answer:**<br><br>**AI and Data Science Trends in 2024:**<br><br>* **AI-powered Data Analytics:** AI is revolutionizing data analytics by automating tasks, improving accuracy, and providing actionable insights. Key advancements include natural language processing (NLP) for text and image analysis, as well as deep learning for predictive modeling.<br><br>* **Emerging AI Applications:** AI is permeating various industries, including healthcare, finance, retail, and transportation. Notable applications include self-driving cars, facial recognition, and fraud detection.<br><br>.<br>.<br>.<br><br> [DEBUG]: == Working Agent: Content Strategist<br> [INFO]: == Starting Task: Using the insights provided, develop an engaging blog<br>    post that highlights the topic of AI and data science trends in 2024.<br>    Your post should be informative yet accessible, catering to any audience, easy to understand.<br>    Make it sound cool, avoid complex words so it doesn&#39;t sound like AI.<br><br><br>&gt; Entering new CrewAgentExecutor chain...<br> Thought: With the insights provided, I&#39;m ready to craft an engaging blog post on AI and data science trends in 2024.<br><br>Final Answer:<br><br>**Welcome to the Future:** **AI and Data Science Trends Shaping Our World in 2024**<br><br>Imagine a world where machines learn, adapt, and make decisions just like us. That&#39;s not science fiction anymore; it&#39;s our present-day reality. Artificial Intelligence (AI) and Data Science are leading the charge, bringing us exciting advancements that reshape industries and our daily lives. Let&#39;s explore some trends that will dominate these fields in 2024.<br><br>.<br>.<br>.<br><br><br>#### Result ####<br>**Welcome to the Future:** **AI and Data Science Trends Shaping Our World in 2024**<br><br>Imagine a world where machines learn, adapt, and make decisions just like us. That&#39;s not science fiction anymore; it&#39;s our present-day reality. Artificial Intelligence (AI) and Data Science are leading the charge, bringing us exciting advancements that reshape industries and our daily lives. Let&#39;s explore some trends that will dominate these fields in 2024.<br><br>**Transforming Data with AI:** **Revolutionizing Analytics**<br><br>In the data-driven world we live in today, understanding trends and making informed decisions is crucial. And here comes AI to the rescue! Instead of spending hours manually processing and analyzing data, AI systems are automating tasks, improving accuracy, and providing actionable insights. Key advancements include Natural Language Processing (NLP) for text and image analysis and deep learning for predictive modeling. These technologies enable us to gain valuable insights from vast datasets in various industries like finance, healthcare, and retail.<br><br>**AI Everywhere:** **Emerging Applications in Multiple Sectors**<br><br>From self-driving cars revolutionizing transportation to facial recognition systems enhancing security, AI is permeating various sectors. In healthcare, it&#39;s being used for diagnosis and personalized treatment plans. In finance, AI is powering fraud detection and risk assessments. Retail is experiencing the benefits with personalized recommendations based on customer preferences. The applications of AI are endless!<br><br>**Breaking Down Data Silos:** **Data Democratization**<br><br>Data is no longer locked away in silos; it&#39;s becoming more accessible to everyone thanks to advancements in data visualization tools and platforms. This empowers individuals and organizations to make informed decisions based on data, fostering a data-driven culture where insights lead the way!<br><br>**Protecting Our Data:** **Data Privacy and Security**<br><br>As we embrace these technological advancements, data privacy and security are becoming growing concerns in the wake of increasing data breaches and cyberattacks. Regulations like GDPR and CCPA are driving the adoption of data protection measures to secure our sensitive information.<br><br>.<br>.<br>.<br><br>In conclusion, these trends in AI and data science are shaping our future in remarkable ways. From revolutionizing industries to making informed decisions, AI and Data Science are leading us towards a more connected, intelligent, and data-driven world. Stay tuned for more updates on these exciting trends!<br></pre><p>We can see the output of each agent and how each agent is working together to perform the task for us.</p><h3>Bonus</h3><p>One limitation of AI models is that they only know what they have been trained on. So, if you ask an AI model to perform a task it hasn’t been trained for or inquire about recent news, it’s impossible for the AI to know the answer, and it might provide incorrect information or generate a hallucination.</p><p>In this section, we will address this problem by providing additional contextual information, which could come from various sources such as PDFs, websites, videos, audios, etc. This will enable the AI to answer our questions more effectively. To put it simply, we are going to develop another program where we can query the AI both with and without supplementary assistance.</p><p>Let’s create a file called ask.py and add the following content:</p><pre>from langchain_community.llms import Ollama<br>from langchain_community.document_loaders import WebBaseLoader<br>from langchain.text_splitter import RecursiveCharacterTextSplitter<br>from langchain_community.embeddings import OllamaEmbeddings<br>from langchain_community.vectorstores import Chroma<br>from langchain.chains import RetrievalQA<br>import sys<br><br>ollama = Ollama(model=&quot;mistral:7b&quot;)<br><br>def answer_with_context(question, context_url):<br>    # Now let&#39;s load a document to ask questions against. <br>    loader = WebBaseLoader(context_url)<br>    data = loader.load()<br><br>    # This file is pretty big. Which means the full document won&#39;t fit into the context for the model. So we need to split it up into smaller pieces.<br>    text_splitter=RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=0)<br>    all_splits = text_splitter.split_documents(data)<br><br>    # It&#39;s split up, but we have to find the relevant splits and then submit those to the model. <br>    # We can do this by creating embeddings and storing them in a vector database. <br>    # We can use Ollama directly to instantiate an embedding model. <br>    oembed = OllamaEmbeddings(model=&quot;nomic-embed-text&quot;)<br>    vectorstore = Chroma.from_documents(documents=all_splits, embedding=oembed)<br><br>    # And here is the relevant part of the document to the question.<br>    docs = vectorstore.similarity_search(question)<br>    print(&quot;\n\n#### Context From Document ####&quot;)<br>    print(&quot;url: &quot;, context_url)<br>    print(docs)<br><br>    # The next thing is to send the question and the relevant parts of the docs to the model to see if we can get a good answer. <br>    qachain = RetrievalQA.from_chain_type(ollama, retriever=vectorstore.as_retriever())<br>    output = qachain.invoke({&quot;query&quot;: question})<br>    return output[&#39;result&#39;]<br><br>def answer(question):<br>    output = ollama.invoke(question)<br>    return output<br><br>def main():<br>    if len(sys.argv) &lt; 2:<br>        print(&quot;Please provide a topic as an argument.&quot;)<br>        print(&#39;Usage 1: python ask.py &quot;Who is current President in USA?&quot;&#39;)<br>        print(&#39;Usage 2: python ask.py &quot;Who is current President in USA?&quot; &quot;https://en.wikipedia.org/wiki/President_of_the_United_States&quot;&#39;)<br><br>    # Get the first command-line argument after the script name<br>    question = sys.argv[1]<br><br>    print(&quot;\n\n#### Question ####&quot;)<br>    print(question)<br><br>    # If the user provides a second argument, we will use that as the context URL to find the answer.<br>    context_url = &#39;&#39;<br>    if len(sys.argv) == 3:<br>        context_url = sys.argv[2]<br><br>    if context_url == &#39;&#39;:<br>        result = answer(question)<br>    else:<br>        result = answer_with_context(question, context_url)<br><br>    print(&quot;\n\n#### Result ####&quot;)<br>    print(result)<br><br>if __name__ == &#39;__main__&#39;:<br>    main()</pre><p>We have created two functions: <strong>answer</strong> and <strong>answer_with_context</strong>.</p><p>In the <strong>answer</strong> function, the AI model attempts to provide an answer without any additional assistance.</p><p>In contrast, the <strong>answer_with_context</strong> function operates as follows:</p><ol><li>It retrieves data (text) from the provided URL.</li><li>The retrieved data is converted into vectors using the <strong>nomic-embed-text</strong> model and stored in the <strong>Chroma</strong> vector database.</li><li>Only the portions of the documents relevant to the user’s question are extracted.</li><li>Finally, this information from the vector database is passed to the AI model to generate an answer to the question.</li></ol><p>To run the application, use the following command:</p><pre>&gt; python ask.py &quot;Who is current President in USA?&quot;<br><br><br>#### Question ####<br>Who is current President in USA?<br><br><br>#### Result ####<br> As of my knowledge up to 2021, the current President of the United States is Joe Biden. He assumed office on January 20, 2021.</pre><p>Now with context</p><pre>python3.10 ask.py &quot;Who is current President in USA?&quot; &quot;https://en.wikipedia.org/wiki/President_of_the_United_States&quot;<br><br><br>#### Question ####<br>Who is current President in USA?<br><br><br>#### Context From Document ####<br>url:  https://en.wikipedia.org/wiki/President_of_the_United_States<br>[Document(page_content=&#39;^ &quot;The Presidents of the United States of America&quot;. <br>Enchanted Learning. Retrieved August 2, 2018.\n\n^ <br>&quot;Political Parties of the Presidents&quot;. Presidents USA. <br>Retrieved August 2, 2018.\n\n\nFurther reading&#39;, .....<br>...<br><br>#### Result ####<br> The current President of the United States is Joe Biden.</pre><p>With little bit of help, our AI can answer the question correctly. Here is the link to Github Repo — <a href="https://github.com/yong-asial/local-llm">https://github.com/yong-asial/local-llm</a>.</p><h3>Conclusion</h3><p>In this article, we have learned how to use CrewAI to create multiple AI agents to perform the task for us. And in the bonus part, we demonstrate how we can provide some context to AI to perform a better job. I hope you can find them useful and maybe your homework is to combine these techniques together and create even a better and interesting application.</p><p>Happy Coding.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cfdbcd7eabaa" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-web-tub/let-ais-do-the-jobs-with-crewai-cfdbcd7eabaa">Let AIs do the Jobs with CrewAI</a> was originally published in <a href="https://medium.com/the-web-tub">The Web Tub</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unlock AI Power in Your Hybrid Mobile App: Local Embedding of HuggingFace Model with Transformers.js]]></title>
            <link>https://medium.com/the-web-tub/unlock-ai-power-in-your-hybrid-mobile-app-local-embedding-of-huggingface-model-with-transformers-js-9805a400c924?source=rss-8279bf0635d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/9805a400c924</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[onnx]]></category>
            <category><![CDATA[hugging-face]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[MPyK]]></dc:creator>
            <pubDate>Tue, 05 Mar 2024 09:30:59 GMT</pubDate>
            <atom:updated>2024-03-06T06:08:35.983Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5XpgBhwAIE2CTuBJ-bW65A.png" /><figcaption>Credit to <a href="https://huggingface.co/blog/optimum-onnxruntime-training">https://huggingface.co/blog/optimum-onnxruntime-training</a></figcaption></figure><p>In previous articles, we demonstrated how to utilize HuggingFace models via API endpoint calls in mobile applications. While this method provides a quick and easy way to test out the model, it can be unstable due to the unpredictability of free endpoints. Therefore, in this tutorial, we will introduce an alternative approach: downloading the model from Huggingface and running it locally with Transformers.js.</p><h3>Get Started</h3><p>First, let’s clone this GitHub <a href="https://github.com/yong-asial/local-model-huggingface">repository</a> to your local directory. Then, we’ll delve into the key components and codebase of the project. The application we’re developing is a text classification or sentiment analysis app. Users input a sentence, and the AI assesses whether it’s positive/negative or rates the text on a scale of 1 to 5 stars.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/383/1*UUHVkFEYnAomhZfpmcLbDA.png" /><figcaption>The App — Text Classification</figcaption></figure><h3>The HTML</h3><p>The application we’re constructing is refreshingly straightforward. Let’s start by examining the index.html file.</p><pre>&lt;!DOCTYPE HTML&gt;<br>&lt;html&gt;<br>&lt;head&gt;<br>    &lt;meta charset=&quot;utf-8&quot;&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no&quot;&gt;<br>    &lt;meta http-equiv=&quot;Content-Security-Policy&quot; content=&quot;default-src * data: gap: content: https://ssl.gstatic.com; style-src * &#39;unsafe-inline&#39;; script-src * &#39;unsafe-inline&#39; &#39;unsafe-eval&#39;&quot;&gt;<br>    &lt;script src=&quot;components/loader.js&quot;&gt;&lt;/script&gt;<br>    &lt;link rel=&quot;stylesheet&quot; href=&quot;components/loader.css&quot;&gt;<br>    &lt;link rel=&quot;stylesheet&quot; href=&quot;css/style.css&quot;&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;!-- Loading image --&gt;<br>    &lt;div id=&quot;loading&quot;&gt;<br>        &lt;img src=&quot;loading.gif&quot; alt=&quot;Loading...&quot; width=&quot;250&quot; /&gt;<br>    &lt;/div&gt;<br><br>    &lt;h1&gt;Hugging Face&lt;/h1&gt;<br><br>    &lt;!-- Result section --&gt;<br>    &lt;div id=&quot;result&quot;&gt;<br>        This is result.<br>    &lt;/div&gt;<br><br>    &lt;!-- Query section --&gt;<br>    &lt;label&gt;Query:&lt;/label&gt;<br>    &lt;textarea id=&quot;query&quot; placeholder=&quot;I like Monaca&quot;&gt;I like Monaca&lt;/textarea&gt;<br><br>    &lt;!-- buttons --&gt;<br>    &lt;button id=&quot;btnSentimenLocal&quot;&gt;Text Classification (Local model file)&lt;/button&gt;<br>    &lt;button id=&quot;btnSentimentCache&quot;&gt;Sentiment Analysis&lt;/button&gt;<br><br>    &lt;script src=&quot;main.js&quot; type=&quot;module&quot;&gt;&lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>As you can see, our interface is divided into four sections. Firstly, the loading image is displayed when the model is loading or processing data. Following that, the “result” section showcases the application status and displays results from the model predictions. Moving on, the “query” section allows users to input their text. Finally, we have two buttons: the “Text Classification” button utilizes local model embedding within the application, while the “Sentiment Analysis” button leverages the model from the HuggingFace cloud.</p><h3>The Javascript</h3><p>As you may have noticed in the HTML file above, we also import the JavaScript file main.js, which houses the logic for handling user interactions and executing the AI functionalities. It utilizes the ES6 module syntax (type=&quot;module&quot;). Now, let&#39;s delve deeper into its components.</p><pre>import { pipeline, env } from &#39;https://cdn.jsdelivr.net/npm/@xenova/transformers@2.15.1&#39;;<br><br>// global var<br>let sentimentPipeline = null;<br>let textClassificationPipeline = null;<br>let startTime;<br>const resultEl = document.getElementById(&#39;result&#39;);<br>const loadingImage = document.getElementById(&#39;loading&#39;);<br><br>const updateResult = (html) =&gt; {<br>    resultEl.innerHTML = html;<br>    console.log(html); // debug purpose<br>};<br><br>const start = () =&gt; {<br>    loadingImage.style.display = &#39;block&#39;; // show loading image<br>    updateResult(&#39;Loading ...&#39;);<br>    startTime = performance.now(); // calculate processing time<br>}<br><br>const predict = async (type, pipelineModel, sentence) =&gt; {<br>    if (!sentence) {<br>        loadingImage.style.display = &#39;none&#39;;<br>        alert(&#39;Input some query&#39;);<br>        return;<br>    }<br>    if (!pipelineModel) {<br>        alert(&#39;The model is not loaded.&#39;);<br>        loadingImage.style.display = &#39;none&#39;;<br>        return;<br>    }<br>    updateResult(&#39;Processing ...&#39;);<br>    try {<br>        // process sentence and return result from model pipeline function<br>        const result = await pipelineModel(sentence);<br>        const endTime = performance.now(); // calculate processing time<br>        if (result) {<br>            updateResult(`<br>                &lt;p&gt;${JSON.stringify(result)}&lt;/p&gt;<br>                &lt;p&gt;Time taken: ${((endTime - startTime) / 1000).toFixed(2)} seconds (${type}).&lt;/p&gt;<br>            `);<br>        }<br>    } catch (e) {<br>        updateResult(e.toString());<br>    }<br>    loadingImage.style.display = &#39;none&#39;; // hide loading image<br>};<br><br>const getBrowserCachePipeline = async (useRemote, taskName, modelName) =&gt; {<br>    let piplelineModel;<br>    env.allowRemoteModels = useRemote; // true: use HuggingFace cloud model. false: use downloaded model in browser cache<br>    try {<br>        piplelineModel = await pipeline(<br>            taskName,<br>            modelName<br>        );<br>    } catch (e) {<br>        console.log(e);<br>        piplelineModel = null;<br>    }<br>    return piplelineModel;<br>};<br><br>const useBrowserCache = async (pipelineCache, taskName, modelName) =&gt; {<br>    env.useBrowserCache = true;<br>    if (!pipelineCache) {<br>        updateResult(&#39;Loading model from cache...&#39;);<br>        pipelineCache = await getBrowserCachePipeline(false, taskName, modelName);<br>        if (!pipelineCache) {<br>            updateResult(&#39;Cache not available. Loading remote model...&#39;);<br>            pipelineCache = await getBrowserCachePipeline(true, taskName, modelName);<br>        }<br>        updateResult(&#39;Model is loaded.&#39;);<br>    }<br>    await predict(&#39;browser&#39;, pipelineCache, document.getElementById(&quot;query&quot;).value);<br>    return pipelineCache;<br>};<br><br>const useLocalModel = async (pipelineCache, taskName, modelName) =&gt; {<br>    env.localModelPath = &#39;./models/&#39;;<br>    env.allowRemoteModels = false;<br>    env.allowLocalModels = true;<br>    env.useBrowserCache = false;<br>    if (!pipelineCache) {<br>        updateResult(&#39;Loading model from local...&#39;);<br>        pipelineCache = await pipeline(<br>            taskName,<br>            modelName<br>        );<br>        updateResult(&#39;Model is loaded.&#39;);<br>    }<br>    await predict(&#39;local&#39;, pipelineCache, document.getElementById(&quot;query&quot;).value);<br>    return pipelineCache;<br>};<br><br>const sentimentClassifyLocalModel = async () =&gt; {<br>    start();<br>    // this model doesn&#39;t have onnx model. so we use the converter tool to convert from pytorch model to onnx and upload to www/local folder.<br>    textClassificationPipeline = await useLocalModel(<br>        textClassificationPipeline,<br>        &#39;text-classification&#39;,<br>        &#39;local/nlptown/bert-base-multilingual-uncased-sentiment&#39;<br>    );<br>};<br><br>const sentimentClassify = async () =&gt; {<br>    start();<br>    // this model has onnx model file. so we can use it directly from HuggingFace. It will first download it then cache it.<br>    sentimentPipeline = await useBrowserCache(<br>        sentimentPipeline,<br>        &#39;sentiment-analysis&#39;,<br>        &#39;Xenova/distilbert-base-uncased-finetuned-sst-2-english&#39;<br>    );<br>};<br><br>const main = () =&gt; {<br>    document.getElementById(&quot;btnSentimentCache&quot;).addEventListener(&#39;click&#39;, sentimentClassify, false);<br>    document.getElementById(&quot;btnSentimenLocal&quot;).addEventListener(&#39;click&#39;, sentimentClassifyLocalModel, false);<br>};<br><br><br>main();</pre><p>Transformers.js is designed to mirror Hugging Face’s transformers Python library, providing functionality that allows you to run the same pretrained models using a very similar API. For a comprehensive understanding of Transformers.js, please refer to the full <a href="https://huggingface.co/docs/transformers.js/index">documentation</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*gMAIIngxrlmhW_QrUdSFFA.png" /><figcaption>Transformers vs Transformers</figcaption></figure><p>The only caveat is that Transformers.js currently supports ONNX models, leveraging ONNX Runtime to execute models in browsers. However, we’ve got you covered with a converter tool that can easily convert pretrained PyTorch, TensorFlow, or JAX models to ONNX format. We’ve provided a <a href="https://colab.research.google.com/drive/1v0lmkGTHKdbfOFYDJ1Oz1G7R64ArDmHs?usp=sharing">Google Colab script</a> for your convenience, so simply sign up for a free account, specify the desired model for conversion, and run the script. If everything goes smoothly, you should obtain results similar to the example below. You can then download the folders and upload them to your project directory. For this application, we’ve uploaded them to the “www/models/local” directory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kC8RaWCQHowwRh9X6M9ynw.png" /><figcaption>ONNX Converter</figcaption></figure><h4>Some Explanation</h4><p>First things first, to utilize the Transformers library, we need to import the package into the project.</p><pre>import { pipeline, env } from &#39;https://cdn.jsdelivr.net/npm/@xenova/transformers@2.15.1’;</pre><p>To use the model locally, we need to set up an environment variable (env.localModelPath) specifying the path to load the model from. Additionally, we instruct Transformers to utilize the model locally, rather than remotely or from the browser cache.</p><pre>env.localModelPath = &#39;./models/&#39;;<br>env.allowRemoteModels = false;<br>env.allowLocalModels = true;<br>env.useBrowserCache = false;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*asIgiH_U0BQA4OVqzjN-PQ.png" /><figcaption>The App — Sentiment Analysis</figcaption></figure><p>To utilize the model remotely or from the browser cache, we also need to configure the ‘<strong>env</strong>’ settings. Setting ‘<strong>env.allowRemoteModels</strong>’ to <em>true</em> enables the use of remote models, while setting it to <em>false</em> directs the application to use the model stored in the browser cache (provided ‘<strong>env.useBrowserCache</strong>’ is set to <em>true</em>). When using the browser cache, the model is initially downloaded from the cloud, and subsequent usage relies on the cached version. It’s important to note that for this setup to work, the model uploaded to Hugging Face must include <a href="https://huggingface.co/Xenova/distilbert-base-uncased-finetuned-sst-2-english/tree/main/onnx">ONNX model files</a> in the repository.</p><p>The remaining code is dedicated to displaying the application status, loading image, and other related elements. It is designed to be simple and straightforward in its implementation.</p><h3>Running On Mobile</h3><p>If you want to make it as mobile application, you can sign up a free account with <a href="https://monaca.io/">Monaca</a> and import this <a href="https://monaca.mobi/en/directimport?pid=65dd9c39e78885532946af06">project</a>. You can then run it on both android and iPhone devices in no time.</p><h3>Conclusion</h3><p>In conclusion, this tutorial has provided a comprehensive overview of embedding a Hugging Face AI model into a hybrid mobile application using Transformers.js.</p><p>Furthermore, we addressed the limitations of Transformers.js in supporting ONNX models and provided a solution by offering a converter tool and guiding users through its usage. By following the steps outlined in this tutorial, developers can seamlessly integrate powerful AI capabilities into their hybrid mobile applications, opening up new possibilities for enhancing user experiences and functionality.</p><p>Overall, this tutorial serves as a valuable resource for developers looking to leverage the capabilities of Hugging Face models in their mobile applications, providing clear instructions and insights into the process of local model embedding and usage.</p><p>Happy Coding.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9805a400c924" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-web-tub/unlock-ai-power-in-your-hybrid-mobile-app-local-embedding-of-huggingface-model-with-transformers-js-9805a400c924">Unlock AI Power in Your Hybrid Mobile App: Local Embedding of HuggingFace Model with Transformers.js</a> was originally published in <a href="https://medium.com/the-web-tub">The Web Tub</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an AI mobile application with HugginFace and Stable Diffusion Model]]></title>
            <link>https://medium.com/the-web-tub/building-an-ai-mobile-application-with-react-and-framework7-1b9238aaa8a9?source=rss-8279bf0635d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b9238aaa8a9</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[image-generation]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[mobile-application]]></category>
            <category><![CDATA[stable-diffusion]]></category>
            <dc:creator><![CDATA[MPyK]]></dc:creator>
            <pubDate>Sun, 07 Jan 2024 11:53:48 GMT</pubDate>
            <atom:updated>2024-01-23T08:42:56.157Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DoZhhHPFZKPCk1oPyGG62A.jpeg" /></figure><p>In this tutorial, we will create a React-based mobile app using Framework7 to generate and share AI-generated images on social media platforms. The app allows users to input a query, fetch an image from an AI service, and share it on Facebook or Instagram. We’ll cover topics such as UI components, state management, and social media integration.</p><h3><strong>Get Started</strong></h3><p>First, let’s clone this Github <a href="http://git@github.com:monaca-samples/image-to-sns.git">repo</a> to your local directory and then we will walk through the important part and codebase of the project. Here is the application we are building.</p><h4><strong>Routing/Navigation</strong></h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/da3ba023a6f4365ecc3b79ba525a92d0/href">https://medium.com/media/da3ba023a6f4365ecc3b79ba525a92d0/href</a></iframe><p>It establishes route configurations for a Framework7 application. It defines two routes: one for the home page (/) and another for the history page (/history/). Each route is associated with a React component (HomePage and HistoryPage), facilitating navigation between these pages in the application.</p><h4><strong>Home Page</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jxnpXr8MC-BxGos_cHOW1g.png" /><figcaption>Home Page</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f57023edede5b8adcb1e1664341ee478/href">https://medium.com/media/f57023edede5b8adcb1e1664341ee478/href</a></iframe><p>For the `UI part`, it is structured using Framework7 components. It consists of a Navbar, input field, “Go” button, image display area, and social media sharing buttons. The layout is responsive, and components are styled using utility classes.</p><blockquote>The social media sharing buttons only run on mobile devices.</blockquote><p>The `generatePicture` function fetches an image from an AI service based on the user’s input. It handles loading states, error conditions, and dispatches a Redux action to store the generated image in the array and localstorage to display them later in the History page.</p><p>Here is the `getImageFromAI` function from `src/js/util.js`.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8eb01fa4dd35f57ce24f09d0b9377463/href">https://medium.com/media/8eb01fa4dd35f57ce24f09d0b9377463/href</a></iframe><p>It is simply a fetch api to `huggingface` with the `stable-diffusion-xl-base-1.0` model. The response from the API is extracted as a Blob using the blob() method. A Blob represents binary data, which in this case, contains the generated image. Next, to display on the Image element, we need to convert to Base64 with the `convertToBase64` function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3fbd7c73c28de271f9ddcee0914531f7/href">https://medium.com/media/3fbd7c73c28de271f9ddcee0914531f7/href</a></iframe><p>It takes a Blob of binary data as input and returns a Promise. It uses the FileReader API to read the binary data as a Data URL, which is a Base64-encoded string representation of the data. The Promise resolves with the Base64-encoded data once the reading operation is completed.</p><p>Now let’s look at the `store` object where we manage the “database” for this application.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d838a8bbdde9f0729df3606fa3cd73dd/href">https://medium.com/media/d838a8bbdde9f0729df3606fa3cd73dd/href</a></iframe><p>We define `images` as the property of the `state` for storing all generated images. It read the data (if any) from localstorage via the `readFromLocalStorage` function. The `addImage` is the function to add new image (in which we called from the Home page `store.dispatch(‘addImage’, {…})`) to the state and at the same time saving to localstorage via the `writeToLocalStorage` function.</p><h4><strong>Social Media Sharing Plugin</strong></h4><p>If you are running the application on mobile phone, you can share the generated image to your social media platform — facebook or instagram. This is done with the `shareFacebook` and `shareInstagram` function defined in `src/js/utils.js` file.</p><blockquote>If you are running on browser, it will display an alert message.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/af311c8ffef37290530dd790d1db10e1/href">https://medium.com/media/af311c8ffef37290530dd790d1db10e1/href</a></iframe><p>To use this sharing feature, we need to install `cordova-plugin-x-socialsharing` cordova plugin. The usage is very straightforward as written above.</p><h4><strong>History Page</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GiE2hTF5jWyHmTWDYGSqIQ.png" /><figcaption>History Page</figcaption></figure><p>Finally, let’s look at the History Page. The page display all generated images and if clicked on, will share the image to Instagram account.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1a461a5af1381143f7a5db35f43f6f2f/href">https://medium.com/media/1a461a5af1381143f7a5db35f43f6f2f/href</a></iframe><p>It fetches the array of images from the store, displays them in a list with titles, dates, and clickable thumbnails. The component handles both the case when there are images in the history and when there are none, providing a message in the latter scenario. Clicking on an image triggers a sharing function.</p><h4><strong>Running On Mobile</strong></h4><p>If you want to make it as mobile application, you can sign up a free account with <a href="https://monaca.io/">Monaca</a> and import this <a href="https://monaca.mobi/en/directimport?pid=659a320ee788855973aa27dc">project</a>. You can then run it on both android and iPhone devices in no time.</p><h3><strong>Conclusion</strong></h3><p>In this article, we have learned how to use HugginFace to develop a simple AI-image-generation mobile application. This is just a simple introduction and a small part of what HuggingFace can offer. Please explore it <a href="https://huggingface.co/models">more</a>.</p><p>Happy Coding.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b9238aaa8a9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-web-tub/building-an-ai-mobile-application-with-react-and-framework7-1b9238aaa8a9">Building an AI mobile application with HugginFace and Stable Diffusion Model</a> was originally published in <a href="https://medium.com/the-web-tub">The Web Tub</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Build an Intelligent Chatbot Using OpenAI’s Pre-Trained Models with Javascript]]></title>
            <link>https://medium.com/the-web-tub/how-to-build-an-intelligent-chatbot-using-openais-pre-trained-models-with-javascript-207558b62b2f?source=rss-8279bf0635d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/207558b62b2f</guid>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[chatbots]]></category>
            <dc:creator><![CDATA[MPyK]]></dc:creator>
            <pubDate>Mon, 13 Mar 2023 04:57:31 GMT</pubDate>
            <atom:updated>2023-03-16T05:36:10.437Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1eFm3P8AECntegAsnN16mw.png" /></figure><p>Chatbots are becoming increasingly popular, and they can be used for various purposes, such as customer service, lead generation, and sales. Thanks to advancements in artificial intelligence (AI), chatbots are now more intelligent than ever before, and can carry out more complex tasks. One of the leading companies in the field of AI is <a href="https://openai.com/blog/chatgpt"><strong>OpenAI</strong></a>, which provides state-of-the-art AI tools and models to developers and businesses.</p><blockquote>OpenAI was founded in 2015 by a group of tech luminaries, including Elon Musk, Sam Altman, Greg Brockman, Ilya Sutskever, and John Schulman. The company’s mission is to create safe and beneficial AI that can benefit humanity as a whole. OpenAI has since become a leader in the field of AI, and has developed a wide range of models and tools that can be used to create intelligent applications and systems.</blockquote><p>One of the most impressive models developed by OpenAI is <strong>GPT</strong> (Generative Pre-trained Transformer), a machine learning model that can generate human-like text. GPT has been pre-trained on massive amounts of text data, and can generate coherent and contextually appropriate responses to a wide range of prompts. OpenAI has also released several pre-trained versions of GPT, including GPT-2 and GPT-3, which have been used to create some of the most impressive chatbots to date.</p><p>OpenAI also provides a <a href="https://chat.openai.com/chat">chat service</a>, which allows developers and businesses to integrate chatbots into their websites and applications with ease. The service provides access to pre-trained GPT models, as well as a powerful API that allows for customization and control over the chatbot’s behavior.</p><p>In this tutorial, we’ll be using OpenAI’s pre-trained models, including GPT-3, to create a chatbot web/mobile application. By leveraging the power of OpenAI’s natural language processing capabilities, we can create an intelligent chatbot, i called it <strong>iChatGPT</strong>, that can respond to user input in a way that feels natural and human-like. So let’s get started!</p><h3>Step 1: The HTML</h3><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>&lt;head&gt;<br>    &lt;meta charset=&quot;utf-8&quot;&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no&quot;&gt;<br>    &lt;meta http-equiv=&quot;Content-Security-Policy&quot; content=&quot;default-src * data: gap: content: https://ssl.gstatic.com; style-src * &#39;unsafe-inline&#39;; script-src * &#39;unsafe-inline&#39; &#39;unsafe-eval&#39;&quot;&gt;<br>    &lt;!-- monaca resources --&gt;<br>    &lt;script src=&quot;components/loader.js&quot;&gt;&lt;/script&gt;<br>    &lt;link rel=&quot;stylesheet&quot; href=&quot;components/loader.css&quot;&gt;<br>    &lt;!-- css --&gt;<br>    &lt;link rel=&quot;stylesheet&quot; href=&quot;css/style.css&quot;&gt;<br> &lt;title&gt;iChatGPT&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br> &lt;div class=&quot;container messages&quot;&gt;<br>  &lt;!-- Chat messages will be added here --&gt;<br> &lt;/div&gt;<br><br> &lt;form class=&quot;chat-form&quot; id=&quot;chat-form&quot;&gt;<br>  &lt;input type=&quot;text&quot; class=&quot;chat-input&quot; id=&quot;chat-input&quot; placeholder=&quot;Ask me...&quot;&gt;<br>  &lt;button type=&quot;submit&quot; class=&quot;chat-send&quot; id=&quot;chat-send&quot;&gt;<br>   &lt;img src=&quot;send-icon.png&quot; width=&quot;20px&quot; height=&quot;20px&quot; alt=&quot;Send&quot; id=&quot;send-img&quot;&gt;<br>  &lt;/button&gt;<br>  &lt;div class=&quot;loader&quot;&gt;&lt;/div&gt;<br> &lt;/form&gt;<br><br>    &lt;!-- javascript --&gt;<br>    &lt;script src=&quot;main.js&quot;&gt;&lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>Let’s go over what each part of the code does:</p><ul><li>The div element with a class of container messages will hold the chat messages. The messages from the user and responses from the bot</li><li>The form element with a class of chat-form and an ID of chat-form will be used to submit the user&#39;s chat message. We will later apply css to fix and position it at the bottom of the page.</li><li>The input element with a type of text, a class of chat-input, and an ID of chat-input is where the user will type their chat message.</li><li>The div element with a class of loader will be used to display a loading animation when the chat message is being sent.</li><li>Finally, the script tag includes a JavaScript file called main.js that will contain the code for the chat interface.</li></ul><p>That’s it for the HTML code! Now let’s move on to the CSS code.</p><h3>Step 2: The CSS</h3><pre><br>* {<br>    box-sizing: border-box;<br>    margin: 0;<br>    padding: 0;<br>}<br><br>body {<br>    background-color: #f2f2f2;<br>    font-family: Arial, sans-serif;<br>    font-size: 16px;<br>    line-height: 1.5;<br>    height: 100vh;<br>    display: flex;<br>    flex-direction: column;<br>}<br><br>.container {<br>    flex: 1;<br>    padding: 20px;<br>    padding-bottom: 70px !important;<br>    display: flex;<br>    flex-direction: column;<br>    overflow-y: scroll;<br>    scroll-behavior: smooth;<br>}<br><br>.message {<br>    max-width: 80%;<br>    margin: 10px;<br>    padding: 10px;<br>    border-radius: 5px;<br>    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.3);<br>}<br><br>.user-message {<br>    align-self: flex-end;<br>    background-color: #2D81D8;<br>    color: white;<br>}<br><br>.bot-message {<br>    align-self: flex-start;<br>    background-color: #f2f2f2;<br>}<br><br>.chat-form {<br>    display: flex;<br>    position: fixed;<br>    bottom: 0;<br>    left: 0;<br>    right: 0;<br>    padding: 10px;<br>    background-color: white;<br>    box-shadow: 0 -1px 5px rgba(0, 0, 0, 0.3);<br>    z-index: 1;<br>}<br><br>.chat-input {<br>    flex: 1;<br>    border: none;<br>    border-radius: 5px;<br>    padding: 10px;<br>    margin-right: 10px;<br>    font-size: 16px;<br>}<br><br>.chat-send {<br>    background-color: #2D81D8;<br>    color: white;<br>    border: none;<br>    border-radius: 5px;<br>    padding: 10px 15px;<br>    cursor: pointer;<br>    font-size: 16px;<br>}<br><br>.loader {<br>    display: none;<br>    margin-left: 10px;<br>    margin-top: 10px;<br>    border: 4px solid #f3f3f3;<br>    border-top: 4px solid #2D81D8;<br>    border-radius: 50%;<br>    width: 20px;<br>    height: 20px;<br>    animation: spin 2s linear infinite;<br>}<br><br>@keyframes spin {<br>    0% { transform: rotate(0deg); }<br>    100% { transform: rotate(360deg); }<br>}</pre><p>This is the CSS code for styling the HTML document. It sets some default styles for all elements on the page using the universal selector (*), including box-sizing, margin, and padding.</p><p>The .container class is used to style the div element that contains the chat messages. It sets flex properties to make it stretch to fill the available space, sets padding to create a margin around the messages, and sets overflow-y to scroll so that users can scroll through the messages. The <strong>.message</strong>, .<strong>user-message</strong>, and <strong>.bot-message</strong> classes are used to style the individual chat messages, <strong>with different background colors</strong> for messages sent by the user and messages received from the bot.</p><p>The <strong>.chat-form</strong> class is used to style the form element used to send messages. It is given a <strong>fixed position at the bottom of the page</strong> using the position property, and padding to create some space around the form elements.</p><p>Finally, the <strong>.loader</strong> class is used to style the loading animation that appears when the bot is thinking, using the border, border-radius, width, height, and animation properties. The @keyframes spin rule defines an animation sequence that is used to rotate the .loader element to create a spinning animation. The spin animation is set to run infinitely using the infinite value of the animation-iteration-count property.</p><p>The @keyframes rule is used to define a sequence of CSS styles to be applied to an element over time. In this case, it defines two keyframes - one at 0% and the other at 100%. The transform property is used to rotate the .loader element, starting at 0 degrees and ending at 360 degrees at the end of the animation sequence. This creates a spinning effect.</p><p>When the .loader element is shown, the display property is set to block, which causes it to be displayed. When it is hidden, the display property is set to none, which causes it to be hidden.</p><p>Now, let’s add the magic with javascript.</p><h3>Step 3: The Javascript</h3><pre>// DOM<br>const chatForm = document.querySelector(&#39;#chat-form&#39;);<br>const chatInput = document.querySelector(&#39;#chat-input&#39;);<br>const chatSend = document.querySelector(&#39;#chat-send&#39;);<br>const messageContainer = document.querySelector(&#39;.messages&#39;);<br>const sendImg = document.querySelector(&#39;#send-img&#39;);<br>const loader = document.querySelector(&#39;.loader&#39;);<br><br>// OpenAI API<br>const OPENAI_MODEL = &#39;gpt-3.5-turbo&#39;; // gpt-3.5-turbo, gpt-3.5-turbo-0301<br>const OPENAI_URL = &#39;https://api.openai.com/v1/chat/completions&#39;;<br>// Input Your OpenAI API Key Here. <br>// You can sign up and get API Key from here <br>// https://platform.openai.com/account/api-keys<br>let apiKey = &#39;&#39;;<br>const messages = []; // store previous messages to remember whole conversation<br><br>// Function to add a chat message to the container<br>function addMessage(message, isUser) {<br>    const messageDiv = document.createElement(&#39;div&#39;);<br>    messageDiv.classList.add(&#39;message&#39;);<br>    messageDiv.classList.add(isUser ? &#39;user-message&#39; : &#39;bot-message&#39;);<br>    messageDiv.textContent = message;<br>    messageContainer.appendChild(messageDiv);<br><br>    // Scroll to the bottom of the chat container<br>    messageContainer.scrollTop = messageContainer.scrollHeight;<br>}<br><br><br>// Function to handle user input<br>function handleUserInput(event) {<br>    event.preventDefault();<br>    const message = chatInput.value.trim();<br>    if (message !== &#39;&#39;) {<br>        messages.push({<br>            &#39;role&#39;: &#39;user&#39;,<br>            &#39;content&#39;: message<br>        });<br>        addMessage(message, true);<br>        chatInput.value = &#39;&#39;;<br>        showLoader();<br>        // Other request body from here https://platform.openai.com/docs/api-reference/chat/create<br>        fetch(OPENAI_URL, {<br>            method: &#39;POST&#39;,<br>            headers: {<br>                &#39;Content-Type&#39;: &#39;application/json&#39;,<br>                &#39;Authorization&#39;: &#39;Bearer &#39; + apiKey<br>            },<br>            body: JSON.stringify({ <br>                &#39;model&#39;: OPENAI_MODEL,<br>                &#39;messages&#39;: messages<br>            })<br>        })<br>        .then(response =&gt; response.json())<br>        .then(data =&gt; {<br>            hideLoader();<br>            const responseMessage = data.choices[0].message;<br>            addMessage(responseMessage.content, false);<br>            messages.push(responseMessage);<br>        })<br>        .catch(() =&gt; {<br>            hideLoader();<br>            addMessage(&#39;Oops! Something went wrong. Please try again later.&#39;, false);<br>        });<br>    }<br>}<br><br><br>// Function to show the loader icon<br>function showLoader() {<br>    loader.style.display = &#39;inline-block&#39;;<br>    chatSend.disabled = true;<br>}<br><br>// Function to hide the loader icon<br>function hideLoader() {<br>    loader.style.display = &#39;none&#39;;<br>    chatSend.disabled = false;<br>}<br><br>// Ask user to input his/her API Key<br>function checkAPIKey() {<br>    if (!apiKey) apiKey = prompt(&#39;Please input OpenAI API Key.&#39;);<br>    if (!apiKey) alert(&#39;You have not entered the API Key. The application will not work.&#39;);<br>}<br><br>// Add an event listener to the form<br>chatForm.addEventListener(&#39;submit&#39;, handleUserInput);<br><br>// check<br>checkAPIKey();</pre><ul><li>The first block of code defines variables that represent different elements of the chat interface, such as the chat form, chat input, send button, message container, loader, and send image.</li><li>The next block defines constants for the OpenAI API, including the model name and API endpoint URL. The code also defines a variable for the API key and an array to store previous messages to remember the whole conversation.</li></ul><blockquote>You can get a free API key here at <a href="https://platform.openai.com/account/api-keys">https://platform.openai.com/account/api-keys</a>.</blockquote><ul><li>The addMessage function is defined to add a new message to the message container, either from the user or the bot. The function creates a new message div element, adds the appropriate CSS class based on the sender, and appends the message to the message container. The function also scrolls the message container to the bottom to show the latest messages.</li><li>The handleUserInput function is defined to handle user input when the user sends a message. The function first prevents the default behavior of the form submission. If the input is not empty, the function pushes the message to the messages array, adds the message to the message container with the addMessage function, clears the input field, shows the loader, and sends a request to the OpenAI API to get a response. The request body includes the model name and the previous messages stored in the messages array.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/1*TGHzmjqGxrn6uBBAKO1_KQ.png" /></figure><blockquote>we store all the messages from the users and bots so that model could understand the context and previous conversation. As you can see in the screenshots, we just say — “how about in Japanese?”, “Chinese” and the bot know exactly what to do based on its previous conversation.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/390/1*HuNLz2rSjzWWg-VsZMndwg.png" /></figure><ul><li>If the request is successful, the function hides the loader, retrieves the response message from the API response, adds the message to the message container with the addMessage function, and pushes the response message to the messages array.</li><li>The showLoader and hideLoader functions are defined to show and hide the loader icon, respectively. The functions change the display CSS property of the loader and disable or enable the send button.</li><li>The checkAPIKey function is defined to prompt the user to input their OpenAI API key if it&#39;s not already defined. If the user does not input the API key, the function shows an alert message.</li></ul><p>It is all done now. If you put them together, you would be able to run this on a browser. All the source code is available here <a href="https://github.com/monaca-samples/iChatGPT">https://github.com/monaca-samples/iChatGPT</a>.</p><p>If you want to make it as mobile application, you can sign up a free account with <a href="https://monaca.io/">Monaca</a> and <a href="https://monaca.mobi/en/directimport?pid=640eab89e788856477a02f49">import this project</a>. You can then run it on both android and iphone devices in no time.</p><h3>Conclusion</h3><p>In this article, we have learned how to use OpenAI to develop a simple chatbot web/mobile application. This is just a simple introduction and a small part of what OpenAI can offer. You can read more about the services more <a href="https://platform.openai.com/docs/introduction">here</a>.</p><p>Happy Coding.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=207558b62b2f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-web-tub/how-to-build-an-intelligent-chatbot-using-openais-pre-trained-models-with-javascript-207558b62b2f">How to Build an Intelligent Chatbot Using OpenAI’s Pre-Trained Models with Javascript</a> was originally published in <a href="https://medium.com/the-web-tub">The Web Tub</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ChatGPT: How an AI Language Model Revolutionized Online Conversations]]></title>
            <link>https://sopheaktra-yong.medium.com/chatgpt-how-an-ai-language-model-revolutionized-online-conversations-58d9b4e4576?source=rss-8279bf0635d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/58d9b4e4576</guid>
            <category><![CDATA[gpt]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[chat]]></category>
            <dc:creator><![CDATA[MPyK]]></dc:creator>
            <pubDate>Thu, 16 Feb 2023 12:25:04 GMT</pubDate>
            <atom:updated>2023-02-16T12:25:04.527Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GLrOK-D8sPXvvHAGNakYow.jpeg" /></figure><p>ChatGPT is an artificial intelligence language model developed by OpenAI that has revolutionized the way people interact online. With its ability to understand and respond to natural language input, ChatGPT has become a popular tool for chatbots, customer service, and language learning platforms. In this article, we’ll explore the history of ChatGPT, how it’s built, and provide an example of how it works.</p><h3>History</h3><p>The development of ChatGPT started in 2018, with the release of the first version of GPT-1 (Generative Pre-trained Transformer 1), an AI language model designed to generate natural language text. GPT-1 was soon followed by GPT-2, which was capable of generating more coherent and accurate text. In 2019, OpenAI released a version of GPT-2 that could be fine-tuned for specific tasks, such as text classification or question answering. This paved the way for the development of ChatGPT, which is a variant of GPT-2 that’s been optimized for conversational input.</p><p>GPT, which stands for Generative Pre-trained Transformer, is a type of artificial intelligence (AI) language model that helps computers understand and generate natural language text, like a human being might. It’s a bit like a really smart robot that can talk to people and answer their questions or have a conversation with them.</p><h3>GPT</h3><p>GPT works by analyzing a huge amount of text data that it has been trained on. It learns the patterns and relationships between words, phrases, and sentences in this text data, so that when someone asks it a question or gives it some text input, it can use that knowledge to generate a response that makes sense.</p><p>For example, if you ask GPT “What is the weather like today?” it might look at its database of text and see that people often talk about the weather being sunny or rainy, and then generate a response based on that knowledge. The more text data GPT has access to, the better it can understand and respond to different types of text input.</p><p>There are different versions of GPT that have been developed over time, and each new version is typically more advanced and capable than the previous one. GPT-3, which was released in 2020, is currently one of the most advanced language models available and can do things like generate entire articles or stories based on just a few input sentences.</p><p>Overall, GPT is an exciting technology that has a lot of potential to help people communicate and interact with computers in new and more natural ways.</p><h3>How it’s built</h3><p>ChatGPT is built using a neural network architecture called a transformer, which allows it to understand the context of a conversation and generate appropriate responses. The model is pre-trained on a massive dataset of text from the internet, which enables it to generate natural language responses that are often indistinguishable from those written by a human. Once the model is trained, it can be fine-tuned on specific conversational datasets, allowing it to generate responses that are more relevant and accurate for a particular use case.</p><h3>Example</h3><p>To illustrate how ChatGPT works, let’s imagine a user named Sarah who is chatting with a language learning platform that uses ChatGPT as its chatbot. Sarah types, “Can you help me practice my Spanish?” ChatGPT understands the context of Sarah’s question and generates a response such as, “Of course! I can provide you with practice exercises and help you practice your speaking skills with a native Spanish speaker. What level of proficiency are you currently at?” Sarah replies, “I’m at an intermediate level.” ChatGPT then generates a set of exercises and recommends a tutor who can help Sarah improve her skills.</p><h3>Conclusion</h3><p>ChatGPT is a powerful tool that has transformed the way we interact online. With its ability to generate natural language responses and understand the context of a conversation, it has become an essential component of chatbots, customer service, and language learning platforms. As AI technology continues to evolve, we can expect ChatGPT and other language models to become even more advanced and integrated into our daily lives.</p><p><strong>Disclaimer</strong>: This article was generated by ChatGPT, an artificial intelligence language model developed by OpenAI. While I provided the prompt and guidance, the content of this article was created by ChatGPT.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=58d9b4e4576" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Voice Bot with Alan and Monaca]]></title>
            <link>https://medium.com/the-web-tub/a-voice-bot-with-alan-and-monaca-5846d98c2034?source=rss-8279bf0635d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/5846d98c2034</guid>
            <category><![CDATA[mobile]]></category>
            <category><![CDATA[voices]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[chat]]></category>
            <dc:creator><![CDATA[MPyK]]></dc:creator>
            <pubDate>Tue, 19 Jul 2022 12:15:20 GMT</pubDate>
            <atom:updated>2022-07-20T02:03:35.406Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9bwdfJ2xSXrThX1aw96cug.png" /><figcaption>Image Courtesy of <a href="https://alan.app/">Alan</a></figcaption></figure><p>A voice chatbot is a conversational AI communication tool that can capture, interpret, and analyze vocal input given by the speaker to respond in a similar natural language. Users can interact with a voice AI chatbot with voice commands and receive relevant responses. In this article, we will learn how to create a simple voice chatbot mobile application with the help of <a href="https://alan.app/">Alan</a>.</p><h3>What we are building?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/135/1*WGvlDr4oeH7g4xm3aHE-jg.gif" /><figcaption>Demo</figcaption></figure><p>We are going to build a hybrid mobile application in which users could start a simple daily conversation with the bot. The application will recognize the user’s voice and convert it into “intent” and the AI will pick the response and reply in “voice”. To build this application from scratch, we will need a lot of machine learning components to understand user voices for different spoken languages and accents, natural language processing, and speech-to-text/text-to-speech. It would at least take months, if not years, to collect data and train the models. Fortunately, we have a service, Alan, that does these things for us. It provides the production-ready AI solution for us which we can just plug and play in our application.</p><h3>What is Alan?</h3><p>Alan is an advanced Voice AI Platform that allows you to add a voice interface to your app without overhead.</p><blockquote>Alan is an end-to-end conversational AI platform to build robust and reliable in-app voice assistants and chatbots. There is no need to create spoken language models, train the speech recognition software, deploy and host voice components — the Alan AI backend does the bulk of work. With Alan, a voice experience for your app can be built and developed by a single developer, rather than a team of Machine Learning and Dev Ops experts.</blockquote><h4>Creating Voice Bot</h4><p>First and foremost, we have to create an Alan project, a voice assistant to handle the user’s vocal input. Please <a href="https://studio.alan.app/register">sign up </a>for a free account with Alan before continuing.</p><p>You can create the project with <a href="https://studio.alan.app/projects">Alan Studio</a>.</p><blockquote>Alan Studio lets you go beyond the capabilities of touch and type interfaces and voice enable any complex workflow or function in your app. Voice scripts are written in JavaScript, which makes them highly customizable and flexible.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YHMYd7EJeLYro7PAMQwpMw.png" /><figcaption>“Hello World” Alan</figcaption></figure><p>In this article, we will be creating a simple chit-chat application. Thus, we choose the “Hello World” project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pqv9X0RWiKUHF3SICEnZfQ.png" /><figcaption>Script</figcaption></figure><p>What we have in the above picture is the script that Alan used to handle user’s vocal conversation. Let’s look at the snippet of the script.</p><pre>intent(<br>    &#39;Who\&#39;s there&#39;,<br>    &#39;What\&#39;s your name&#39;,<br>    p =&gt; {<br>        p.play(<br>            &#39;My name is Alan.&#39;,<br>            &#39;It\&#39;s Alan.&#39;,<br>        );<br>    },<br>);</pre><p>When the user speaks Who&#39;s there or What&#39;s your name or something similar such as Your name , name , How can i call you , etc. The Alan AI converts those vocal to texts and tries to match defined <strong>intent</strong> and response back, in this case, it will say My name is Alan. or It&#39;s Alan. back to the user.</p><p>Let’s look at another snippet.</p><pre>const intentPatterns = [<br>    &#39;What is your favorite food&#39;,<br>    &#39;What food do you like&#39;,<br>];</pre><pre>intent(intentPatterns, p =&gt; {<br>    p.play(&#39;CPU time, yammy!&#39;);<br>});</pre><p>Similarly, this section is prepared to answer when the user asks what Alan likes to eat.</p><p>As you can see here, the script is straightforward. Please explore it and adjust it to your preference. You could also add new scripts or import from the provided templates to make your application smarter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nJ7ouZr6YxNwXruANpESGA.png" /><figcaption>Other Scripts</figcaption></figure><h4>Integrations</h4><p>After you are satisfied with the scripts and settings, it’s time to integrate into your mobile application. To do that, click on theIntegrations button at the top and copy SDK to insert into the application code later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rebubbQydWbtWHPtwgITQg.png" /><figcaption>Integration</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ESFgrdbnMDqrTxIzUeS_lA.png" /><figcaption>Copy SDK Key</figcaption></figure><h3>Coding Time</h3><p>The application we are creating is based on <a href="https://github.com/monaca-templates/framework7-v6-vue-blank">Framework7-Vue template</a>. To start off, we need to install the Alan SDK plugin to the project. Therefore, please add <strong>“</strong><a href="http://twitter.com/alan"><strong>@alan</strong></a><strong>-ai/cordova-plugin-alan-voice”</strong> to the <strong>package.json</strong> file as follows.</p><pre>{<br>    &quot;name&quot;: &quot;voice-chat&quot;,<br>    ...</pre><pre>    &quot;dependencies&quot;: {<br>        ...<br>        &quot;<a href="http://twitter.com/alan">@alan</a>-ai/cordova-plugin-alan-voice&quot;: &quot;^2.7.0&quot;,<br>    },<br>    &quot;cordova&quot;: {<br>        &quot;plugins&quot;: {<br>            ...<br>            &quot;<a href="http://twitter.com/alan">@alan</a>-ai/cordova-plugin-alan-voice&quot;: {}<br>        }<br>    }<br>}</pre><p>Next, delete all the code from “src/pages/home.vue” and replace it with the following code to create the message template/component provided by <a href="https://framework7.io/vue/messages#examples">Framework 7</a>. The code is simple. It displays the interactive messages between the user and Alan bot. Once we add a new message to the “messagesData” variable, the message will be displayed on the screen. It will display as it from the user if the “message.type” is “sent” or null and display as it from the Alan bot if the “message.type” is “received”.</p><pre>&lt;template&gt;<br>&lt;f7-page&gt;<br>  &lt;f7-navbar title=&quot;Your Companion Voice Chat&quot; /&gt;</pre><pre>&lt;f7-messages&gt;<br>    &lt;f7-messages-title&gt;Press the Alan icon and start talking&lt;/f7-messages-title&gt;<br>    &lt;f7-message<br>      v-for=&quot;(message, index) in messagesData&quot;<br>      :key=&quot;index&quot;<br>      :type=&quot;message.type&quot;<br>      :name=&quot;message.name&quot;<br>      :avatar=&quot;message.avatar&quot;<br>      :first=&quot;isFirstMessage(message, index)&quot;<br>      :last=&quot;isLastMessage(message, index)&quot;<br>      :tail=&quot;isTailMessage(message, index)&quot;<br>    &gt;<br>      &lt;template #text&gt;<br>        &lt;!-- eslint-disable-next-line --&gt;<br>        &lt;span v-if=&quot;message.text&quot; v-html=&quot;message.text&quot;&gt;&lt;/span&gt;<br>      &lt;/template&gt;<br>    &lt;/f7-message&gt;<br>  &lt;/f7-messages&gt;<br>&lt;/f7-page&gt;<br>&lt;/template&gt;</pre><p>Next, let’s add the <strong>script</strong> tag to the file.</p><pre>&lt;script&gt;<br>import { f7ready } from &#39;framework7-vue&#39;;</pre><pre>export default {<br>  data() {<br>    return {<br>      messagesData: [],<br>      people: {<br>          name: &#39;Alan&#39;,<br>          avatar: &#39;<a href="https://avatars.githubusercontent.com/u/54960780?s=200&amp;v=4&#39;">https://avatars.githubusercontent.com/u/54960780?s=200&amp;v=4&#39;</a>,<br>      },<br>    };<br>  },<br>  mounted() {<br>    f7ready(() =&gt; {<br>      const self = this;<br>      document.addEventListener(&#39;deviceready&#39;, self.deviceReady, false);<br>    });<br>  },<br>  methods: {<br>    deviceReady() {<br>      const self = this;<br>      // Please input your ALAN API KEY for better customization<br>      const API_KEY = &#39;1ee6a74d9cccea77faceb579449bc5142e956eca572e1d8b807a3e2338fdd0dc/stage&#39;; // This is the free API Key provided by ALAN<br>      cordova.exec(<br>          self.alanData,<br>          self.alanDataError,<br>          &#39;alanVoice&#39;,<br>          &#39;addButton&#39;,<br>          [API_KEY]<br>      );<br>    },<br>    alanData(response) {<br>      const self = this;<br>      if (<br>        response.type === &#39;onEvent&#39; &amp;&amp;<br>        response.data &amp;&amp; <br>        response.data.text<br>      ) {<br>        if ( response.data.final &amp;&amp; response.data.name === &#39;recognized&#39;) {<br>          self.sendMessage(response.data.text);<br>        } else if (response.data.ctx &amp;&amp; response.data.ctx.success) {<br>          self.receiveMessage(response.data.text);<br>        }<br>      }<br>    },<br>    alanDataError(error) {<br>      alert(&#39;There are some error. Please try again&#39;);<br>      console.log(error);<br>    },<br>    sendMessage(text) {<br>      const self = this;<br>      const messagesToSend = [];<br>      messagesToSend.push({<br>        text,<br>      });<br>      self.messagesData.push(...messagesToSend);<br>    },<br>    receiveMessage(answer) {<br>      const self = this;<br>      const person = self.people;<br>      self.messagesData.push({<br>        text: answer,<br>        type: &#39;received&#39;,<br>        name: person.name,<br>        avatar: person.avatar,<br>      });<br>    }<br>  },<br>};<br>&lt;/script&gt;</pre><h4>Explanation</h4><p>In the “data()” section, we created “messagesData” to store messages and “people” to store the icon for Alan bot when replying the message.</p><pre>data() {<br>    return {<br>      messagesData: [],<br>      people: {<br>          name: &#39;Alan&#39;,<br>          avatar: &#39;<a href="https://avatars.githubusercontent.com/u/54960780?s=200&amp;v=4&#39;">https://avatars.githubusercontent.com/u/54960780?s=200&amp;v=4&#39;</a>,<br>      },<br>    };<br>  },</pre><p>In the “mounted()” section, we invoke “deviceReady” function when the application/device is ready — running on a mobile phone and everything is loaded properly.</p><pre>deviceReady() {<br>      const self = this;<br>      // Please input your ALAN API KEY for better customization<br>      const API_KEY = &#39;&lt;INSERT_YOUR_ALAN_API_KEY_HERE&gt;&#39;;<br>      cordova.exec(<br>          self.alanData,<br>          self.alanDataError,<br>          &#39;alanVoice&#39;,<br>          &#39;addButton&#39;,<br>          [API_KEY]<br>      );<br>    },</pre><p>This is where we insert Alan button to the application. It is plain simple. If the button is added successfully, it will invoke “alanData” otherwise it will call “alanDataError”.</p><pre>alanData(response) {<br>      const self = this;<br>      if (<br>        response.type === &#39;onEvent&#39; &amp;&amp;<br>        response.data &amp;&amp; <br>        response.data.text<br>      ) {<br>        if (response.data.final &amp;&amp; response.data.name === &#39;recognized&#39;) {<br>          self.sendMessage(response.data.text);<br>        } else if (response.data.ctx &amp;&amp; response.data.ctx.success) {<br>          self.receiveMessage(response.data.text);<br>        }<br>      }<br>    },</pre><p>In this snippet, we filter the “response” whether the result is when Alan detected the user’s vocal or detected the answer received from the server. In this Alan SDK version, as of this writing, it is the message from the user when the “response.data.final” is true and it is the answer from the AI when the “response.data.ctx.success” is true. Thus we invoke functions “sendMessage” and “recieveMessage” respectively.</p><blockquote>To debug it, you can write “console.log(response)” in the function to see the value when we are communicating with Alan server.</blockquote><pre>sendMessage(text) {<br>      const self = this;<br>      const messagesToSend = [];<br>      messagesToSend.push({<br>        text,<br>      });<br>      self.messagesData.push(...messagesToSend);<br>    },</pre><p>The difference is the “receiveMessage” set the “type” to “recieved” as well as sets “name” and “avatar” to show Alan bot icon.</p><pre>receiveMessage(answer) {<br>      const self = this;<br>      const person = self.people;<br>      self.messagesData.push({<br>        text: answer,<br>        type: &#39;received&#39;,<br>        name: person.name,<br>        avatar: person.avatar,<br>      });<br>    }</pre><p>All the source code can be found <a href="https://github.com/monaca-samples/voice-chat-alan">here</a>.</p><p>To run the application, you have to build application with Cordova/Monaca. Please refer to this document to build the <a href="https://en.docs.monaca.io/products_guide/debugger/installation/debugger_ios#building-a-custom-monaca-debugger">application</a>.</p><blockquote>The application is not working properly on Android devices.</blockquote><h3>Conclusion</h3><p>In this article, we have learned how to use Alan to develop a simple voice chat mobile application. This is just a simple introduction and a small part of what the service can offer. You can read more about the tools <a href="https://alan.app/docs/">here</a>.</p><p>Happy Coding.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5846d98c2034" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-web-tub/a-voice-bot-with-alan-and-monaca-5846d98c2034">A Voice Bot with Alan and Monaca</a> was originally published in <a href="https://medium.com/the-web-tub">The Web Tub</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create Text Recognition Mobile Application with Google Cloud Vision]]></title>
            <link>https://medium.com/the-web-tub/ocr-with-javascript-e7639099fba?source=rss-8279bf0635d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/e7639099fba</guid>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[cloud-vision]]></category>
            <category><![CDATA[google]]></category>
            <category><![CDATA[ocr]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[MPyK]]></dc:creator>
            <pubDate>Thu, 20 Jan 2022 03:00:41 GMT</pubDate>
            <atom:updated>2022-01-21T06:08:31.651Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*fTODzGu-cOuUjwjEllvWVQ.png" /><figcaption>Image Courtesy of <a href="https://www.ricoh.co.jp/service/cloud-ocr/column/ocr/">RICOH</a></figcaption></figure><p>Optical Character Recognition (OCR) is a widespread technology to recognize text inside images. It is used to convert images containing text (typed, handwritten, or printed) into machine-readable text data. In this article, we are going to create a simple OCR application with Google Cloud Version API.</p><blockquote>Text Recognition can automate tedious data entry for credit cards, receipts, and business cards. With the Cloud-based API, you can also extract text from pictures of documents, which you can use to increase accessibility or translate documents. Apps can even keep track of real-world objects, such as by reading the numbers on trains.</blockquote><h3><strong>What are we building?</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZW6phpvGv4mxdnFMKjaOxQ.png" /><figcaption>Our OCR App!</figcaption></figure><p>Here, it is what we are going to build. It takes a picture with a mobile phone camera or pc webcam, displays it as the first picture, then draws bounding boxes around detected text in the second picture, and finally outputs all the text at the bottom.</p><h3>Get Cloud Vision API Key</h3><p>To extract text information from an image, in this article, we are using <a href="https://cloud.google.com/vision">Cloud Vision API</a> provided by Google. First, you will need to <a href="https://console.cloud.google.com/projectselector2/home/dashboard?_ga=2.114804551.1184164042.1642573565-1721050475.1598326128&amp;_gac=1.89892457.1642575566.CjwKCAiA55mPBhBOEiwANmzoQhkt-RJ1I3r62RoDuETqvdtPRaWwtW5K4jDVJfan43vO0MKcqUJ5gBoCPwcQAvD_BwE">create a project</a> in Google Cloud, then <a href="https://cloud.google.com/billing/docs/how-to/modify-project#confirm_billing_is_enabled_on_a_project">enable billing</a>, <a href="https://console.cloud.google.com/flows/enableapi?apiid=vision.googleapis.com&amp;_ga=2.12377204.1184164042.1642573565-1721050475.1598326128&amp;_gac=1.91406952.1642575566.CjwKCAiA55mPBhBOEiwANmzoQhkt-RJ1I3r62RoDuETqvdtPRaWwtW5K4jDVJfan43vO0MKcqUJ5gBoCPwcQAvD_BwE">enable Cloud Vision API</a>, and finally <a href="https://cloud.google.com/docs/authentication/api-keys">create an API key</a> to access the Cloud Vision API.</p><blockquote>The Cloud Vision API recognizes text in <a href="https://cloud.google.com/vision/docs/languages#supported-langs">100+ different languages</a> and can be tested freely with the first <a href="https://firebase.google.com/pricing">1000 requests</a>. it is built for both recognizing sparse text in images (such as photos of business cards) and recognizing densely-spaced text in pictures of scanned documents.</blockquote><p>If you get it right, you would have something like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l_brZWkqubo2IlqDDMpbEA.png" /><figcaption>API Key</figcaption></figure><p>Copy the API Key `AIza…41Y` to use later in the application.</p><h3>Let’s Build the App</h3><p>Similar to my <a href="https://medium.com/the-web-tub/create-your-first-machine-learning-mobile-application-853176e4eaa1">previous blog</a>, we will be using Vue 3 and Framework 7 to build the app. We are suggesting cloning this <a href="https://github.com/yong-asial/ocr">Github repository</a> and we will start explaining the main pieces of the application.</p><p>First is the application layout.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5f38e15c0901cedf8fcb01115a0e2205/href">https://medium.com/media/5f38e15c0901cedf8fcb01115a0e2205/href</a></iframe><p>The application’s body is divided into 3 rows (<em>from line 7 to line 29</em>). In the first row, there are 3 <strong>div</strong> elements. The <strong>canvas</strong> element, <em>on line 16</em>, is always shown. It is used to draw bounding boxes of all detected texts from the captured image. The <strong>video</strong> element, <em>on line 10</em>, is shown only on a non-mobile platform. It is used to fit live video from the PC’s webcam. If the platform is mobile, we will display the <strong>image</strong> element,<em> on line 13</em>, to render the image from the phone’s camera. The 2nd and 3rd rows are pretty much intuitive.</p><p>Next, let’s check out the “script” part.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/88bac6f6355ebe4b3f6104c9fadc4c50/href">https://medium.com/media/88bac6f6355ebe4b3f6104c9fadc4c50/href</a></iframe><p>On <em>line 3</em>, we import <a href="https://www.npmjs.com/package/axios">axios</a> package to handle HTTP requests. Thus, please install the package if you are not cloning the Github repo or you can use browser-based <a href="https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch">Fetch API</a> but then you have to manage the data, request, response a little bit more.</p><p>Next, we have declared variables related to Google Cloud Vision API from <em>lines 14 to 29</em>. Input your API key created earlier on <em>line 14</em>. We then have the API endpoint on the next line (<em>line 15</em>) for text recognition concatenating with the API key. Finally, we have the constant variable REQUEST_OPTION as the input data and option for HTTP requests. It accepts the image as in <a href="https://developer.mozilla.org/en-US/docs/Glossary/Base64">base64</a> encoding (on <em>line 20</em>). we will later assign image value as base64 encoding to this property.</p><blockquote>Base64 encoding schemes are commonly used when there is a need to encode binary data that needs to be stored and transferred over media that are designed to deal with ASCII. This is to ensure that the data remain intact without modification during transport.</blockquote><p>On <em>line 24</em>, we assign TEXT_DETECTION to the type property. TEXT_DETECTION detects and <strong>extracts text from any image</strong>. For example, a photograph might contain a street sign or traffic sign. The JSON includes the entire extracted string, as well as individual words, and their bounding boxes. The other option is DOCUMENT_TEXT_DETECTION . It also extracts text from an image, but the response is <strong>optimized for dense text and documents</strong>. The JSON includes page, block, paragraph, word, and break information.</p><p>Moving on to onMounted lifecycle hook, the startUserMedia is called if the platform is non-mobile and it supports UserMedia web API. Otherwise, on a mobile platform, we listen to the load event of the image element and call ocr function when the image is completed loaded followed by the imageLoaded flag. It is the flag to skip calling the ocr function when the image is first loaded from assigning static file — “static/icons/favicon.png”.</p><p>Here, is the startUserMedia function. On <em>line 12</em>, we hook the web cam’s stream to the <strong>video</strong> element.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3408a594c1141f6b53b44a7caea93f75/href">https://medium.com/media/3408a594c1141f6b53b44a7caea93f75/href</a></iframe><p>and here is the ocr function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c68826c9447d4d03a2713b05807d632c/href">https://medium.com/media/c68826c9447d4d03a2713b05807d632c/href</a></iframe><p>In the ocr function, we first draw anything from the passing argument <strong>image</strong> to the canvas on <em>line 3</em>. It could be from <strong>video</strong> element or <strong>image</strong> element from PC’s webcam or phone’s camera respectively. Then, the canvas is converted to base64 encoding format for passing as a parameter to recognize function. The recognize function is just a simple function calling Cloud Vision API and if any detected found, it invokes drawBoundingBoxes function to draw bounding boxes on all detected texts.</p><p>Now, let’s see how we can draw the result on the canvas. First, here is the result (<em>line 13</em>) returned from the API. The result returned as an array. The first record contains all detected texts. As you can see in the description property, it has all the texts separated by \n. From the second record onward, it stores all individual detected texts and their corresponding bounding boxes boundingPoly.vertices.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/73d022ef2650d33901e724007695fb01/href">https://medium.com/media/73d022ef2650d33901e724007695fb01/href</a></iframe><p>To draw the boxes on canvas can be done with the following two functions. The actual drawing part is from <em>line 19 to line 22</em> in which we draw lines from each vertex to another vertex to form the polygon shape.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f6cfdc5f3da3bd628d0fcd0149b4881d/href">https://medium.com/media/f6cfdc5f3da3bd628d0fcd0149b4881d/href</a></iframe><p>Finally, the scan function. If it is on the mobile function, we use getPicture method of the <a href="https://cordova.apache.org/docs/en/10.x/reference/cordova-plugin-camera/">Cordova Camera plugin</a>. On the success callback function, we assign the value to the <strong>image</strong> element and set the imageLoaded flag to true. When the <strong>image</strong> is fully loaded it will call the ocr function as we listened to the load event in the onMounted hook. Otherwise, on a non-mobile platform, we will invoke ocr function directly.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ad1c9da1fa3a1725baa8c1d849317be6/href">https://medium.com/media/ad1c9da1fa3a1725baa8c1d849317be6/href</a></iframe><h4>Run on mobile device</h4><p>If you would like to run this application on your phone device, please sign up for an account with <a href="https://monaca.io/">Monaca</a> and follow this <a href="https://en.docs.monaca.io/tutorials/monaca_cli/building_app">guideline</a> on how to build an android or iOS application.</p><blockquote><em>What is Monaca?</em></blockquote><blockquote><em>Cross-platform hybrid mobile app development platform and tools in the cloud</em></blockquote><p>All the source code can be found here — <a href="https://github.com/yong-asial/ocr">https://github.com/yong-asial/ocr</a></p><h3>Conclusion</h3><p>In this article, we have learned how to use <strong>Google Cloud Vision API </strong>to extract text information from an image. The image is scanned from the PC’s webcam by using <strong>UserMedia</strong> web API and from the phone’s camera by using <strong>the Cordova Camera</strong> plugin.</p><p>happy Coding.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e7639099fba" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-web-tub/ocr-with-javascript-e7639099fba">Create Text Recognition Mobile Application with Google Cloud Vision</a> was originally published in <a href="https://medium.com/the-web-tub">The Web Tub</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>