basic.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. import json
  2. import httpx
  3. import requests
  4. from Log import logger
  5. class BasicService:
  6. def __init__(self, base_url: str):
  7. self.base_url = base_url
  8. def _check_response(self, response: httpx.Response):
  9. """检查响应并处理错误"""
  10. if response.status_code not in [200, 201]:
  11. raise Exception(f"Failed to fetch data from API: {response.text}")
  12. response_data = response.json()
  13. return response_data
  14. async def download_from_url(self, url, params=None):
  15. async with httpx.AsyncClient() as client:
  16. async with client.stream('GET', url, params=params) as response:
  17. if response.status_code == 200:
  18. # 获取文件名
  19. content_disposition = response.headers.get('Content-Disposition')
  20. if content_disposition:
  21. filename = content_disposition.split('filename=')[1].strip('"')
  22. else:
  23. filename = 'unknown_filename'
  24. # 获取内容类型
  25. content_type = response.headers.get('Content-Type')
  26. # 读取文件内容
  27. content = await response.aread()
  28. return content, filename, content_type
  29. else:
  30. raise Exception(f"Failed to download: {response.status_code}")
  31. async def excel_talk_image_download(self, file_id: str):
  32. url = f"{self.base_url}/exceltalk/download/image"
  33. return await self.download_from_url(url, params={'images_name': file_id})
  34. async def excel_talk_excel_download(self, file_id: str):
  35. url = f"{self.base_url}/exceltalk/download/excel"
  36. return await self.download_from_url(url, params={'excel_name': file_id})
  37. async def excel_talk_upload(self, chat_id: str, files):
  38. url = f"{self.base_url}/exceltalk/upload/files"
  39. params = {'chat_id': chat_id, 'is_col': '0'}
  40. async with httpx.AsyncClient() as client:
  41. response = await client.post(
  42. url,
  43. files=files,
  44. params=params
  45. )
  46. return self._check_response(response)
  47. async def excel_talk(self, question: str, chat_id: str):
  48. url = f"{self.base_url}/exceltalk/talk"
  49. params = {'chat_id': chat_id}
  50. data = {"query": question}
  51. headers = {'Content-Type': 'application/json'}
  52. with requests.post(url, headers=headers, json=data, params=params, timeout=60,
  53. stream=True) as response:
  54. for line in response.iter_lines():
  55. if line:
  56. decoded_line = line.decode("utf-8")
  57. try:
  58. if decoded_line.startswith("data:"):
  59. decoded_line = decoded_line[5:]
  60. answer = json.loads(decoded_line)
  61. yield answer
  62. except GeneratorExit as e:
  63. print(e)
  64. yield {"message": "内部错误", "type": "close"}
  65. finally:
  66. # 在所有数据接收完毕后返回close
  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={'word_name': file_id})