basic.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  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, files):
  37. url = f"{self.base_url}/exceltalk/upload/files"
  38. params = {'chat_id': chat_id, 'is_col': '0'}
  39. async with httpx.AsyncClient() as client:
  40. response = await client.post(
  41. url,
  42. files=files,
  43. params=params
  44. )
  45. return self._check_response(response)
  46. async def excel_talk(self, question: str, chat_id: str):
  47. url = f"{self.base_url}/exceltalk/talk"
  48. params = {'chat_id': chat_id}
  49. data = {"query": question}
  50. headers = {'Content-Type': 'application/json'}
  51. buffer = bytearray()
  52. async with httpx.AsyncClient(timeout=300.0) as client:
  53. async with client.stream("POST", url, params=params, json=data, headers=headers) as response:
  54. if response.status_code == 200:
  55. try:
  56. async for chunk in response.aiter_bytes():
  57. json_data = process_buffer(chunk, buffer)
  58. if json_data:
  59. yield json_data
  60. buffer.clear()
  61. except GeneratorExit as e:
  62. print(e)
  63. yield {"message": "内部错误", "type": "close"}
  64. finally:
  65. # 在所有数据接收完毕后记录日志
  66. logger.info("All messages received and processed - over")
  67. yield {"message": "", "type": "close"}
  68. else:
  69. yield f"Error: {response.status_code}"
  70. async def questions_talk(self, question, chat_id: str):
  71. logger.error("---------------questions_talk--------------------------")
  72. url = f"{self.base_url}/questions/talk"
  73. params = {'chat_id': chat_id}
  74. headers = {'Content-Type': 'text/plain'}
  75. async with httpx.AsyncClient(timeout=1800) as client:
  76. response = await client.post(
  77. url,
  78. data=question,
  79. headers=headers,
  80. params=params
  81. )
  82. return self._check_response(response)
  83. async def questions_talk_word_download(self, file_id: str):
  84. url = f"{self.base_url}/questions/download/word"
  85. return await self.download_from_url(url, params={'excel_name': file_id})
  86. def process_buffer(data, buffer):
  87. def try_parse_json(data1):
  88. try:
  89. return True, json.loads(data1)
  90. except json.JSONDecodeError:
  91. return False, None
  92. if data.startswith(b'data:'):
  93. # 删除 'data:' 头
  94. data = data[5:].strip()
  95. else:
  96. pass
  97. # 直接拼接到缓冲区尝试解析JSON
  98. buffer.extend(data.strip())
  99. success, parsed_data = try_parse_json(buffer)
  100. if success:
  101. return parsed_data
  102. else:
  103. # 解析失败,继续拼接
  104. return None