1+ import requests
2+ import json
3+ import os
4+ import base64
5+ from PIL import Image
6+ from io import BytesIO
7+ import time
8+ from src .upload .bilitool .bilitool .model .model import Model
9+ from src .config import BAIDU_API_KEY
10+
11+ def cover_up (img : str ):
12+ """Upload the cover image
13+ Parameters
14+ ----------
15+ - img: img path or stream
16+ Returns
17+ -------
18+ - url: str
19+ the url of the cover image in bili server
20+ """
21+ from PIL import Image
22+ from io import BytesIO
23+ request = requests .Session ()
24+ request .headers = {
25+ 'user-agent' : "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 Chrome/63.0.3239.108" ,
26+ 'referer' : "https://www.bilibili.com/" ,
27+ 'connection' : 'keep-alive'
28+ }
29+ model = Model ().get_config ()
30+ request .cookies .set ('SESSDATA' , model ['cookies' ]['SESSDATA' ])
31+ with Image .open (img ) as im :
32+ # you should keep the image ratio 16:10
33+ xsize , ysize = im .size
34+ if xsize / ysize > 1.6 :
35+ delta = xsize - ysize * 1.6
36+ region = im .crop ((delta / 2 , 0 , xsize - delta / 2 , ysize ))
37+ else :
38+ delta = ysize - xsize * 10 / 16
39+ region = im .crop ((0 , delta / 2 , xsize , ysize - delta / 2 ))
40+ buffered = BytesIO ()
41+ region .save (buffered , format = im .format )
42+ r = request .post (
43+ url = "https://member.bilibili.com/x/vu/web/cover/up" ,
44+ data = {
45+ "cover" : b"data:image/jpeg;base64,"
46+ + (base64 .b64encode (buffered .getvalue ())),
47+ "csrf" : model ['cookies' ]['bili_jct' ]
48+ },
49+ timeout = 30 ,
50+ )
51+ buffered .close ()
52+ res = r .json ()
53+ if res .get ("data" ) is None :
54+ raise Exception (res )
55+ print (res ["data" ]["url" ], flush = True )
56+ return res ["data" ]["url" ]
57+
58+ def baidu_generate_cover (your_file_path ):
59+ try :
60+ cover_url = cover_up (your_file_path )
61+
62+ url = "https://qianfan.baidubce.com/v2/images/generations"
63+ payload = json .dumps ({
64+ "model" : "irag-1.0" ,
65+ "prompt" : "这是视频截图,请根据该图生成对应的动漫类型的封面" ,
66+ "refer_image" : cover_url
67+ })
68+ headers = {
69+ 'Content-Type' : 'application/json' ,
70+ 'Authorization' : f'Bearer { BAIDU_API_KEY } '
71+ }
72+
73+ response = requests .request ("POST" , url , headers = headers , data = payload )
74+ if response .status_code == 200 :
75+ image_url = response .json ()['data' ][0 ]['url' ]
76+ img_data = requests .get (image_url ).content
77+ cover_name = time .strftime ("%Y%m%d%H%M%S" ) + ".png"
78+ temp_cover_path = os .path .join (os .path .dirname (your_file_path ), cover_name )
79+ with open (temp_cover_path , "wb" ) as handler :
80+ handler .write (img_data )
81+ os .remove (your_file_path )
82+ return temp_cover_path
83+ else :
84+ print (response .text , flush = True )
85+ return None
86+ except Exception as e :
87+ print (e , flush = True )
88+ return None
89+
90+ if __name__ == '__main__' :
91+ print (baidu_generate_cover ("" ))
0 commit comments