Copilot.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. from __future__ import annotations
  2. import os
  3. import json
  4. import asyncio
  5. import base64
  6. from http.cookiejar import CookieJar
  7. from urllib.parse import quote
  8. try:
  9. from curl_cffi.requests import Session, CurlWsFlag
  10. has_curl_cffi = True
  11. except ImportError:
  12. has_curl_cffi = False
  13. try:
  14. import nodriver
  15. has_nodriver = True
  16. except ImportError:
  17. has_nodriver = False
  18. from .base_provider import AbstractProvider, ProviderModelMixin
  19. from .helper import format_prompt_max_length
  20. from .openai.har_file import get_headers, get_har_files
  21. from ..typing import CreateResult, Messages, ImagesType
  22. from ..errors import MissingRequirementsError, NoValidHarFileError
  23. from ..requests.raise_for_status import raise_for_status
  24. from ..providers.response import BaseConversation, JsonConversation, RequestLogin, Parameters
  25. from ..providers.asyncio import get_running_loop
  26. from ..requests import get_nodriver
  27. from ..image import ImageResponse, to_bytes, is_accepted_format
  28. from .. import debug
  29. class Conversation(JsonConversation):
  30. conversation_id: str
  31. def __init__(self, conversation_id: str):
  32. self.conversation_id = conversation_id
  33. class Copilot(AbstractProvider, ProviderModelMixin):
  34. label = "Microsoft Copilot"
  35. url = "https://copilot.microsoft.com"
  36. working = True
  37. supports_stream = True
  38. default_model = "Copilot"
  39. models = [default_model]
  40. model_aliases = {
  41. "gpt-4": "Copilot",
  42. }
  43. websocket_url = "wss://copilot.microsoft.com/c/api/chat?api-version=2"
  44. conversation_url = f"{url}/c/api/conversations"
  45. _access_token: str = None
  46. _cookies: CookieJar = None
  47. @classmethod
  48. def create_completion(
  49. cls,
  50. model: str,
  51. messages: Messages,
  52. stream: bool = False,
  53. proxy: str = None,
  54. timeout: int = 900,
  55. prompt: str = None,
  56. images: ImagesType = None,
  57. conversation: BaseConversation = None,
  58. return_conversation: bool = False,
  59. api_key: str = None,
  60. web_search: bool = False,
  61. **kwargs
  62. ) -> CreateResult:
  63. if not has_curl_cffi:
  64. raise MissingRequirementsError('Install or update "curl_cffi" package | pip install -U curl_cffi')
  65. websocket_url = cls.websocket_url
  66. headers = None
  67. if cls.needs_auth or images is not None:
  68. if api_key is not None:
  69. cls._access_token = api_key
  70. if cls._access_token is None:
  71. try:
  72. cls._access_token, cls._cookies = readHAR(cls.url)
  73. except NoValidHarFileError as h:
  74. debug.log(f"Copilot: {h}")
  75. if has_nodriver:
  76. login_url = os.environ.get("G4F_LOGIN_URL")
  77. if login_url:
  78. yield RequestLogin(cls.label, login_url)
  79. get_running_loop(check_nested=True)
  80. cls._access_token, cls._cookies = asyncio.run(get_access_token_and_cookies(cls.url, proxy))
  81. else:
  82. raise h
  83. yield Parameters(**{"api_key": cls._access_token, "cookies": cls._cookies if isinstance(cls._cookies, dict) else {c.name: c.value for c in cls._cookies}})
  84. websocket_url = f"{websocket_url}&accessToken={quote(cls._access_token)}"
  85. headers = {"authorization": f"Bearer {cls._access_token}"}
  86. with Session(
  87. timeout=timeout,
  88. proxy=proxy,
  89. impersonate="chrome",
  90. headers=headers,
  91. cookies=cls._cookies,
  92. ) as session:
  93. if cls._access_token is not None:
  94. cls._cookies = session.cookies.jar
  95. # if cls._access_token is None:
  96. # try:
  97. # url = "https://copilot.microsoft.com/cl/eus-sc/collect"
  98. # headers = {
  99. # "Accept": "application/x-clarity-gzip",
  100. # "referrer": "https://copilot.microsoft.com/onboarding"
  101. # }
  102. # response = session.post(url, headers=headers, data=get_clarity())
  103. # clarity_token = json.loads(response.text.split(" ", maxsplit=1)[-1])[0]["value"]
  104. # debug.log(f"Copilot: Clarity Token: ...{clarity_token[-12:]}")
  105. # except Exception as e:
  106. # debug.log(f"Copilot: {e}")
  107. # else:
  108. # clarity_token = None
  109. response = session.get("https://copilot.microsoft.com/c/api/user")
  110. raise_for_status(response)
  111. user = response.json().get('firstName')
  112. if user is None:
  113. cls._access_token = None
  114. debug.log(f"Copilot: User: {user or 'null'}")
  115. if conversation is None:
  116. response = session.post(cls.conversation_url)
  117. raise_for_status(response)
  118. conversation_id = response.json().get("id")
  119. conversation = Conversation(conversation_id)
  120. if return_conversation:
  121. yield conversation
  122. if prompt is None:
  123. prompt = format_prompt_max_length(messages, 10000)
  124. debug.log(f"Copilot: Created conversation: {conversation_id}")
  125. else:
  126. conversation_id = conversation.conversation_id
  127. if prompt is None:
  128. prompt = messages[-1]["content"]
  129. debug.log(f"Copilot: Use conversation: {conversation_id}")
  130. uploaded_images = []
  131. if images is not None:
  132. for image, _ in images:
  133. data = to_bytes(image)
  134. response = session.post(
  135. "https://copilot.microsoft.com/c/api/attachments",
  136. headers={"content-type": is_accepted_format(data)},
  137. data=data
  138. )
  139. raise_for_status(response)
  140. uploaded_images.append({"type":"image", "url": response.json().get("url")})
  141. break
  142. wss = session.ws_connect(cls.websocket_url)
  143. # if clarity_token is not None:
  144. # wss.send(json.dumps({
  145. # "event": "challengeResponse",
  146. # "token": clarity_token,
  147. # "method":"clarity"
  148. # }).encode(), CurlWsFlag.TEXT)
  149. wss.send(json.dumps({
  150. "event": "send",
  151. "conversationId": conversation_id,
  152. "content": [*uploaded_images, {
  153. "type": "text",
  154. "text": prompt,
  155. }],
  156. "mode": "chat"
  157. }).encode(), CurlWsFlag.TEXT)
  158. is_started = False
  159. msg = None
  160. image_prompt: str = None
  161. last_msg = None
  162. try:
  163. while True:
  164. try:
  165. msg = wss.recv()[0]
  166. msg = json.loads(msg)
  167. except:
  168. break
  169. last_msg = msg
  170. if msg.get("event") == "appendText":
  171. is_started = True
  172. yield msg.get("text")
  173. elif msg.get("event") == "generatingImage":
  174. image_prompt = msg.get("prompt")
  175. elif msg.get("event") == "imageGenerated":
  176. yield ImageResponse(msg.get("url"), image_prompt, {"preview": msg.get("thumbnailUrl")})
  177. elif msg.get("event") == "done":
  178. break
  179. elif msg.get("event") == "replaceText":
  180. yield msg.get("text")
  181. elif msg.get("event") == "error":
  182. raise RuntimeError(f"Error: {msg}")
  183. elif msg.get("event") not in ["received", "startMessage", "citation", "partCompleted"]:
  184. debug.log(f"Copilot Message: {msg}")
  185. if not is_started:
  186. raise RuntimeError(f"Invalid response: {last_msg}")
  187. finally:
  188. yield Parameters(**{"conversation": conversation.get_dict(), "user": user, "prompt": prompt})
  189. yield Parameters(**{"cookies": {c.name: c.value for c in session.cookies.jar}})
  190. async def get_access_token_and_cookies(url: str, proxy: str = None, target: str = "ChatAI",):
  191. browser = await get_nodriver(proxy=proxy, user_data_dir="copilot")
  192. page = await browser.get(url)
  193. access_token = None
  194. while access_token is None:
  195. access_token = await page.evaluate("""
  196. (() => {
  197. for (var i = 0; i < localStorage.length; i++) {
  198. try {
  199. item = JSON.parse(localStorage.getItem(localStorage.key(i)));
  200. if (item.credentialType == "AccessToken"
  201. && item.expiresOn > Math.floor(Date.now() / 1000)
  202. && item.target.includes("target")) {
  203. return item.secret;
  204. }
  205. } catch(e) {}
  206. }
  207. })()
  208. """.replace('"target"', json.dumps(target)))
  209. if access_token is None:
  210. await asyncio.sleep(1)
  211. cookies = {}
  212. for c in await page.send(nodriver.cdp.network.get_cookies([url])):
  213. cookies[c.name] = c.value
  214. await page.close()
  215. return access_token, cookies
  216. def readHAR(url: str):
  217. api_key = None
  218. cookies = None
  219. for path in get_har_files():
  220. with open(path, 'rb') as file:
  221. try:
  222. harFile = json.loads(file.read())
  223. except json.JSONDecodeError:
  224. # Error: not a HAR file!
  225. continue
  226. for v in harFile['log']['entries']:
  227. if v['request']['url'].startswith(url):
  228. v_headers = get_headers(v)
  229. if "authorization" in v_headers:
  230. api_key = v_headers["authorization"].split(maxsplit=1).pop()
  231. if v['request']['cookies']:
  232. cookies = {c['name']: c['value'] for c in v['request']['cookies']}
  233. if api_key is None:
  234. raise NoValidHarFileError("No access token found in .har files")
  235. return api_key, cookies
  236. def get_clarity() -> bytes:
  237. #{"e":["0.7.58",5,7284,4779,"n59ae4ieqq","aln5en","1upufhz",1,0,0],"a":[[7323,12,65,217,324],[7344,12,65,214,329],[7385,12,65,211,334],[7407,12,65,210,337],[7428,12,65,209,338],[7461,12,65,209,339],[7497,12,65,209,339],[7531,12,65,208,340],[7545,12,65,208,342],[11654,13,65,208,342],[11728,14,65,208,342],[11728,9,65,208,342,17535,19455,0,0,0,"Annehmen",null,"52w7wqv1r.8ovjfyrpu",1],[7284,4,1,393,968,393,968,0,0,231,310,939,0],[12063,0,2,147,3,4,4,18,5,1,10,79,25,15],[12063,36,6,[11938,0]]]}
  238. body = base64.b64decode("H4sIAAAAAAAAA23RwU7DMAwG4HfJ2aqS2E5ibjxH1cMOnQYqYZvUTQPx7vyJRGGAemj01XWcP+9udg+j80MetDhSyrEISc5GrqrtZnmaTydHbrdUnSsWYT2u+8Obo0Ce/IQvaDBmjkwhUlKKIRNHmQgosqEArWPRDQMx90rxeUMPzB1j+UJvwNIxhTvsPcXyX1T+rizE4juK3mEEhpAUg/JvzW1/+U/tB1LATmhqotoiweMea50PLy2vui4LOY3XfD1dwnkor5fn/e18XBFgm6fHjSzZmCyV7d3aRByAEYextaTHEH3i5pgKGVP/s+DScE5PuLKIpW6FnCi1gY3Rbpqmj0/DI/+L7QEAAA==")
  239. return body