basic.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. import json
  2. import httpx
  3. from Log import logger
  4. class BasicService:
  5. def __init__(self, base_url: str):
  6. self.base_url = base_url
  7. def _check_response(self, response: httpx.Response):
  8. """检查响应并处理错误"""
  9. if response.status_code not in [200, 201]:
  10. raise Exception(f"Failed to fetch data from API: {response.text}")
  11. response_data = response.json()
  12. return response_data
  13. async def download_from_url(self, url, params=None):
  14. async with httpx.AsyncClient() as client:
  15. async with client.stream('GET', url, params=params) as response:
  16. if response.status_code == 200:
  17. # 获取文件名
  18. content_disposition = response.headers.get('Content-Disposition')
  19. if content_disposition:
  20. filename = content_disposition.split('filename=')[1].strip('"')
  21. else:
  22. filename = 'unknown_filename'
  23. # 获取内容类型
  24. content_type = response.headers.get('Content-Type')
  25. # 读取文件内容
  26. content = await response.aread()
  27. return content, filename, content_type
  28. else:
  29. raise Exception(f"Failed to download: {response.status_code}")
  30. async def excel_talk_image_download(self, file_id: str):
  31. url = f"{self.base_url}/exceltalk/download/image"
  32. return await self.download_from_url(url, params={'images_name': file_id})
  33. async def excel_talk_excel_download(self, file_id: str):
  34. url = f"{self.base_url}/exceltalk/download/excel"
  35. return await self.download_from_url(url, params={'excel_name': file_id})
  36. async def excel_talk_upload(self, chat_id: str, filename: str, file_content: bytes):
  37. url = f"{self.base_url}/exceltalk/upload/files"
  38. params = {'chat_id': chat_id, 'is_col': '0'}
  39. # 创建 FormData 对象
  40. files = [('files', (filename, file_content, 'application/octet-stream'))]
  41. async with httpx.AsyncClient() as client:
  42. response = await client.post(
  43. url,
  44. files=files,
  45. params=params
  46. )
  47. return self._check_response(response)
  48. async def excel_talk(self, question: str, chat_id: str):
  49. url = f"{self.base_url}/exceltalk/talk"
  50. params = {'chat_id': chat_id}
  51. data = {"query": question}
  52. headers = {'Content-Type': 'application/json'}
  53. buffer = bytearray()
  54. async with httpx.AsyncClient(timeout=300.0) as client:
  55. async with client.stream("POST", url, params=params, json=data, headers=headers) as response:
  56. if response.status_code == 200:
  57. try:
  58. async for chunk in response.aiter_bytes():
  59. json_data = process_buffer(chunk, buffer)
  60. if json_data:
  61. yield json_data
  62. buffer.clear()
  63. except GeneratorExit as e:
  64. print(e)
  65. yield {"message": "内部错误", "type": "close"}
  66. finally:
  67. # 在所有数据接收完毕后记录日志
  68. logger.info("All messages received and processed - over")
  69. yield {"message": "", "type": "close"}
  70. else:
  71. yield f"Error: {response.status_code}"
  72. async def questions_talk(self, question, chat_id: str):
  73. logger.error("---------------questions_talk--------------------------")
  74. url = f"{self.base_url}/questions/talk"
  75. params = {'chat_id': chat_id}
  76. headers = {'Content-Type': 'text/plain'}
  77. async with httpx.AsyncClient(timeout=1800) as client:
  78. response = await client.post(
  79. url,
  80. data=question,
  81. headers=headers,
  82. params=params
  83. )
  84. return self._check_response(response)
  85. async def questions_talk_word_download(self, file_id: str):
  86. url = f"{self.base_url}/questions/download/word"
  87. return await self.download_from_url(url, params={'word_name': file_id})
  88. def process_buffer(data, buffer):
  89. def try_parse_json(data1):
  90. try:
  91. return True, json.loads(data1)
  92. except json.JSONDecodeError:
  93. return False, None
  94. if data.startswith(b'data:'):
  95. # 删除 'data:' 头
  96. data = data[5:].strip()
  97. else:
  98. pass
  99. # 直接拼接到缓冲区尝试解析JSON
  100. buffer.extend(data.strip())
  101. success, parsed_data = try_parse_json(buffer)
  102. if success:
  103. return parsed_data
  104. else:
  105. # 解析失败,继续拼接
  106. return None