65 lines
2.5 KiB
Python
65 lines
2.5 KiB
Python
from zhipuai import ZhipuAI
|
|
from datetime import datetime
|
|
import pytz, io, logging, json, re
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
class ZhipuFileService:
|
|
def __init__(self):
|
|
self.app_secret_key = "d54f764a1d67c17d857bd3983b772016.GRjowY0fyiMNurLc"
|
|
|
|
|
|
def submit_file(self, prefix, project_name, file_content: str) -> dict:
|
|
"""
|
|
Uploads a file to the Zhipu API and returns the file ID.
|
|
"""
|
|
file_list = self.get_file_list()
|
|
current_date = datetime.now().strftime('%Y-%m-%d')
|
|
base_filename = f"{prefix}-{project_name}-{current_date}"
|
|
next_version = self.get_next_version(file_list, base_filename)
|
|
filename = f"{base_filename}_v{next_version}.txt"
|
|
|
|
client = ZhipuAI(api_key=self.app_secret_key) # 请填写您自己的APIKey
|
|
|
|
file_obj = io.BytesIO(file_content.encode('utf-8'))
|
|
file_tuple = (filename, file_obj, 'text/plain')
|
|
|
|
|
|
result = client.files.create(
|
|
file=file_tuple,
|
|
purpose="retrieval" , #支持retrieval、batch、fine-tune、file-extract
|
|
knowledge_id="1843318172036575232",
|
|
)
|
|
# logger.info("File uploaded result:", result)
|
|
|
|
if result.successInfos and len(result.successInfos) > 0:
|
|
return {"status": "success", "document_id": result.successInfos[0]['documentId'], "filename": filename}
|
|
elif result.failedInfos and len(result.failedInfos) > 0:
|
|
return {"status": "failed", "error": result.failedInfos[0].get('reason', 'Unknown error'), "filename": filename}
|
|
else:
|
|
return {"status": "unknown", "error": "No success or failure information provided", "filename": filename}
|
|
|
|
def get_file_list(self):
|
|
client = ZhipuAI(api_key=self.app_secret_key) # 请填写您自己的APIKey
|
|
result = client.knowledge.document.list(
|
|
purpose="retrieval", #支持retrieval
|
|
knowledge_id="1843318172036575232"
|
|
)
|
|
file_list = []
|
|
if result and hasattr(result, 'list'):
|
|
for doc in result.list:
|
|
file_list.append({
|
|
'id': doc.id,
|
|
'filename': doc.name
|
|
})
|
|
|
|
return file_list
|
|
|
|
def get_next_version(self, file_list, base_filename):
|
|
versions = [1] # Start with version 1 if no existing versions
|
|
for file in file_list:
|
|
match = re.match(rf'{re.escape(base_filename)}_v(\d+)', file['filename'])
|
|
if match:
|
|
versions.append(int(match.group(1)))
|
|
return max(versions) + 1
|