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.
-
Text AI can only process text, such as asking ChatGPT to write an article.
-
Image AI can only process images, such as asking Midjourney to draw a picture.
-
Audio AI can only process sound, such as asking Whisper to transcribe speech.
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.
-
The first challenge is "alignment"—how to make the "cat" in the image and the "cat" in the text be the same thing in the model's view?
-
The second challenge is "fusion"—when seeing an image and text simultaneously, how to combine their information?
-
The third challenge is "generation"—how to generate an image based on a text description, or generate a text description based on an image?
-
Fortunately, these problems are being solved step by step. Most mainstream large models after 2024 are multimodal.
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:
-
One is to directly upload an image file, such as clicking the image icon in the ChatGPT web version to upload.
-
The other is to embed the image in the API request using Base64 encoding, which is suitable for program calls.
| 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:
-
Image description—What is in this picture?
-
OCR—Extract text from the image.
-
Chart analysis—What is this bar chart saying?
-
Detail finding—Help me check this design draft for any issues.
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
(
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}"
(
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
)
:
(
f
"Hint: Please prepare an image named {test_image} in the current directory"
)
(
"Or modify the image path in the code"
)
else
:
Task 1: General Image Description
(
"\n"
"="
50
)
(
"Task 1: Image Description"
)
(
"="
50
)
result1
=
analyze_image_with_gpt4o
(
test_image
,
"Please describe this image in detail, including the main subject, background, colors, composition, etc."
)
(
result1
)
Task 2: OCR Text Extraction
(
"\n"
"="
50
)
(
"Task 2: OCR Text Extraction"
)
(
"="
50
)
result2
=
extract_text_from_image
(
test_image
)
(
result2
)
Task 3: Chart Analysis (if the image is a chart)
(
"\n"
"="
50
)
(
"Task 3: Chart Analysis"
)
(
"="
50
)
result3
=
analyze_chart
(
test_image
)
(
result3
)
(
"\n"
"="
50
)
(
"RUNOOB Tutorial Demonstration Complete!"
)
(
"="
50
)
Before running this program, you need to:
-
1. Install dependencies:
pip install requests -
2. Prepare a test image and name it
runoob_test_image.jpg -
3. Replace the API key with your own
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:
-
Training phase: Show the model a clear image, then gradually add noise until it becomes a completely snowy mess. The model learns how to gradually restore the image from the noise.
-
Generation phase: Give the model a random noise image and have it gradually denoise based on the text prompt to finally generate a clear image that matches the description.
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:
-
Subject description—"a cat wearing a hat"
-
Style—"Miyazaki style", "Oil painting", "3D rendering"
-
Lighting—"Natural light", "Cinematic light", "Cyberpunk neon light"
-
Composition—"Close-up", "Wide-angle", "Top-down"
-
Image Quality—"8K", "Ultra-high detail", "Photorealistic"
| 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:
-
1. Install Python 3.10
-
2. Download Stable Diffusion WebUI
-
3. Download model files (.safetensors format)
-
4. Run webui.bat (Windows) or webui.sh (Mac/Linux)
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
(
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
)
(
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
)
(
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}"
(
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"
:
(
"="
60
)
(
"RUNOOB DALL·E 3 Image Generation Demo"
)
(
"="
60
)
Task 1: Generate Logo
(
"\n[Task 1] Generating Logo ..."
)
result1
=
generate_runoob_logo_demo
(
)
Task 2: Generate book cover
(
"\n[Task 2] Generating book cover ..."
)
result2
=
generate_book_cover_demo
(
)
Task 3: Generate banner
(
"\n[Task 3] Generating banner ..."
)
result3
=
generate_banner_demo
(
)
(
"\n"
"="
60
)
(
"All tasks completed! Check the runoob_generated_images directory"
)
(
"="
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 | 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:
-
Advantages include: fast creativity, low cost, and the ability to achieve effects that are difficult to film in reality.
-
Disadvantages include: limited duration, easy detail degradation, and sometimes incorrect physical logic (e.g., objects passing through each other, incorrect hand poses).
-
Suitable scenarios: concept demonstrations, short video materials, e-commerce advertisements, and game animations.
-
Unsuitable scenarios: long-form content requiring precise control, serious news, legal evidence.
Video understanding and summarization
Besides generating videos, AI can also understand videos.
Common tasks in video understanding:
-
Video summarization—"What is this video about? Summarize it in 3 sentences."
-
Content retrieval—"Find the segment where someone is riding a bicycle in the video."
-
Question answering—"What did the third person say in the video?"
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:
-
Longer—from 10 seconds to 1 minute, and then to 10 minutes.
-
More controllable—able to precisely control every shot using a storyboard.
-
More consistent—the same character remains consistent across different shots.
-
More practical—from looking cool to solving real-world problems.
-
We can expect: in a few years, perhaps everyone will be able to create movie-like video works using AI.
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
(
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"
]
(
f
"Transcription complete, total {len(text)} characters"
)
return
{
"text"
: text
,
"language"
: language
}
else
:
error_msg
=
f
"Request failed: {response.status_code} - {response.text}"
(
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
(
"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)
(
"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
)
:
(
f
"Hint: Please prepare an audio file named {test_audio}"
)
(
"Or record a voice message on your phone and save it as mp3 format"
)
else
:
Task 1: Simple Transcription
(
"\n"
"="
50
)
(
"Task 1: Simple Transcription"
)
(
"="
50
)
result1
=
transcribe_audio_with_whisper
(
test_audio
,
language
=
"zh"
)
if
"text"
in
result1:
(
"Transcription result:"
)
(
result1
[
"text"
]
)
Task 2: Transcription with timestamp
(
"\n"
"="
50
)
(
"Task 2: Transcription with timestamp"
)
(
"="
50
)
result2
=
transcribe_with_timestamps
(
test_audio
)
if
"segments"
in
result2:
(
"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"
]
(
f
"[{start}-{end}] {text}"
)
(
"\n"
"="
50
)
(
"RUNOOB Whisper demo completed!"
)
(
"="
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:
-
Can do: generate background music, write song demos, quickly try styles.
-
Cannot do well: completely replicate a song, precisely control notes, professional-grade post-production.
-
Regarding copyright: terms differ for various tools; please confirm before commercial use.
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:
-
1. Convert the image into a vector
-
2. Convert the text into a vector
-
3. Make the vectors of paired image and text as close as possible, and those of unpaired items as far apart as possible
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:
-
A vision encoder (like ViT) - responsible for seeing images
-
A large language model (like LLaMA) - responsible for speaking
-
A projection layer - converts image vectors into a format the language model can understand
Training is done in two steps:
-
First step: Pre-training alignment - making the vision encoder and language model speak the same language
-
Second step: Instruction fine-tuning - training with image-question-answer data to learn to answer according to instructions
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
:
(
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
"""
(
f
"Starting image analysis: {image_path}"
)
First classify
(
"[1/5] Categorizing..."
)
category
=
self
.
classify
(
image_path
)
or
"Unknown"
Description
(
"[2/5] In description..."
)
description
=
self
.
describe
(
image_path
)
or
""
Extract text
(
"[3/5] OCR in progress..."
)
text
=
self
.
extract_text
(
image_path
)
or
""
Perform specialized analysis by category
(
"[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
(
"[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"
)
(
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
)
:
(
f
"Please prepare the image: {image_path}"
)
return
Method 1: Using a specific function alone
(
Method 1: Using OCR function separately
)
(
"-"
40
)
text
=
analyzer.
extract_text
(
image_path
)
if
text:
(
"Extracted text:"
)
(
text
)
Method 2: Full Analysis
(
"\nMethod 2: Full Analysis"
)
(
"-"
40
)
report
=
analyzer.
full_analysis
(
image_path
)
(
f
"Category result: {report['category']}"
)
(
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:
-
Add more analysis scenarios (such as medical imaging, industrial inspection, or educational question analysis)
-
Add a simple web interface (using Flask or Gradio)
-
Support batch processing of images in a folder
-
Store the results in a database