一、AIGC 概述
AIGC(人工智能生成內容)是指利用人工智能技術自動生成文本、圖像、音頻、視頻等內容的技術。主要技術包括:
- 生成對抗網絡 (GANs) - 用於圖像生成
- 變分自編碼器 (VAEs) - 用於數據生成和壓縮
- 擴散模型 (Diffusion Models) - 當前主流的圖像生成技術
- 大語言模型 (LLMs) - 如GPT系列,用於文本生成
- 多模態模型 - 如DALL-E、Stable Diffusion,可跨模態生成內容
二、文本生成示例 - 使用Transformers
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM
class TextGenerator:
def __init__(self, model_name="gpt2"):
"""初始化文本生成器"""
self.tokenizer = AutoTokenizer.from_pretrained(model_name)
self.model = AutoModelForCausalGPT2LM.from_pretrained(model_name)
if self.tokenizer.pad_token is None:
self.tokenizer.pad_token = self.tokenizer.eos_token
def generate_text(self, prompt, max_length=100, temperature=0.7):
"""生成文本
Args:
prompt: 提示文本
max_length: 生成的最大長度
temperature: 温度參數,控制隨機性
"""
# 編碼輸入
inputs = self.tokenizer(prompt, return_tensors="pt")
# 生成文本
with torch.no_grad():
outputs = self.model.generate(
inputs.input_ids,
max_length=max_length,
temperature=temperature,
do_sample=True,
top_p=0.9,
pad_token_id=self.tokenizer.pad_token_id,
eos_token_id=self.tokenizer.eos_token_id
)
# 解碼輸出
generated_text = self.tokenizer.decode(outputs[0], skip_special_tokens=True)
return generated_text
# 使用示例
if __name__ == "__main__":
generator = TextGenerator()
prompt = "人工智能在未來將"
result = generator.generate_text(prompt, max_length=50)
print("提示:", prompt)
print("生成結果:", result)
三、圖像生成示例 - 使用Stable Diffusion
import torch
from diffusers import StableDiffusionPipeline
from PIL import Image
import matplotlib.pyplot as plt
class ImageGenerator:
def __init__(self, model_id="runwayml/stable-diffusion-v1-5"):
"""初始化圖像生成器"""
self.pipe = StableDiffusionPipeline.from_pretrained(
model_id,
torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32
)
if torch.cuda.is_available():
self.pipe = self.pipe.to("cuda")
def generate_image(self, prompt, negative_prompt=None,
num_inference_steps=30, guidance_scale=7.5):
"""生成圖像
Args:
prompt: 正面提示詞
negative_prompt: 負面提示詞
num_inference_steps: 推理步數
guidance_scale: 指導尺度
"""
# 生成圖像
image = self.pipe(
prompt=prompt,
negative_prompt=negative_prompt,
num_inference_steps=num_inference_steps,
guidance_scale=guidance_scale
).images[0]
return image
def generate_variations(self, prompt, num_variations=4):
"""生成多個變體"""
images = []
for i in range(num_variations):
image = self.generate_image(
prompt=f"{prompt}, variation {i+1}",
num_inference_steps=25
)
images.append(image)
return images
# 使用示例(簡化版 - 實際運行需要GPU和較大內存)
if __name__ == "__main__":
# 注意:完整運行需要GPU和至少8GB顯存
# 以下為演示代碼結構
# generator = ImageGenerator()
# 生成單張圖像
# prompt = "一隻可愛的卡通貓,數字藝術,明亮色彩"
# image = generator.generate_image(prompt)
# image.save("generated_cat.png")
# 生成多個變體
# variations = generator.generate_variations("星空下的山脈", num_variations=4)
print("圖像生成器初始化完成(示例代碼)")
四、簡易AIGC應用 - 文本摘要生成
import re
from collections import Counter
import numpy as np
from typing import List, Tuple
class SimpleTextSummarizer:
"""基於TextRank的簡易文本摘要生成器"""
def __init__(self):
self.stopwords = set([
'的', '了', '在', '是', '我', '有', '和', '就',
'不', '人', '都', '一', '一個', '上', '也', '很',
'到', '説', '要', '去', '你', '會', '着', '沒有',
'看', '好', '自己', '這', '那', '他', '她', '它'
])
def preprocess(self, text: str) -> List[str]:
"""預處理文本"""
# 分割句子
sentences = re.split(r'[。!?!?]', text)
sentences = [s.strip() for s in sentences if len(s.strip()) > 5]
# 分詞(簡易版本)
words_in_sentences = []
for sentence in sentences:
words = []
for char in sentence:
if char not in self.stopwords and char.strip():
words.append(char)
words_in_sentences.append(words)
return sentences, words_in_sentences
def calculate_similarity(self, words1: List[str], words2: List[str]) -> float:
"""計算兩個句子的相似度"""
if not words1 or not words2:
return 0.0
# 使用Jaccard相似度
set1, set2 = set(words1), set(words2)
intersection = len(set1.intersection(set2))
union = len(set1.union(set2))
return intersection / union if union > 0 else 0.0
def build_graph(self, words_in_sentences: List[List[str]]) -> np.ndarray:
"""構建句子圖"""
n = len(words_in_sentences)
graph = np.zeros((n, n))
for i in range(n):
for j in range(n):
if i != j:
graph[i][j] = self.calculate_similarity(
words_in_sentences[i],
words_in_sentences[j]
)
return graph
def textrank(self, graph: np.ndarray, damping=0.85, max_iter=100) -> np.ndarray:
"""TextRank算法計算句子重要性"""
n = len(graph)
scores = np.ones(n) / n
# 歸一化圖
norm_graph = graph / (graph.sum(axis=1)[:, np.newaxis] + 1e-10)
for _ in range(max_iter):
new_scores = (1 - damping) / n + damping * norm_graph.T.dot(scores)
if np.abs(new_scores - scores).sum() < 1e-6:
break
scores = new_scores
return scores
def summarize(self, text: str, num_sentences: int = 3) -> str:
"""生成摘要"""
# 預處理
sentences, words_in_sentences = self.preprocess(text)
if len(sentences) <= num_sentences:
return '。'.join(sentences) + '。'
# 構建圖和計算重要性
graph = self.build_graph(words_in_sentences)
scores = self.textrank(graph)
# 選擇最重要的句子
ranked_indices = np.argsort(-scores)[:num_sentences]
ranked_indices.sort() # 保持原文順序
# 生成摘要
summary_sentences = [sentences[i] for i in ranked_indices]
summary = '。'.join(summary_sentences) + '。'
return summary
# 使用示例
if __name__ == "__main__":
# 示例文本
text = """
人工智能是計算機科學的一個分支,它企圖瞭解智能的實質,並生產出一種新的能以人類智能相似的方式做出反應的智能機器。
該領域的研究包括機器人、語言識別、圖像識別、自然語言處理和專家系統等。人工智能從誕生以來,理論和技術日益成熟,
應用領域也不斷擴大,可以設想,未來人工智能帶來的科技產品,將會是人類智慧的容器。人工智能可以對人的意識、
思維的信息過程的模擬。人工智能不是人的智能,但能像人那樣思考,也可能超過人的智能。
"""
summarizer = SimpleTextSummarizer()
summary = summarizer.summarize(text, num_sentences=2)
print("原文:")
print(text)
print("\n自動摘要:")
print(summary)
五、AIGC應用注意事項
1. 倫理問題
class AIGCEthicsChecker:
"""AIGC倫理檢查器(簡化版)"""
def __init__(self):
self.harmful_patterns = [
"暴力", "仇恨", "歧視", "虛假信息",
"隱私侵犯", "版權侵權", "深度偽造"
]
def check_content(self, content: str, content_type: str = "text") -> dict:
"""檢查內容是否符合倫理規範"""
issues = []
# 檢查有害內容
for pattern in self.harmful_patterns:
if pattern in content:
issues.append(f"可能包含{pattern}")
# 根據不同內容類型添加特定檢查
if content_type == "image":
issues.extend(self._check_image_ethics(content))
elif content_type == "text":
issues.extend(self._check_text_ethics(content))
return {
"has_issues": len(issues) > 0,
"issues": issues,
"suggestion": "請確保生成內容符合倫理規範和法律法規"
}
def _check_text_ethics(self, text: str) -> List[str]:
"""檢查文本倫理"""
issues = []
# 這裏可以添加更復雜的檢查邏輯
return issues
def _check_image_ethics(self, image_info: str) -> List[str]:
"""檢查圖像倫理"""
issues = []
# 這裏可以添加圖像特定的檢查邏輯
return issues
2. 實踐建議
- 明確目標:確定AIGC的具體應用場景
- 數據質量:確保訓練數據的質量和多樣性
- 迭代優化:通過反饋循環不斷改進生成結果
- 人工審核:重要內容需進行人工審核
- 版權意識:注意生成內容的版權問題
六、未來發展趨勢
- 多模態融合:文本、圖像、音頻、視頻的深度融合生成
- 交互式生成:人機協作的內容創作模式
- 個性化定製:根據用户偏好生成個性化內容
- 實時生成:低延遲的實時內容生成
- 可解釋性:提高生成過程的透明度和可解釋性
以上代碼示例展示了AIGC的基本應用,實際生產中需要根據具體需求選擇合適的模型和優化策略。AIGC技術正在快速發展,為內容創作帶來了革命性的變化。