Runoob Tutorial ArchiveEnglish

AI Multimodal

AI Multimodal

AI can not only speak but also see images, hear sounds, and understand videos—master multimodal tools and technologies.

For a long time, AI was unimodal.

But the real world is multimodal—when we read a book, we see illustrations; when we watch a movie, there are visuals and sound; and when we communicate with people, we observe facial expressions and tone.

Multimodal AI is AI that can simultaneously understand and generate multiple types of content, which is like giving AI eyes, ears, and a mouth, allowing it to interact with the world in a more human-like way.

A practical example: if you give AI a photo of a shopping receipt, it can recognize the text on it (OCR), understand what items were purchased, help you organize it into a table, and even read it to you via voice. This is a typical multimodal task.


What is Multimodal AI?

First, let's clarify a few basic concepts.

Unimodal vs Multimodal

Modality refers to the form in which information is presented.

Text, images, audio, and video are all different modalities.

Type Description Typical Products
Single-modality AI Can only process one modality Early GPT-3 (text only), Stable Diffusion (image only)
Multimodal AI Can process multiple modalities simultaneously GPT-4o, Claude 3, Gemini

The core breakthrough of multimodal AI is: it can convert information from different modalities into a single language for understanding.

For example, when seeing a picture of a "cat," it can convert the image into a vector (a set of numbers); it can also convert the word "cat" into a vector. These two vectors are close in mathematical space because they represent the same concept.

The core challenges of multimodality

Multimodality sounds simple, but it is actually very difficult to implement.


Image Understanding (Vision)

Image understanding means letting AI understand pictures—describing content, recognizing text, analyzing charts, and finding details.

Most mainstream large models now support image input.

There are usually two ways to use it:

Models Image input methods Supported image formats
GPT URL, Base64, direct upload JPG, PNG, WEBP, GIF
Claude Base64, direct upload JPG, PNG, WEBP, GIF
Gemini Direct upload, Google Drive JPG, PNG, WEBP

Common visual tasks include:

Practical application: Call the GPT-4o Vision API using Python

Let's look at a complete example—analyzing an image using the API.

Example

============================================

File: runoob_vision_demo.py

Function: Analyze an image using the GPT-4o Vision API

============================================

import

base64

import

requests

import

os

Configure API key (please replace with your actual key)

Get address: https://platform.openai.com/api-keys

OPENAI_API_KEY

=

"sk-your-api-key-here"

OPENAI_API_URL

=

"https://api.openai.com/v1/chat/completions"

def

encode_image_to_base64

(

image_path:

str

)

str

:

   

"""
Encodes a local image file into a Base64 string
This is the transmission format required by the API
"""

   

with

open

(

image_path

,

"rb"

)

as

image_file:

       

Read the binary file content and Base64 encode it

base64_data

=

base64

.

b64encode

(

image_file.

read

(

)

)

.

decode

(

"utf-8"

)

       

return

base64_data

def

analyze_image_with_gpt4o

(

    image_path:

str

,

    prompt:

str

=

"Please describe the content of this image in detail"

,

    model:

str

=

"gpt-4o"

)

str

:

   

"""
Analyze images using the GPT-4o Vision API

Parameter description:
image_path: Local image file path (e.g., "runoob_test.jpg")
prompt: The question you want to ask or the task you want the AI to perform
model: The name of the model used (default is gpt-4o)

Returns:
The text of the AI's analysis result
"""

   

Step 1: Encode the image to Base64

base64_image

=

encode_image_to_base64

(

image_path

)

   

Step 2: Construct the request header

headers

=

{

       

"Content-Type"

:

"application/json"

,

       

"Authorization"

: f

"Bearer {OPENAI_API_KEY}"

   

}

   

Step 3: Construct the request body

   

Note: Image content is passed through the image_url field, formatted as "data:image/jpeg;base64,..."

payload

=

{

       

"model"

: model

,

       

"messages"

:

[

           

{

               

"role"

:

"user"

,

               

"content"

:

[

                   

The first part is the text prompt

                   

{

"type"

:

"text"

,

"text"

: prompt

}

,

                   

The second part is images

                   

{

                       

"type"

:

"image_url"

,

                       

"image_url"

:

{

                           

"url"

: f

"data:image/jpeg;base64,{base64_image}"

                       

}

                   

}

               

]

           

}

       

]

,

       

"max_tokens"

:

1000

 

Control the output length to prevent excessive costs

   

}

   

Step 4: Send API request

   

print

(

f

"Analyzing image: {image_path} ..."

)

response

=

requests.

post

(

OPENAI_API_URL

,

headers

=

headers

,

json

=

payload

)

   

Step 5: Process response

   

if

response.

status_code

==

200

:

        result

=

response.

json

(

)

       

Extract the AI's answer

answer

=

result

[

"choices"

]

[

0

]

[

"message"

]

[

"content"

]

       

return

answer

   

else

:

       

Print detailed information when an error occurs

error_msg

=

f

"Request failed: {response.status_code} - {response.text}"

       

print

(

error_msg

)

       

return

error_msg

def

extract_text_from_image

(

image_path:

str

)

str

:

   

"""
Specifically for OCR: extract text from images
"""

prompt

=

"""
Please extract all text content from this image.
Requirements:
1. Accurately restore the text without omissions
2. Maintain the original paragraphs and format
3. If there is a table, please output it in table format
4. If there is no text in the image, please state so
This is an OCR test for the RUNOOB tutorial.
"""

   

return

analyze_image_with_gpt4o

(

image_path

,

prompt

)

def

analyze_chart

(

image_path:

str

)

str

:

   

"""
Specifically for chart analysis
"""

prompt

=

"""
Please analyze this chart.
Please answer the following questions:
1. What type of chart is this (bar chart, line chart, pie chart, etc.)?
2. What is the title of the chart and the meaning of the axes?
3. What is the main information conveyed by the chart?
4. Are there any notable trends or anomalies?
This is a chart analysis test from the RUNOOB tutorial.
"""

   

return

analyze_image_with_gpt4o

(

image_path

,

prompt

)

============================================

Main program: Demonstrates different visual analysis tasks

============================================

if

name

==

"main"

:

   

Assume we have a test image (you need to prepare a real image)

   

It can be: product photos, screenshots, document photos, charts, etc.

test_image

=

"runoob_test_image.jpg"

   

Check if the image exists

   

if

not

os

.

path

.

exists

(

test_image

)

:

       

print

(

f

"Hint: Please prepare an image named {test_image} in the current directory"

)

       

print

(

"Or modify the image path in the code"

)

   

else

:

       

Task 1: General Image Description

       

print

(

"\n"

"="

50

)

       

print

(

"Task 1: Image Description"

)

       

print

(

"="

50

)

result1

=

analyze_image_with_gpt4o

(

test_image

,

           

"Please describe this image in detail, including the main subject, background, colors, composition, etc."

       

)

       

print

(

result1

)

       

Task 2: OCR Text Extraction

       

print

(

"\n"

"="

50

)

       

print

(

"Task 2: OCR Text Extraction"

)

       

print

(

"="

50

)

result2

=

extract_text_from_image

(

test_image

)

       

print

(

result2

)

       

Task 3: Chart Analysis (if the image is a chart)

       

print

(

"\n"

"="

50

)

       

print

(

"Task 3: Chart Analysis"

)

       

print

(

"="

50

)

result3

=

analyze_chart

(

test_image

)

       

print

(

result3

)

       

print

(

"\n"

"="

50

)

       

print

(

"RUNOOB Tutorial Demonstration Complete!"

)

       

print

(

"="

50

)

Before running this program, you need to:

Cost notice: GPT-4o Vision is billed based on image size. A 1024x1024 image costs approximately $0.00765. Smaller images are cheaper. It is recommended to use low-resolution images for debugging and use high-definition images for production.


Text-to-Image

Text-to-Image is about having the AI generate images based on text descriptions, which is another very mature multimodal application field.

Introduction to Diffusion Model Principles

Today's text-to-image tools basically use Diffusion Model technology.

A simple understanding of its working principle:

This process usually requires 20-50 steps, so generating an image takes a few seconds.

Advanced usage tips for Midjourney

Midjourney is one of the most popular text-to-image tools currently, used via Discord.

A high-quality prompt usually includes these elements:

Parameters Description Example
--ar Set aspect ratio --ar 16:9 (video), --ar 3:4 (mobile)
--v Specify model version --v 6.0 (latest version)
--s Stylization strength (0-1000) --s 750 (strong artistic feel)
--q Rendering quality (0.25-2) --q 2 (higher quality, slower)
--iw Reference image weight --iw 1.5 (more like the reference image)

Local deployment of Stable Diffusion

If you want complete control, you can run Stable Diffusion locally:https://github.com/compvis/stable-diffusion.

The most commonly used tool is the Automatic1111 WebUI.

The steps are roughly as follows:

The advantages of local deployment are: generation is free, no content restrictions, you can fine-tune styles with LoRA, and you can precisely control composition with ControlNet.

The disadvantages are: it requires a graphics card with at least 6GB of VRAM, and the setup is somewhat complicated.

Practical application: calling the DALL·E 3 API to generate images

If you want a simple API method to generate images, DALL·E 3 is a good choice.

Example

============================================

File: runoob_dalle3_demo.py

Function: generating images using the DALL·E 3 API

============================================

import

requests

import

os

from

datetime

import

datetime

Configure API key (please replace with your actual key)

OPENAI_API_KEY

=

"sk-your-api-key-here"

DALLE3_API_URL

=

"https://api.openai.com/v1/images/generations"

def

generate_image_with_dalle3

(

    prompt:

str

,

    size:

str

=

"1024x1024"

,

    quality:

str

=

"standard"

,

    style:

str

=

"vivid"

,

    save_dir:

str

=

"runoob_generated_images"

)

dict

:

   

"""
Use DALL·E 3 API to generate images

Parameter description:
prompt: Text description, the more detailed the better
size: Image size
Optional: 1024x1024, 1024x1792 (portrait), 1792x1024 (landscape)
quality: Image quality
Optional: standard, hd (high definition, more expensive)
style: Style
Optional: vivid (vivid, more artistic), natural (natural, more realistic)
save_dir: Image save directory

Returns:
A dictionary containing image URLs and save paths
"""

   

Step 1: Prepare request headers

headers

=

{

       

"Content-Type"

:

"application/json"

,

       

"Authorization"

"Authorization"

: f

   

}

   

Step 2: Prepare the request body

payload

=

{

       

"model"

:

"dall-e-3"

,

       

"prompt"

: prompt

,

       

"n"

:

1

,

 

DALL·E 3 can only generate 1 image at a time

       

"size"

: size

,

       

"quality"

: quality

,

       

"style"

: style

   

}

   

Step 3: Send request

   

print

(

f

"Generating image, prompt: {prompt[:50]}..."

)

    response

=

requests.

post

(

DALLE3_API_URL

,

headers

=

headers

,

json

=

payload

)

   

Step 4: Process response

   

if

response.

status_code

==

200

:

        result

=

response.

json

(

)

image_url

=

result

[

"data"

]

[

0

]

[

"url"

]

revised_prompt

=

result

[

"data"

]

[

0

]

.

get

(

"revised_prompt"

,

prompt

)

       

print

(

f

"DALL·E 3 automatically optimized prompt: {revised_prompt}"

)

       

Step 5: Download and save the image

       

if

not

os

.

path

.

exists

(

save_dir

)

:

           

os

.

makedirs

(

save_dir

)

       

Generate filename using timestamp

timestamp

=

datetime

.

now

(

)

.

strftime

(

"%Y%m%d_%H%M%S"

)

filename

=

f

"runoob_dalle3_{timestamp}.png"

filepath

=

os

.

path

.

join

(

save_dir

,

filename

)

       

Download image

image_response

=

requests.

get

(

image_url

)

       

if

image_response.

status_code

==

200

:

           

with

open

(

filepath

,

"wb"

)

as

f:

f.

write

(

image_response.

content

)

           

print

(

f

"Image saved to: {filepath}"

)

       

return

{

           

"image_url"

: image_url

,

           

"filepath"

: filepath

,

           

"revised_prompt"

: revised_prompt

       

}

   

else

:

error_msg

=

f

"Request failed: {response.status_code} - {response.text}"

       

print

(

error_msg

)

       

return

{

"error"

: error_msg

}

def

generate_runoob_logo_demo

(

)

:

   

"""Demo: Generate a RUNOOB style logo"""

    prompt

=

"""
A cute and friendly robot mascot for the RUNOOB tutorial website.
Blue and green color scheme, modern flat design, white background.
The robot looks helpful and intelligent, with big friendly eyes.
Simple, clean, suitable for a tech education brand.
"""

   

Chinese prompts are also supported; DALL·E 3 supports multiple languages.

prompt

=

"""
Design a cute and friendly robot mascot for the RUNOOB tutorial website.
Blue-green tones, modern flat design, white background.
The robot should look helpful and intelligent, with big friendly eyes.
Simple and clean, suitable for a tech education brand.
"""

   

return

generate_image_with_dalle3

(

prompt

=

prompt

,

size

=

"1024x1024"

,

quality

=

"hd"

,

style

=

"vivid"

   

)

def

generate_book_cover_demo

(

)

:

   

"""Demonstration: Generate book cover"""

prompt

=

"""
Book cover design for "AI Tutorial for Beginners".
Modern minimalist style, deep blue and purple gradient background.
The title text is elegant and readable.
Subtle tech elements: floating geometric shapes, faint circuit patterns.
Professional, trustworthy, suitable for a programming book.
"""

   

return

generate_image_with_dalle3

(

prompt

=

prompt

,

size

=

"1024x1792"

,

 

Portrait

quality

=

"hd"

,

style

=

"natural"

   

)

def

generate_banner_demo

(

)

:

   

"""Demonstration: Generate banner advertisement image"""

prompt

=

"""
Web banner design for a coding tutorial website (RUNOOB).
16:9 wide format. Modern gradient background from teal to blue.
Clean layout with space for text.
Abstract tech elements: floating code snippets, subtle grid lines.
Professional and inviting.
"""

   

return

generate_image_with_dalle3

(

prompt

=

prompt

,

size

=

"1792x1024"

,

 

Horizontal

quality

=

"standard"

,

style

=

"vivid"

   

)

============================================

Main program: Demonstrates different generation tasks

============================================

if

name

==

"main"

:

   

print

(

"="

60

)

   

print

(

"RUNOOB DALL·E 3 Image Generation Demo"

)

   

print

(

"="

60

)

   

Task 1: Generate Logo

   

print

(

"\n[Task 1] Generating Logo ..."

)

result1

=

generate_runoob_logo_demo

(

)

   

Task 2: Generate book cover

   

print

(

"\n[Task 2] Generating book cover ..."

)

result2

=

generate_book_cover_demo

(

)

   

Task 3: Generate banner

   

print

(

"\n[Task 3] Generating banner ..."

)

result3

=

generate_banner_demo

(

)

   

print

(

"\n"

"="

60

)

   

print

(

"All tasks completed! Check the runoob_generated_images directory"

)

   

print

(

"="

60

)

DALL·E 3 features: strong understanding, no distorted hands or faces, and good text generation results.

However, it also has limitations: it can only generate 1 image at a time, style control is not precise, and it cannot be fine-tuned like Stable Diffusion.

Copyright notice: The current consensus is that the prompt writer has the right to use AI-generated images, but not the copyright (because the copyright office requires human creation). When used for commercial purposes, it is recommended to check the tool's terms of use.


Video AI

Video AI is divided into two categories: video generation and video understanding.

Compared to images, video is technically more difficult—because video is a combination of "time + space," requiring each frame to be coherent and the motion to be natural.

Comparison of AI Video Generation Tools

2024 is the first year of AI video, and many companies have launched video generation products.

Tool Provider Features Typical Duration
Sora OpenAI Industry-leading in visual detail and spatial scene understanding, with realistic physical logic, not yet fully open to public beta Up to 60 seconds
Runway Gen-4 Runway All-in-one creative platform, integrating text/image-to-video, AI post-production editing, motion brush, and VFX effects, the preferred choice for professional creators overseas 10–20 seconds
Kling (Keling AI) Kuaishou Excellent Chinese prompt adaptation, smooth character movements, stable characters across shots, high cost-performance in China, supports multi-segment narrative splicing 5–30 seconds, maximum 2 minutes per segment
Pika Pika Labs Extremely strong expressive power for anime and film illustration styles, consistent character appearance, supports video style redrawing and frame interpolation 5–10 seconds
Veo Google Cinematic lighting and camera work, stable long-take narrative, natural physical rendering, not yet publicly released Over 60 seconds
Jimeng AI (Seedance) ByteDance Deep integration with Jianying/Douyin ecosystem, precise Chinese semantics, audio-visual lip-sync, supports automatic script storyboarding 5–15 seconds, multiple segments spliced into a film
Tongyi Wanxiang Video Alibaba Damouyuan Open-source foundation model, stable multi-agent interaction, supports screen text generation, and can be deployed for local inference 2–15 seconds
Hailuo AI MiniMax Xiyu Lightweight and fast generation, suitable for turning posters into dynamic short videos and social media flash materials, with outstanding anime style expression 4–10 seconds
Luma Dream Machine Luma AI Top physical dynamics simulation, realistic effects like water, fire, cloth, and explosions, cinematic camera movements 5–12 seconds
Zhiying Tencent Leans towards AI editing + digital human videos, massive short video templates, one-stop subtitle, voiceover, and green screen, low barrier to commercial use Unlimited duration, AI-generated clips of 5–15 seconds
Haiyi AI Haiyi Technology Supports 4K/60fps high frame rate output, multi-image linked video generation, and a complete film production workbench with ample limited-time free quotas. Maximum length of 30 seconds per segment.

AI video is still in the early stages:

Video understanding and summarization

Besides generating videos, AI can also understand videos.

Common tasks in video understanding:

The technical approach is usually: frame sampling the video (e.g., sampling 1 frame per second), then using a vision model to look at frame by frame, and finally integrating the information.

Future Trends

The development direction of video AI is very clear:


Audio and Speech AI

Audio AI mainly includes: Speech-to-Text (ASR), Text-to-Speech (TTS), and music generation.

This is a relatively mature field.

Speech-to-Text (Whisper API)

Whisper is an open-source speech recognition model from OpenAI with excellent performance, supporting 99 languages.

Example

============================================

File: runoob_whisper_demo.py

Function: Transcribe speech using Whisper API

============================================

import

requests

import

os

Configure API key

OPENAI_API_KEY

=

"sk-your-api-key-here"

WHISPER_API_URL

=

"https://api.openai.com/v1/audio/transcriptions"

def

transcribe_audio_with_whisper

(

audio_path:

str

,

    language:

str

=

"zh"

,

 

zh=Chinese, en=English, leave blank for auto-detection

prompt:

str

=

""

,

   

Optional: Provide some terminology hints to improve accuracy

temperature:

float

=

0.0

)

dict

:

   

"""
Use Whisper API to transcribe audio files

Parameter description:
audio_path: Path to the audio file (supports mp3, wav, m4a, etc.)
language: Language code (optional, auto-detect if not specified)
Common codes: zh (Chinese), en (English), ja (Japanese)
prompt: Prompt (optional, write potential technical terms or names here)
temperature: Sampling temperature (0.0 is most certain, 1.0 is more diverse)

Returns:
A dictionary containing the transcribed text
"""

   

Step 1: Check if the file exists

   

if

not

os

.

path

.

exists

(

audio_path

)

:

       

return

{

"error"

: f

"File not found: {audio_path}"

}

   

Step 2: Prepare request headers

headers

=

{

       

"Authorization"

: f

"Bearer {OPENAI_API_KEY}"

   

}

   

Step 3: Prepare the request body (Note: audio must use multipart/form-data format)

files

=

{

       

"file"

:

open

(

audio_path

,

"rb"

)

   

}

data

=

{

       

"model"

:

"whisper-1"

,

       

"temperature"

: temperature

   

}

   

if

language:

data

[

"language"

]

=

language

   

if

prompt:

data

[

"prompt"

]

=

prompt

   

Step 4: Send request

   

print

(

f

"Transcribing audio: {audio_path} ..."

)

response

=

requests.

post

(

WHISPER_API_URL

,

headers

=

headers

,

files

=

files

,

data

=

data

)

   

Step 5: Close files

files

[

"file"

]

.

close

(

)

   

Step 6: Process response

   

if

response.

status_code

==

200

:

result

=

response.

json

(

)

text

=

result

[

"text"

]

       

print

(

f

"Transcription complete, total {len(text)} characters"

)

       

return

{

           

"text"

: text

,

           

"language"

: language

       

}

   

else

:

error_msg

=

f

"Request failed: {response.status_code} - {response.text}"

       

print

(

error_msg

)

       

return

{

"error"

: error_msg

}

def

transcribe_with_timestamps

(

audio_path:

str

)

dict

:

   

"""
Transcription with timestamps (using verbose_json format)
"""

headers

=

{

       

"Authorization"

: f

"Bearer {OPENAI_API_KEY}"

   

}

files

=

{

"file"

:

open

(

audio_path

,

"rb"

)

}

data

=

{

       

"model"

:

"whisper-1"

,

       

"response_format"

:

"verbose_json"

,

 

Returns detailed information, including timestamps

       

"timestamp_granularities"

:

[

"segment"

,

"word"

]

 

Supports segment-level and word-level timestamps

   

}

response

=

requests.

post

(

WHISPER_API_URL

,

headers

=

headers

,

files

=

files

,

data

=

data

)

files

[

"file"

]

.

close

(

)

   

if

response.

status_code

==

200

:

        result

=

response.

json

(

)

       

return

result

   

else

:

       

return

{

"error"

: response.

text

}

def

translate_audio_to_english

(

audio_path:

str

)

dict

:

   

"""
Translate audio from any language into English text
"""

headers

=

{

       

"Authorization"

: f

"Bearer {OPENAI_API_KEY}"

   

}

files

=

{

"file"

:

open

(

audio_path

,

"rb"

)

}

data

=

{

       

"model"

:

"whisper-1"

,

       

"task"

:

"translate"

 

Special specification: translation task

   

}

response

=

requests.

post

(

"https://api.openai.com/v1/audio/translations"

,

headers

=

headers

,

files

=

files

,

data

=

data

)

files

[

"file"

]

.

close

(

)

   

if

response.

status_code

==

200

:

       

return

response.

json

(

)

   

else

:

       

return

{

"error"

: response.

text

}

def

runoob_meeting_minutes_demo

(

audio_path:

str

)

str

:

   

"""
Practical application: Generate meeting minutes
Step 1: Transcribe audio with Whisper
Step 2: Organize into minutes using GPT-4o
"""

   

First, transcribe

   

print

(

"Step one: Transcribe the meeting recording..."

)

transcribe_result

=

transcribe_audio_with_whisper

(

audio_path

,

language

=

"zh"

,

prompt

=

"This is a meeting of the RUNOOB technical team to discuss product development, progress, technical solutions, etc."

   

)

   

if

"error"

in

transcribe_result:

       

return

transcribe_result

[

"error"

]

transcript

=

transcribe_result

[

"text"

]

   

Reorganize (simplified here, in actual projects you can call the GPT-4o API)

   

print

(

"Step two: Organize meeting minutes..."

)

   

For demonstration, it directly returns the transcribed text

   

In a real project, you can send the transcript to GPT-4o to have it organize

   

return

transcript

============================================

Main program

============================================

if

name

==

"main"

:

   

Prepare a test audio file

test_audio

=

"runoob_test_audio.mp3"

   

if

not

os

.

path

.

exists

(

test_audio

)

:

       

print

(

f

"Hint: Please prepare an audio file named {test_audio}"

)

       

print

(

"Or record a voice message on your phone and save it as mp3 format"

)

   

else

:

       

Task 1: Simple Transcription

       

print

(

"\n"

"="

50

)

       

print

(

"Task 1: Simple Transcription"

)

       

print

(

"="

50

)

result1

=

transcribe_audio_with_whisper

(

test_audio

,

language

=

"zh"

)

       

if

"text"

in

result1:

           

print

(

"Transcription result:"

)

           

print

(

result1

[

"text"

]

)

       

Task 2: Transcription with timestamp

       

print

(

"\n"

"="

50

)

       

print

(

"Task 2: Transcription with timestamp"

)

       

print

(

"="

50

)

result2

=

transcribe_with_timestamps

(

test_audio

)

       

if

"segments"

in

result2:

           

print

(

"Paragraph information:"

)

           

for

seg

in

result2

[

"segments"

]

[

:

3

]

:

Only print the first 3 segments

start

=

round

(

seg

[

"start"

]

,

2

)

end

=

round

(

seg

[

"end"

]

,

2

)

text

=

seg

[

"text"

]

               

print

(

f

"[{start}-{end}] {text}"

)

       

print

(

"\n"

"="

50

)

       

print

(

"RUNOOB Whisper demo completed!"

)

       

print

(

"="

50

)

Whisper's advantages are: good multilingual support, tolerant of accents, and automatic punctuation.

Typical application scenarios: meeting recording transcription, video subtitle generation, podcast transcripts, voice diaries.

Text-to-Speech (TTS)

Text-to-Speech means having the AI "read" the text.

OpenAI also provides a TTS API that supports various voice styles.

Other TTS tools: ElevenLabs (most human-like), Azure TTS (enterprise-grade), Edge TTS (free), Coqui (open-source).

Music Generation (Suno, Udio)

Music generation has also made breakthroughs.

Suno and Udio are two representative products—you input lyrics and style descriptions, and they can generate a complete song with vocals and accompaniment.

Capability boundaries:


Introduction to multimodal model architecture

Understanding some principles can help you use the tools better.

CLIP: The cornerstone of image-text alignment

CLIP (Contrastive Language-Image Pre-training) is a model published by OpenAI in 2021.

Its idea is simple: look at images and text simultaneously and learn to correspond them.

During training, provide the model with a batch of image-description pairs to teach it:

The significance of CLIP is: it proved that "cross-modal understanding" is feasible.

Later models like Stable Diffusion and GPT-4o were inspired by CLIP.

LLaVA: Open-source multimodal LLM

LLaVA (Large Language and Vision Assistant) is an open-source multimodal model.

Its architecture is very clear:

Training is done in two steps:

LLaVA is a good starting point for learning multimodal technology - the code is open source, the architecture is clear, and the performance is good.


Practical: Building an Image Analysis Tool

We will integrate the previous knowledge to create a practical image analysis tool.

Example

============================================

File: runoob_image_analyzer.py

Function: A complete multimodal image analysis tool

============================================

import

base64

import

requests

import

os

import

json

from

datetime

import

datetime

from

typing

import

Optional

,

Dict

,

Any

class

RunoobImageAnalyzer:

   

"""
RUNOOB Image Analyzer—a wrapped multimodal utility class
"""

   

def

init

(

self

,

api_key:

str

,

base_url:

str

=

"https://api.openai.com/v1"

)

:

       

"""
Initialize the analyzer

Parameters:
api_key: OpenAI API key
base_url: API address (proxy configurable)
"""

       

self

.

api_key

=

api_key

       

self

.

base_url

=

base_url

       

self

.

headers

=

{

           

"Content-Type"

:

"application/json"

,

           

"Authorization"

: f

"Bearer {api_key}"

       

}

   

def

_encode_image

(

self

,

image_path:

str

)

str

:

       

"Encode the image as Base64"

       

with

open

(

image_path

,

"rb"

)

as

f:

           

return

base64

.

b64encode

(

f.

read

(

)

)

.

decode

(

"utf-8"

)

   

def

_call_vision_api

(

       

self

,

image_path:

str

,

prompt:

str

,

model:

str

=

"gpt-4o"

,

max_tokens:

int

=

2000

   

)

Optional

[

str

]

:

       

Internal method: call vision API

base64_image

=

self

._encode_image

(

image_path

)

payload

=

{

           

"model"

: model

,

           

"messages"

:

[

               

{

                   

"role"

:

"user"

,

                   

"content"

:

[

                       

{

"type"

:

"text"

,

"text"

: prompt

}

,

                       

{

                           

"type"

:

"image_url"

,

                           

"image_url"

:

{

"url"

: f

"data:image/jpeg;base64,{base64_image}"

}

                       

}

                   

]

               

}

           

]

,

           

"max_tokens"

: max_tokens

       

}

url

=

f

"{self.base_url}/chat/completions"

response

=

requests.

post

(

url

,

headers

=

self

.

headers

,

json

=

payload

)

       

if

response.

status_code

==

200

:

           

return

response.

json

(

)

[

"choices"

]

[

0

]

[

"message"

]

[

"content"

]

       

else

:

           

print

(

f

"API Error: {response.status_code} - {response.text}"

)

           

return

None

   

def

describe

(

self

,

image_path:

str

)

Optional

[

str

]

:

       

"""Detailed description of the image content"""

prompt

=

"""
Please describe this image in detail, including:
1. Main content (what people/objects are there)
2. Background environment
3. Colors and lighting
4. Overall atmosphere
Answer in Chinese with a clear structure.
"""

       

return

self

._call_vision_api

(

image_path

,

prompt

)

   

def

extract_text

(

self

,

image_path:

str

)

Optional

[

str

]

:

       

"""Extract all text from the image (OCR)"""

prompt

=

"""
Please extract all text content from this image.
Requirements:
1. Accurately reproduce, do not omit
2. Maintain the original paragraph structure
3. If it is a table, please output in Markdown table format
4. If there is no text, please clearly state "No recognizable text in the image"
"""

       

return

self

._call_vision_api

(

image_path

,

prompt

)

   

def

analyze_ui

(

self

,

image_path:

str

)

Optional

[

str

]

:

       

"""Analyze UI design mockups (screenshots)"""

        prompt

=

"""
Please analyze this UI design draft:
1. What type of interface is this (APP, webpage, mini-program, etc.)?
2. What are the main functional modules of the interface?
3. What is the design style (color scheme, layout, font)?
4. What can be improved?
Please answer in Chinese, listing points.
"""

       

return

self

._call_vision_api

(

image_path

,

prompt

)

   

def

analyze_product

(

self

,

image_path:

str

)

Optional

[

str

]

:

       

"Analyze the product image and generate e-commerce copy"

prompt

=

"""
Please analyze this product image and generate a piece of e-commerce copy.
The copy should include:
1. Product name and type
2. Appearance features (color, material, design)
3. A catchy short tagline (30-50 characters)
Answer in Chinese with a friendly and positive tone.
"""

       

return

self

._call_vision_api

(

image_path

,

prompt

)

   

def

classify

(

self

,

image_path:

str

,

categories:

list

=

None

)

Optional

[

str

]

:

       

"""Classify the image"""

       

if

categories

is

None

:

categories

=

[

               

"Character Photo"

,

"Scenery Photo"

,

"Food Photo"

,

"Product Photos"

,

               

"Design Drafts/Screenshots"

,

"Documents/Spreadsheets"

,

"Charts/Data Visualization"

,

"Other"

           

]

cat_list

=

","

.

join

(

categories

)

prompt

=

f

"""
Please determine which category this image belongs to.
Available categories: {cat_list}
Please return only the name of the most matching category, no other text.
"""

       

return

self

._call_vision_api

(

image_path

,

prompt

)

   

def

full_analysis

(

self

,

image_path:

str

,

output_dir:

str

=

"runoob_analysis"

)

Dict

[

str

,

Any

]

:

       

"""
Complete analysis: generate a detailed analysis report

Return a dictionary containing all analysis results
"""

       

print

(

f

"Starting image analysis: {image_path}"

)

       

First classify

       

print

(

"[1/5] Categorizing..."

)

category

=

self

.

classify

(

image_path

)

or

"Unknown"

       

Description

       

print

(

"[2/5] In description..."

)

description

=

self

.

describe

(

image_path

)

or

""

       

Extract text

       

print

(

"[3/5] OCR in progress..."

)

text

=

self

.

extract_text

(

image_path

)

or

""

       

Perform specialized analysis by category

       

print

(

"[4/5] Performing specialized analysis..."

)

special_analysis

=

""

       

if

"Design"

in

category

or

"Screenshot"

in

category:

special_analysis

=

self

.

analyze_ui

(

image_path

)

or

""

       

elif

"Product"

in

category

or

"Item"

in

category:

special_analysis

=

self

.

analyze_product

(

image_path

)

or

""

       

Save report

       

print

(

"[5/5] Generating report..."

)

       

if

not

os

.

path

.

exists

(

output_dir

)

:

           

os

.

makedirs

(

output_dir

)

        timestamp

=

datetime

.

now

(

)

.

strftime

(

"%Y%m%d_%H%M%S"

)

report

=

{

           

"image_file"

:

os

.

path

.

basename

(

image_path

)

,

           

"analysis_time"

:

datetime

.

now

(

)

.

isoformat

(

)

,

           

"category"

: category

,

           

"description"

: description

,

           

"extracted_text"

: text

,

           

"special_analysis"

: special_analysis

       

}

       

Save JSON

json_path

=

os

.

path

.

join

(

output_dir

,

f

"report_{timestamp}.json"

)

       

with

open

(

json_path

,

"w"

,

encoding

=

"utf-8"

)

as

f:

json.

dump

(

report

,

f

,

ensure_ascii

=

False

,

indent

=

2

)

       

Save readable text

txt_path

=

os

.

path

.

join

(

output_dir

,

f

"report_{timestamp}.txt"

)

       

with

open

(

txt_path

,

"w"

,

encoding

=

"utf-8"

)

as

f:

f.

write

(

"="

60

"\n"

)

f.

write

(

"RUNOOB Image Analysis Report\n"

)

f.

write

(

"="

60

"\n\n"

)

f.

write

(

f

"Image: {report['image_file']}\n"

)

f.

write

(

f

"Time: {report['analysis_time']}\n"

)

            f.

write

(

f

"Category: {report['category']}\n\n"

)

f.

write

(

"-"

60

"\n"

)

f.

write

(

"Image description:\n"

)

f.

write

(

"-"

60

"\n"

)

f.

write

(

report

[

"description"

]

"\n\n"

)

f.

write

(

"-"

60

"\n"

)

f.

write

(

Extract text:

)

f.

write

(

"-"

60

"\n"

)

f.

write

(

report

[

"extracted_text"

]

""

)

           

if

report

[

"special_analysis"

]

:

f.

write

(

"-"

60

"\n"

)

f.

write

(

"Special analysis:\n"

)

f.

write

(

"-"

60

"\n"

)

f.

write

(

report

[

"special_analysis"

]

"\n"

)

       

print

(

f

"Analysis complete! Report saved to: {output_dir}"

)

       

return

report

============================================

Usage example

============================================

def

main

(

)

:

   

Configure your API Key

api_key

=

"sk-your-api-key-here"

   

Create analyzer

analyzer

=

RunoobImageAnalyzer

(

api_key

)

   

Path of the image to be analyzed

image_path

=

"runoob_test_image.jpg"

   

if

not

os

.

path

.

exists

(

image_path

)

:

       

print

(

f

"Please prepare the image: {image_path}"

)

       

return

   

Method 1: Using a specific function alone

   

print

(

Method 1: Using OCR function separately

)

   

print

(

"-"

40

)

text

=

analyzer.

extract_text

(

image_path

)

   

if

text:

       

print

(

"Extracted text:"

)

       

print

(

text

)

   

Method 2: Full Analysis

   

print

(

"\nMethod 2: Full Analysis"

)

   

print

(

"-"

40

)

report

=

analyzer.

full_analysis

(

image_path

)

   

print

(

f

"Category result: {report['category']}"

)

   

print

(

f

"Report saved"

)

if

name

==

"main"

:

    main

(

)

This tool encapsulates common image analysis functions and can be used directly in projects.

You can extend it according to your needs: