Build a Handwriting Analyzer Web App from Scratch with the Claude 3.5 Sonnet API

claude 3.5. sonnet streamlit Jul 01, 2024
 


With the recent advancements in AI, Claude 3.5 Sonnet's advanced vision capabilities open up a world of exciting possibilities for creating innovative applications. In this post, we'll build a web app using Streamlit and the Claude 3.5 Sonnet API, allowing you to upload handwriting samples and receive personality insights in seconds.


Understanding the Basics

Handwriting analysis is like reading someone's personality through their pen strokes. By examining the unique characteristics of handwriting, we can infer various traits about a person.

With Claude 3.5 Sonnet, we can harness AI to create a powerful tool for this purpose.

Streamlit will help us build a user-friendly interface where users can upload their handwriting images and get detailed analyses. Let’s break it down!


First Steps with the API

First up, let’s get our feet wet with the Anthropic API. We’ll start with a simple "Hi" message to demonstrate how to set up the API and get a response. Before we dive into the code, you’ll need to obtain an API key from the Anthropic website. Once you have your API key, you can export it as an environment variable to keep your credentials secure.

Here’s how you can get started:

  1. Obtain an API Key: Visit the Anthropic website and sign up or log in to your account. Navigate to the API key section in your dashboard and create a new API key. Copy this key for later use.

  2. Export the API Key as an Environment Variable:

    On macOS/Linux:
    export ANTHROPIC_API_KEY="your_api_key_here"

    On Windows:
    set ANTHROPIC_API_KEY="your_api_key_here"

Now, let’s set up a basic Python script to communicate with the Anthropic API. 

import anthropic

client = anthropic.Anthropic()

message = client.messages.create(
    model="claude-3-5-sonnet-2024-06-20",
    max_tokens=1000,
    messages=[
        {
            "role": "user",
            "content": [
                {
                    "type": "text",
                    "text": "Hi"
                }
            ]
        }
    ]
)

print(message.content)

And there you go! This snippet shows how easy it is to send a message and get a response. But we’re just getting warmed up.

 

Analyzing the Handwriting

Now, let’s kick it up a notch. How about analyzing an image? Say, a picture of an ant. Yes, you heard that right! Here’s how we fetch the image, convert it to base64, and send it off for analysis.

import anthropic
import base64
import httpx

client = anthropic.Anthropic()

image_url = "https://upload.wikimedia.org/wikipedia/commons/a/a7/Camponotus_flavomarginatus_ant.jpg"
image_data = base64.b64encode(httpx.get(image_url).content).decode("utf-8")

message = client.messages.create(
    model="claude-3-5-sonnet-20240620",
    max_tokens=1000,
    messages=[
        {
            "role": "user",
            "content": [
                {
                    "type": "image",
                    "source": {
                        "type": "base64",
                        "media_type": "image/jpeg",
                        "data": image_data
                    }
                },
                {
                    "type": "text",
                    "text": "Describe the image"
                }
            ]
        }
    ]
)

print(message.content)

 Voila! We’ve just analyzed an image using AI. How cool is that? But we're aiming higher—we want to decode the secrets of handwriting. 


Adding Streamlit UI

Let's take this project to the next level by building a sleek web UI. This interface will allow users to upload a local file and initiate the analysis with the click of a button.

Using Streamlit, we set up a simple web app where users can upload an image of handwriting. The uploaded image is displayed on the page, and a button triggers the analysis process.

When the button is clicked, the app converts the image to a base64 string, sends it to the Claude API for analysis, and displays the resulting insights directly on the web page.

import anthropic
import base64
import httpx
import streamlit as st
from PIL import Image
from io import BytesIO

client = anthropic.Anthropic()

def analyze_handwriting(image):

  buffered = BytesIO()
  image.save(buffered, format="PNG")
  image_data = base64.b64encode(buffered.getvalue()).decode()

  message = client.messages.create(
      model="claude-3-5-sonnet-20240620",
      max_tokens=1000,
      messages=[
          {
              "role": "user", 
              "content": [
                  {
                      "type": "image", 
                      "source": {
                          "type": "base64",
                          "media_type": "image/png", 
                          "data": image_data
                      }
                  },
                  {
                      "type": "text",
                      "text": """
                        Please analyze this handwriting or signature. 
                        Describe the characteristics you observe and what they might indicate about the writer.
                        Include aspects like pressure, slant, size, spacing, and any other notable features.
                      """
                  }
              ]
          }
      ]
  )

  return message.content[0].text

st.title("🖋️ Handwriting Analyzer")

uploaded_file = st.file_uploader("Choose an image of handwriting or a signature", type=["png", "jpg", "jpeg"])

if uploaded_file is not None:
    image = Image.open(uploaded_file)
    st.image(image, caption="Uploaded Image", use_column_width=True)

    if st.button("Analyze Handwriting"):
      with st.spinner("Analyzing..."):
        analysis = analyze_handwriting(image)
        st.subheader("Analysis Results:")
        st.write(analysis)

 

Conclusion

And there you have it—a fully functional handwriting analysis tool powered by Claude 3.5 Sonnet and Streamlit. With just a few lines of code, we’ve built an application that not only accepts user-uploaded images but also provides detailed personality insights based on handwriting characteristics.

Imagine the possibilities: from personal curiosity to professional applications in psychology, security, and more. This tool showcases the incredible potential of combining AI with user-friendly web frameworks.

Learn To Build Real-world AI

Unlock 100+ AI Videos & Source Code Now