ai_copywriter.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import io
  2. import base64
  3. from PIL import Image
  4. from volcenginesdkarkruntime import Ark
  5. client = Ark(
  6. api_key= "817dff39-5586-4f9b-acba-55004167c0b1",
  7. base_url="https://ark.cn-beijing.volces.com/api/v3",
  8. )
  9. default_prompt = """
  10. ## 角色:小红书博主,文案能力优秀
  11. ## 任务:基于图像内容,生成小红书高赞文案,文案风格为小红书风格,需要有标题,具体文案内容和话题标签(话题标签至少5个)。
  12. ## 要求:
  13. - 字数控制在400字以内,多使用合适的emoji表情
  14. - 除了输出标题、具体文案内容和话题标签,不要输出任何额外的内容
  15. ## 输出格式:
  16. - 标题:<标题文本>
  17. - 文案:<文案文本>
  18. - 话题标签:<话题标签文本>
  19. """
  20. def encode_image(pil_image):
  21. """将PIL Image对象转换为base64编码"""
  22. buffered = io.BytesIO()
  23. pil_image.save(buffered, format="JPEG")
  24. return base64.b64encode(buffered.getvalue()).decode('utf-8')
  25. def gen_copywriter(image_path, sys_prompt=default_prompt):
  26. base64_image = encode_image(image_path)
  27. response = client.chat.completions.create(
  28. model="doubao-1-5-vision-pro-32k-250115",
  29. temperature=1,
  30. max_tokens=200,
  31. messages=[
  32. {
  33. "role": "user",
  34. "content": [
  35. {
  36. "type": "text",
  37. "text": sys_prompt,
  38. },
  39. {
  40. "type": "image_url",
  41. "image_url": {
  42. "url": f"data:image/jpg;base64,{base64_image}"
  43. },
  44. },
  45. ],
  46. }
  47. ],
  48. )
  49. return response.choices[0].message.content
  50. if __name__ == "__main__":
  51. with Image.open("./backend/data/cloth.png") as img:
  52. print(gen_copywriter(img))