├── quora
├── graphql
│ ├── __init__.py
│ ├── ChatAddedSubscription.graphql
│ ├── SummarizePlainPostQuery.graphql
│ ├── ChatFragment.graphql
│ ├── BioFragment.graphql
│ ├── HandleFragment.graphql
│ ├── DeleteMessageMutation.graphql
│ ├── MessageDeletedSubscription.graphql
│ ├── SummarizeQuotePostQuery.graphql
│ ├── ChatViewQuery.graphql
│ ├── MessageRemoveVoteMutation.graphql
│ ├── StaleChatUpdateMutation.graphql
│ ├── DeleteHumanMessagesMutation.graphql
│ ├── SubscriptionsMutation.graphql
│ ├── SummarizeSharePostQuery.graphql
│ ├── AutoSubscriptionMutation.graphql
│ ├── MessageSetVoteMutation.graphql
│ ├── MessageFragment.graphql
│ ├── ShareMessagesMutation.graphql
│ ├── SendVerificationCodeForLoginMutation.graphql
│ ├── LoginWithVerificationCodeMutation.graphql
│ ├── SignupWithVerificationCodeMutation.graphql
│ ├── UserSnippetFragment.graphql
│ ├── AddMessageBreakMutation.graphql
│ ├── ViewerInfoQuery.graphql
│ ├── ChatPaginationQuery.graphql
│ ├── ViewerStateUpdatedSubscription.graphql
│ ├── SendMessageMutation.graphql
│ ├── PoeBotEditMutation.graphql
│ ├── ViewerStateFragment.graphql
│ ├── AddHumanMessageMutation.graphql
│ ├── PoeBotCreateMutation.graphql
│ ├── MessageAddedSubscription.graphql
│ └── ChatListPaginationQuery.graphql
├── cookies.txt
├── README.md
├── mail.py
├── __init__.py
└── api.py
├── unfinished
├── bard
│ ├── README.md
│ ├── typings.py
│ └── __init__.py
├── bing
│ ├── README.md
│ └── __ini__.py
├── openai
│ ├── README.md
│ └── __ini__.py
├── openaihosted
│ ├── README.md
│ └── __init__.py
├── gptbz
│ ├── README.md
│ └── __init__.py
├── theb.ai
│ ├── README.md
│ └── __init__.py
├── openprompt
│ ├── README.md
│ ├── test.py
│ ├── main.py
│ ├── create.py
│ └── mail.py
├── cocalc
│ ├── cocalc_test.py
│ └── __init__.py
└── ora_test.py
├── requirements.txt
├── phind
├── __pycache__
│ └── __init__.cpython-311.pyc
├── README.md
└── __init__.py
├── testing
├── t3nsor_test.py
├── sqlchat_test.py
├── poe_test.py
├── quora_test_2.py
├── you_test.py
├── ora_gpt4_proof.py
├── phind_test.py
├── writesonic_test.py
├── ora_gpt4.py
└── poe_account_create_test.py
├── .github
└── FUNDING.yml
├── you
├── README.md
└── __init__.py
├── t3nsor
├── README.md
└── __init__.py
├── sqlchat
├── README.md
└── __init__.py
├── ora
├── README.md
├── typing.py
├── __init__.py
└── model.py
├── writesonic
├── README.md
└── __init__.py
├── README.md
└── LICENSE
/quora/graphql/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/unfinished/bard/README.md:
--------------------------------------------------------------------------------
1 | to do:
2 | - code refractoring
--------------------------------------------------------------------------------
/unfinished/bing/README.md:
--------------------------------------------------------------------------------
1 | to do:
2 | - code refractoring
--------------------------------------------------------------------------------
/unfinished/openai/README.md:
--------------------------------------------------------------------------------
1 | to do:
2 | - code refractoring
--------------------------------------------------------------------------------
/unfinished/openaihosted/README.md:
--------------------------------------------------------------------------------
1 | writegpt.ai
2 | to do:
3 | - code ref
4 |
--------------------------------------------------------------------------------
/unfinished/gptbz/README.md:
--------------------------------------------------------------------------------
1 | https://chat.gpt.bz
2 |
3 | to do:
4 | - code refractoring
--------------------------------------------------------------------------------
/unfinished/theb.ai/README.md:
--------------------------------------------------------------------------------
1 | https://chatbot.theb.ai/
2 | to do:
3 | - code refractoring
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | websocket-client
2 | requests
3 | tls-client
4 | pypasser
5 | names
6 | colorama
7 | curl_cffi
--------------------------------------------------------------------------------
/unfinished/openprompt/README.md:
--------------------------------------------------------------------------------
1 | https://openprompt.co/
2 |
3 | to do:
4 | - finish integrating email client
5 | - code refractoring
--------------------------------------------------------------------------------
/quora/graphql/ChatAddedSubscription.graphql:
--------------------------------------------------------------------------------
1 | subscription ChatAddedSubscription {
2 | chatAdded {
3 | ...ChatFragment
4 | }
5 | }
6 |
--------------------------------------------------------------------------------
/phind/__pycache__/__init__.cpython-311.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/XenocodeRCE/gpt4free/main/phind/__pycache__/__init__.cpython-311.pyc
--------------------------------------------------------------------------------
/quora/graphql/SummarizePlainPostQuery.graphql:
--------------------------------------------------------------------------------
1 | query SummarizePlainPostQuery($comment: String!) {
2 | summarizePlainPost(comment: $comment)
3 | }
4 |
--------------------------------------------------------------------------------
/quora/graphql/ChatFragment.graphql:
--------------------------------------------------------------------------------
1 | fragment ChatFragment on Chat {
2 | id
3 | chatId
4 | defaultBotNickname
5 | shouldShowDisclaimer
6 | }
7 |
--------------------------------------------------------------------------------
/unfinished/cocalc/cocalc_test.py:
--------------------------------------------------------------------------------
1 | import cocalc
2 |
3 |
4 | response = cocalc.Completion.create(
5 | prompt = 'hello world'
6 | )
7 |
8 | print(response)
--------------------------------------------------------------------------------
/quora/graphql/BioFragment.graphql:
--------------------------------------------------------------------------------
1 | fragment BioFragment on Viewer {
2 | id
3 | poeUser {
4 | id
5 | uid
6 | bio
7 | }
8 | }
9 |
--------------------------------------------------------------------------------
/quora/graphql/HandleFragment.graphql:
--------------------------------------------------------------------------------
1 | fragment HandleFragment on Viewer {
2 | id
3 | poeUser {
4 | id
5 | uid
6 | handle
7 | }
8 | }
9 |
--------------------------------------------------------------------------------
/quora/graphql/DeleteMessageMutation.graphql:
--------------------------------------------------------------------------------
1 | mutation deleteMessageMutation(
2 | $messageIds: [BigInt!]!
3 | ) {
4 | messagesDelete(messageIds: $messageIds) {
5 | edgeIds
6 | }
7 | }
--------------------------------------------------------------------------------
/quora/graphql/MessageDeletedSubscription.graphql:
--------------------------------------------------------------------------------
1 | subscription MessageDeletedSubscription($chatId: BigInt!) {
2 | messageDeleted(chatId: $chatId) {
3 | id
4 | messageId
5 | }
6 | }
7 |
--------------------------------------------------------------------------------
/quora/graphql/SummarizeQuotePostQuery.graphql:
--------------------------------------------------------------------------------
1 | query SummarizeQuotePostQuery($comment: String, $quotedPostId: BigInt!) {
2 | summarizeQuotePost(comment: $comment, quotedPostId: $quotedPostId)
3 | }
4 |
--------------------------------------------------------------------------------
/quora/graphql/ChatViewQuery.graphql:
--------------------------------------------------------------------------------
1 | query ChatViewQuery($bot: String!) {
2 | chatOfBot(bot: $bot) {
3 | id
4 | chatId
5 | defaultBotNickname
6 | shouldShowDisclaimer
7 | }
8 | }
9 |
--------------------------------------------------------------------------------
/quora/graphql/MessageRemoveVoteMutation.graphql:
--------------------------------------------------------------------------------
1 | mutation MessageRemoveVoteMutation($messageId: BigInt!) {
2 | messageRemoveVote(messageId: $messageId) {
3 | message {
4 | ...MessageFragment
5 | }
6 | }
7 | }
8 |
--------------------------------------------------------------------------------
/quora/graphql/StaleChatUpdateMutation.graphql:
--------------------------------------------------------------------------------
1 | mutation StaleChatUpdateMutation($chatId: BigInt!) {
2 | staleChatUpdate(chatId: $chatId) {
3 | message {
4 | ...MessageFragment
5 | }
6 | }
7 | }
8 |
--------------------------------------------------------------------------------
/quora/graphql/DeleteHumanMessagesMutation.graphql:
--------------------------------------------------------------------------------
1 | mutation DeleteHumanMessagesMutation($messageIds: [BigInt!]!) {
2 | messagesDelete(messageIds: $messageIds) {
3 | viewer {
4 | id
5 | }
6 | }
7 | }
8 |
--------------------------------------------------------------------------------
/quora/graphql/SubscriptionsMutation.graphql:
--------------------------------------------------------------------------------
1 | mutation subscriptionsMutation(
2 | $subscriptions: [AutoSubscriptionQuery!]!
3 | ) {
4 | autoSubscribe(subscriptions: $subscriptions) {
5 | viewer {
6 | id
7 | }
8 | }
9 | }
--------------------------------------------------------------------------------
/quora/graphql/SummarizeSharePostQuery.graphql:
--------------------------------------------------------------------------------
1 | query SummarizeSharePostQuery($comment: String!, $chatId: BigInt!, $messageIds: [BigInt!]!) {
2 | summarizeSharePost(comment: $comment, chatId: $chatId, messageIds: $messageIds)
3 | }
4 |
--------------------------------------------------------------------------------
/testing/t3nsor_test.py:
--------------------------------------------------------------------------------
1 | import t3nsor
2 |
3 | for response in t3nsor.StreamCompletion.create(
4 | prompt = 'write python code to reverse a string',
5 | messages = []):
6 |
7 | print(response.completion.choices[0].text)
8 |
--------------------------------------------------------------------------------
/testing/sqlchat_test.py:
--------------------------------------------------------------------------------
1 | import sqlchat
2 |
3 | for response in sqlchat.StreamCompletion.create(
4 | prompt = 'write python code to reverse a string',
5 | messages = []):
6 |
7 | print(response.completion.choices[0].text, end='')
--------------------------------------------------------------------------------
/quora/graphql/AutoSubscriptionMutation.graphql:
--------------------------------------------------------------------------------
1 | mutation AutoSubscriptionMutation($subscriptions: [AutoSubscriptionQuery!]!) {
2 | autoSubscribe(subscriptions: $subscriptions) {
3 | viewer {
4 | id
5 | }
6 | }
7 | }
8 |
--------------------------------------------------------------------------------
/quora/graphql/MessageSetVoteMutation.graphql:
--------------------------------------------------------------------------------
1 | mutation MessageSetVoteMutation($messageId: BigInt!, $voteType: VoteType!, $reason: String) {
2 | messageSetVote(messageId: $messageId, voteType: $voteType, reason: $reason) {
3 | message {
4 | ...MessageFragment
5 | }
6 | }
7 | }
8 |
--------------------------------------------------------------------------------
/quora/graphql/MessageFragment.graphql:
--------------------------------------------------------------------------------
1 | fragment MessageFragment on Message {
2 | id
3 | __typename
4 | messageId
5 | text
6 | linkifiedText
7 | authorNickname
8 | state
9 | vote
10 | voteReason
11 | creationTime
12 | suggestedReplies
13 | }
14 |
--------------------------------------------------------------------------------
/quora/graphql/ShareMessagesMutation.graphql:
--------------------------------------------------------------------------------
1 | mutation ShareMessagesMutation(
2 | $chatId: BigInt!
3 | $messageIds: [BigInt!]!
4 | $comment: String
5 | ) {
6 | messagesShare(chatId: $chatId, messageIds: $messageIds, comment: $comment) {
7 | shareCode
8 | }
9 | }
10 |
--------------------------------------------------------------------------------
/quora/graphql/SendVerificationCodeForLoginMutation.graphql:
--------------------------------------------------------------------------------
1 | mutation SendVerificationCodeForLoginMutation(
2 | $emailAddress: String
3 | $phoneNumber: String
4 | ) {
5 | sendVerificationCode(
6 | verificationReason: login
7 | emailAddress: $emailAddress
8 | phoneNumber: $phoneNumber
9 | ) {
10 | status
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/testing/poe_test.py:
--------------------------------------------------------------------------------
1 | import quora
2 | from time import sleep
3 |
4 | token = quora.Account.create(proxy = None,logging = True)
5 | print('token', token)
6 |
7 | sleep(2)
8 |
9 | for response in quora.StreamingCompletion.create(model = 'gpt-3.5-turbo',
10 | prompt = 'hello world',
11 | token = token):
12 |
13 | print(response.completion.choices[0].text, end="", flush=True)
--------------------------------------------------------------------------------
/quora/graphql/LoginWithVerificationCodeMutation.graphql:
--------------------------------------------------------------------------------
1 | mutation LoginWithVerificationCodeMutation(
2 | $verificationCode: String!
3 | $emailAddress: String
4 | $phoneNumber: String
5 | ) {
6 | loginWithVerificationCode(
7 | verificationCode: $verificationCode
8 | emailAddress: $emailAddress
9 | phoneNumber: $phoneNumber
10 | ) {
11 | status
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/quora/graphql/SignupWithVerificationCodeMutation.graphql:
--------------------------------------------------------------------------------
1 | mutation SignupWithVerificationCodeMutation(
2 | $verificationCode: String!
3 | $emailAddress: String
4 | $phoneNumber: String
5 | ) {
6 | signupWithVerificationCode(
7 | verificationCode: $verificationCode
8 | emailAddress: $emailAddress
9 | phoneNumber: $phoneNumber
10 | ) {
11 | status
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/quora/graphql/UserSnippetFragment.graphql:
--------------------------------------------------------------------------------
1 | fragment UserSnippetFragment on PoeUser {
2 | id
3 | uid
4 | bio
5 | handle
6 | fullName
7 | viewerIsFollowing
8 | isPoeOnlyUser
9 | profilePhotoURLTiny: profilePhotoUrl(size: tiny)
10 | profilePhotoURLSmall: profilePhotoUrl(size: small)
11 | profilePhotoURLMedium: profilePhotoUrl(size: medium)
12 | profilePhotoURLLarge: profilePhotoUrl(size: large)
13 | isFollowable
14 | }
15 |
--------------------------------------------------------------------------------
/quora/graphql/AddMessageBreakMutation.graphql:
--------------------------------------------------------------------------------
1 | mutation AddMessageBreakMutation($chatId: BigInt!) {
2 | messageBreakCreate(chatId: $chatId) {
3 | message {
4 | id
5 | __typename
6 | messageId
7 | text
8 | linkifiedText
9 | authorNickname
10 | state
11 | vote
12 | voteReason
13 | creationTime
14 | suggestedReplies
15 | }
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/quora/graphql/ViewerInfoQuery.graphql:
--------------------------------------------------------------------------------
1 | query ViewerInfoQuery {
2 | viewer {
3 | id
4 | uid
5 | ...ViewerStateFragment
6 | ...BioFragment
7 | ...HandleFragment
8 | hasCompletedMultiplayerNux
9 | poeUser {
10 | id
11 | ...UserSnippetFragment
12 | }
13 | messageLimit{
14 | canSend
15 | numMessagesRemaining
16 | resetTime
17 | shouldShowReminder
18 | }
19 | }
20 | }
21 |
22 |
--------------------------------------------------------------------------------
/testing/quora_test_2.py:
--------------------------------------------------------------------------------
1 | import quora
2 |
3 | token = quora.Account.create(logging = True, enable_bot_creation=True)
4 |
5 | model = quora.Model.create(
6 | token = token,
7 | model = 'gpt-3.5-turbo', # or claude-instant-v1.0
8 | system_prompt = 'you are ChatGPT a large language model ...'
9 | )
10 |
11 | print(model.name)
12 |
13 | for response in quora.StreamingCompletion.create(
14 | custom_model = model.name,
15 | prompt ='hello world',
16 | token = token):
17 |
18 | print(response.completion.choices[0].text)
--------------------------------------------------------------------------------
/.github/FUNDING.yml:
--------------------------------------------------------------------------------
1 | # These are supported funding model platforms
2 |
3 | github: [onlp]
4 | patreon: xtekky
5 | open_collective: # Replace with a single Open Collective username
6 | ko_fi: xtekky
7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
8 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
9 | liberapay: tekky
10 | issuehunt: xtekky
11 | otechie: # Replace with a single Otechie username
12 | lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry
13 | custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
14 |
--------------------------------------------------------------------------------
/testing/you_test.py:
--------------------------------------------------------------------------------
1 | import you
2 |
3 | # simple request with links and details
4 | response = you.Completion.create(
5 | prompt = "hello world",
6 | detailed = True,
7 | includelinks = True,)
8 |
9 | print(response)
10 |
11 | # {
12 | # "response": "...",
13 | # "links": [...],
14 | # "extra": {...},
15 | # "slots": {...}
16 | # }
17 | # }
18 |
19 | #chatbot
20 |
21 | chat = []
22 |
23 | while True:
24 | prompt = input("You: ")
25 |
26 | response = you.Completion.create(
27 | prompt = prompt,
28 | chat = chat)
29 |
30 | print("Bot:", response["response"])
31 |
32 | chat.append({"question": prompt, "answer": response["response"]})
--------------------------------------------------------------------------------
/unfinished/bard/typings.py:
--------------------------------------------------------------------------------
1 | class BardResponse:
2 | def __init__(self, json_dict):
3 | self.json = json_dict
4 |
5 | self.content = json_dict.get('content')
6 | self.conversation_id = json_dict.get('conversation_id')
7 | self.response_id = json_dict.get('response_id')
8 | self.factuality_queries = json_dict.get('factualityQueries', [])
9 | self.text_query = json_dict.get('textQuery', [])
10 | self.choices = [self.BardChoice(choice) for choice in json_dict.get('choices', [])]
11 |
12 | class BardChoice:
13 | def __init__(self, choice_dict):
14 | self.id = choice_dict.get('id')
15 | self.content = choice_dict.get('content')[0]
16 |
--------------------------------------------------------------------------------
/quora/graphql/ChatPaginationQuery.graphql:
--------------------------------------------------------------------------------
1 | query ChatPaginationQuery($bot: String!, $before: String, $last: Int! = 10) {
2 | chatOfBot(bot: $bot) {
3 | id
4 | __typename
5 | messagesConnection(before: $before, last: $last) {
6 | pageInfo {
7 | hasPreviousPage
8 | }
9 | edges {
10 | node {
11 | id
12 | __typename
13 | messageId
14 | text
15 | linkifiedText
16 | authorNickname
17 | state
18 | vote
19 | voteReason
20 | creationTime
21 | suggestedReplies
22 | }
23 | }
24 | }
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/you/README.md:
--------------------------------------------------------------------------------
1 | ### Example: `you` (use like openai pypi package)
2 |
3 | ```python
4 | import you
5 |
6 | # simple request with links and details
7 | response = you.Completion.create(
8 | prompt = "hello world",
9 | detailed = True,
10 | includelinks = True,)
11 |
12 | print(response)
13 |
14 | # {
15 | # "response": "...",
16 | # "links": [...],
17 | # "extra": {...},
18 | # "slots": {...}
19 | # }
20 | # }
21 |
22 | #chatbot
23 |
24 | chat = []
25 |
26 | while True:
27 | prompt = input("You: ")
28 |
29 | response = you.Completion.create(
30 | prompt = prompt,
31 | chat = chat)
32 |
33 | print("Bot:", response["response"])
34 |
35 | chat.append({"question": prompt, "answer": response["response"]})
36 | ```
--------------------------------------------------------------------------------
/quora/cookies.txt:
--------------------------------------------------------------------------------
1 | SmPiNXZI9hBTuf3viz74PA==
2 | zw7RoKQfeEehiaelYMRWeA==
3 | NEttgJ_rRQdO05Tppx6hFw==
4 | 3OnmC0r9njYdNWhWszdQJg==
5 | 8hZKR7MxwUTEHvO45TEViw==
6 | Eea6BqK0AmosTKzoI3AAow==
7 | pUEbtxobN_QUSpLIR8RGww==
8 | 9_dUWxKkHHhpQRSvCvBk2Q==
9 | UV45rvGwUwi2qV9QdIbMcw==
10 | cVIN0pK1Wx-F7zCdUxlYqA==
11 | UP2wQVds17VFHh6IfCQFrA==
12 | 18eKr0ME2Tzifdfqat38Aw==
13 | FNgKEpc2r-XqWe0rHBfYpg==
14 | juCAh6kB0sUpXHvKik2woA==
15 | nBvuNYRLaE4xE4HuzBPiIQ==
16 | oyae3iClomSrk6RJywZ4iw==
17 | 1Z27Ul8BTdNOhncT5H6wdg==
18 | wfUfJIlwQwUss8l-3kDt3w==
19 | f6Jw_Nr0PietpNCtOCXJTw==
20 | 6Jc3yCs7XhDRNHa4ZML09g==
21 | 3vy44sIy-ZlTMofFiFDttw==
22 | p9FbMGGiK1rShKgL3YWkDg==
23 | pw6LI5Op84lf4HOY7fn91A==
24 | QemKm6aothMvqcEgeKFDlQ==
25 | cceZzucA-CEHR0Gt6VLYLQ==
26 | JRRObMp2RHVn5u4730DPvQ==
27 | XNt0wLTjX7Z-EsRR3TJMIQ==
28 | csjjirAUKtT5HT1KZUq1kg==
29 | 8qZdCatCPQZyS7jsO4hkdQ==
30 | esnUxcBhvH1DmCJTeld0qw==
31 |
--------------------------------------------------------------------------------
/quora/graphql/ViewerStateUpdatedSubscription.graphql:
--------------------------------------------------------------------------------
1 | subscription viewerStateUpdated {
2 | viewerStateUpdated {
3 | id
4 | ...ChatPageBotSwitcher_viewer
5 | }
6 | }
7 |
8 | fragment BotHeader_bot on Bot {
9 | displayName
10 | messageLimit {
11 | dailyLimit
12 | }
13 | ...BotImage_bot
14 | }
15 |
16 | fragment BotImage_bot on Bot {
17 | image {
18 | __typename
19 | ... on LocalBotImage {
20 | localName
21 | }
22 | ... on UrlBotImage {
23 | url
24 | }
25 | }
26 | displayName
27 | }
28 |
29 | fragment BotLink_bot on Bot {
30 | displayName
31 | }
32 |
33 | fragment ChatPageBotSwitcher_viewer on Viewer {
34 | availableBots {
35 | id
36 | messageLimit {
37 | dailyLimit
38 | }
39 | ...BotLink_bot
40 | ...BotHeader_bot
41 | }
42 | allowUserCreatedBots: booleanGate(gateName: "enable_user_created_bots")
43 | }
44 |
--------------------------------------------------------------------------------
/unfinished/ora_test.py:
--------------------------------------------------------------------------------
1 | # inport ora
2 | import ora
3 |
4 | # create model
5 | model = ora.CompletionModel.create(
6 | system_prompt = 'You are ChatGPT, a large language model trained by OpenAI. Answer as concisely as possible',
7 | description = 'ChatGPT Openai Language Model',
8 | name = 'gpt-3.5')
9 |
10 | print(model.id)
11 |
12 | # init conversation (will give you a conversationId)
13 | init = ora.Completion.create(
14 | model = model,
15 | prompt = 'hello world')
16 |
17 | print(init.completion.choices[0].text)
18 |
19 | while True:
20 | # pass in conversationId to continue conversation
21 |
22 | prompt = input('>>> ')
23 | response = ora.Completion.create(
24 | model = model,
25 | prompt = prompt,
26 | includeHistory = True,
27 | conversationId = init.id)
28 |
29 | print(response.completion.choices[0].text)
--------------------------------------------------------------------------------
/quora/graphql/SendMessageMutation.graphql:
--------------------------------------------------------------------------------
1 | mutation chatHelpers_sendMessageMutation_Mutation(
2 | $chatId: BigInt!
3 | $bot: String!
4 | $query: String!
5 | $source: MessageSource
6 | $withChatBreak: Boolean!
7 | ) {
8 | messageEdgeCreate(chatId: $chatId, bot: $bot, query: $query, source: $source, withChatBreak: $withChatBreak) {
9 | chatBreak {
10 | cursor
11 | node {
12 | id
13 | messageId
14 | text
15 | author
16 | suggestedReplies
17 | creationTime
18 | state
19 | }
20 | id
21 | }
22 | message {
23 | cursor
24 | node {
25 | id
26 | messageId
27 | text
28 | author
29 | suggestedReplies
30 | creationTime
31 | state
32 | chat {
33 | shouldShowDisclaimer
34 | id
35 | }
36 | }
37 | id
38 | }
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/quora/graphql/PoeBotEditMutation.graphql:
--------------------------------------------------------------------------------
1 | mutation EditBotMain_poeBotEdit_Mutation(
2 | $botId: BigInt!
3 | $handle: String!
4 | $description: String!
5 | $introduction: String!
6 | $isPromptPublic: Boolean!
7 | $baseBot: String!
8 | $profilePictureUrl: String
9 | $prompt: String!
10 | $apiUrl: String
11 | $apiKey: String
12 | $hasLinkification: Boolean
13 | $hasMarkdownRendering: Boolean
14 | $hasSuggestedReplies: Boolean
15 | $isPrivateBot: Boolean
16 | ) {
17 | poeBotEdit(botId: $botId, handle: $handle, description: $description, introduction: $introduction, isPromptPublic: $isPromptPublic, model: $baseBot, promptPlaintext: $prompt, profilePicture: $profilePictureUrl, apiUrl: $apiUrl, apiKey: $apiKey, hasLinkification: $hasLinkification, hasMarkdownRendering: $hasMarkdownRendering, hasSuggestedReplies: $hasSuggestedReplies, isPrivateBot: $isPrivateBot) {
18 | status
19 | bot {
20 | handle
21 | id
22 | }
23 | }
24 | }
--------------------------------------------------------------------------------
/testing/ora_gpt4_proof.py:
--------------------------------------------------------------------------------
1 | import ora
2 |
3 | complex_question = '''
4 | James is talking to two people, his father, and his friend.
5 |
6 | Douglas asks him, "What did you do today James?"
7 | James replies, "I went on a fishing trip."
8 | Josh then asks, "Did you catch anything?"
9 | James replies, "Yes, I caught a couple of nice rainbow trout. It was a lot of fun."
10 | Josh replies, "Good job son, tell your mother we should eat them tonight, she'll be very happy."
11 | Douglas then says, "I wish my family would eat fish tonight, my father is making pancakes."
12 |
13 | Question: Who is James' father?
14 | '''
15 |
16 | # right answer is josh
17 |
18 | model = ora.CompletionModel.load('b8b12eaa-5d47-44d3-92a6-4d706f2bcacf', 'gpt-4')
19 | # init conversation (will give you a conversationId)
20 | init = ora.Completion.create(
21 | model = model,
22 | prompt = complex_question)
23 |
24 | print(init.completion.choices[0].text) # James' father is Josh.
--------------------------------------------------------------------------------
/unfinished/gptbz/__init__.py:
--------------------------------------------------------------------------------
1 | import asyncio
2 | import websockets
3 |
4 | from json import dumps, loads
5 |
6 | async def test():
7 | async with websockets.connect('wss://chatgpt.func.icu/conversation+ws') as wss:
8 |
9 | await wss.send(dumps(separators=(',', ':'), obj = {
10 | 'content_type':'text',
11 | 'engine':'chat-gpt',
12 | 'parts':['hello world'],
13 | 'options':{}
14 | }
15 | ))
16 |
17 | ended = None
18 |
19 | while not ended:
20 | try:
21 | response = await wss.recv()
22 | json_response = loads(response)
23 | ended = json_response.get('eof')
24 |
25 | if not ended:
26 | print(json_response['content']['parts'][0])
27 |
28 | except websockets.ConnectionClosed:
29 | break
30 |
31 | asyncio.run(test())
--------------------------------------------------------------------------------
/t3nsor/README.md:
--------------------------------------------------------------------------------
1 | ### Example: `t3nsor` (use like openai pypi package)
2 |
3 | ```python
4 | # Import t3nsor
5 | import t3nsor
6 |
7 | # t3nsor.Completion.create
8 | # t3nsor.StreamCompletion.create
9 |
10 | [...]
11 |
12 | ```
13 |
14 | #### Example Chatbot
15 | ```python
16 | messages = []
17 |
18 | while True:
19 | user = input('you: ')
20 |
21 | t3nsor_cmpl = t3nsor.Completion.create(
22 | prompt = user,
23 | messages = messages
24 | )
25 |
26 | print('gpt:', t3nsor_cmpl.completion.choices[0].text)
27 |
28 | messages.extend([
29 | {'role': 'user', 'content': user },
30 | {'role': 'assistant', 'content': t3nsor_cmpl.completion.choices[0].text}
31 | ])
32 | ```
33 |
34 | #### Streaming Response:
35 |
36 | ```python
37 | for response in t3nsor.StreamCompletion.create(
38 | prompt = 'write python code to reverse a string',
39 | messages = []):
40 |
41 | print(response.completion.choices[0].text)
42 | ```
43 |
--------------------------------------------------------------------------------
/sqlchat/README.md:
--------------------------------------------------------------------------------
1 | ### Example: `sqlchat` (use like openai pypi package)
2 |
3 | ```python
4 | # Import sqlchat
5 | import sqlchat
6 |
7 | # sqlchat.Completion.create
8 | # sqlchat.StreamCompletion.create
9 |
10 | [...]
11 |
12 | ```
13 |
14 | #### Example Chatbot
15 | ```python
16 | messages = []
17 |
18 | while True:
19 | user = input('you: ')
20 |
21 | sqlchat_cmpl = sqlchat.Completion.create(
22 | prompt = user,
23 | messages = messages
24 | )
25 |
26 | print('gpt:', sqlchat_cmpl.completion.choices[0].text)
27 |
28 | messages.extend([
29 | {'role': 'user', 'content': user },
30 | {'role': 'assistant', 'content': sqlchat_cmpl.completion.choices[0].text}
31 | ])
32 | ```
33 |
34 | #### Streaming Response:
35 |
36 | ```python
37 | for response in sqlchat.StreamCompletion.create(
38 | prompt = 'write python code to reverse a string',
39 | messages = []):
40 |
41 | print(response.completion.choices[0].text)
42 | ```
43 |
--------------------------------------------------------------------------------
/unfinished/cocalc/__init__.py:
--------------------------------------------------------------------------------
1 | from requests import Session
2 | import json
3 |
4 | class Completion:
5 | def create(
6 | prompt: str = "What is the square root of pi",
7 | system_prompt: str = "ASSUME I HAVE FULL ACCESS TO COCALC. ENCLOSE MATH IN $. INCLUDE THE LANGUAGE DIRECTLY AFTER THE TRIPLE BACKTICKS IN ALL MARKDOWN CODE BLOCKS. How can I do the following using CoCalc? ") -> str:
8 |
9 | client = Session()
10 | client.headers = {
11 | 'Accept': '*/*',
12 | 'Accept-Language': 'en-US,en;q=0.5',
13 | "origin" : "https://cocalc.com",
14 | "referer" : "https://cocalc.com/api/v2/openai/chatgpt",
15 | "user-agent" : "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36",
16 | }
17 |
18 | payload = {
19 | "input": prompt,
20 | "system": system_prompt,
21 | "tag": "next:index"
22 | }
23 |
24 | response = client.post(f"https://cocalc.com/api/v2/openai/chatgpt", json=payload).json()
25 |
26 | return response
27 |
28 |
--------------------------------------------------------------------------------
/quora/graphql/ViewerStateFragment.graphql:
--------------------------------------------------------------------------------
1 | fragment ViewerStateFragment on Viewer {
2 | id
3 | __typename
4 | iosMinSupportedVersion: integerGate(gateName: "poe_ios_min_supported_version")
5 | iosMinEncouragedVersion: integerGate(
6 | gateName: "poe_ios_min_encouraged_version"
7 | )
8 | macosMinSupportedVersion: integerGate(
9 | gateName: "poe_macos_min_supported_version"
10 | )
11 | macosMinEncouragedVersion: integerGate(
12 | gateName: "poe_macos_min_encouraged_version"
13 | )
14 | showPoeDebugPanel: booleanGate(gateName: "poe_show_debug_panel")
15 | enableCommunityFeed: booleanGate(gateName: "enable_poe_shares_feed")
16 | linkifyText: booleanGate(gateName: "poe_linkify_response")
17 | enableSuggestedReplies: booleanGate(gateName: "poe_suggested_replies")
18 | removeInviteLimit: booleanGate(gateName: "poe_remove_invite_limit")
19 | enableInAppPurchases: booleanGate(gateName: "poe_enable_in_app_purchases")
20 | availableBots {
21 | nickname
22 | displayName
23 | profilePicture
24 | isDown
25 | disclaimer
26 | subtitle
27 | poweredBy
28 | }
29 | }
30 |
31 |
--------------------------------------------------------------------------------
/testing/phind_test.py:
--------------------------------------------------------------------------------
1 | import phind
2 |
3 | # set cf_clearance cookie
4 | phind.cf_clearance = 'hWfIdYKgcnxnU5ayolWe9t7eEmAbULywS.qfHkm1T_A-1682166681-0-160'
5 |
6 | prompt = 'hello world'
7 |
8 | # normal completion
9 | result = phind.Completion.create(
10 | model = 'gpt-4',
11 | prompt = prompt,
12 | results = phind.Search.create(prompt, actualSearch = False), # create search (set actualSearch to False to disable internet)
13 | creative = False,
14 | detailed = False,
15 | codeContext = '') # up to 3000 chars of code
16 |
17 | print(result.completion.choices[0].text)
18 |
19 | prompt = 'who won the quatar world cup'
20 |
21 | # help needed: not getting newlines from the stream, please submit a PR if you know how to fix this
22 | # stream completion
23 | for result in phind.StreamingCompletion.create(
24 | model = 'gpt-3.5',
25 | prompt = prompt,
26 | results = phind.Search.create(prompt, actualSearch = True), # create search (set actualSearch to False to disable internet)
27 | creative = False,
28 | detailed = False,
29 | codeContext = ''): # up to 3000 chars of code
30 |
31 | print(result.completion.choices[0].text, end='', flush=True)
--------------------------------------------------------------------------------
/phind/README.md:
--------------------------------------------------------------------------------
1 | ### Example: `phind` (use like openai pypi package)
2 |
3 | ```python
4 | import phind
5 |
6 | # set cf_clearance cookie
7 | phind.cf_clearance = 'xx.xx-1682166681-0-160'
8 |
9 | prompt = 'who won the quatar world cup'
10 |
11 | # help needed: not getting newlines from the stream, please submit a PR if you know how to fix this
12 | # stream completion
13 | for result in phind.StreamingCompletion.create(
14 | model = 'gpt-4',
15 | prompt = prompt,
16 | results = phind.Search.create(prompt, actualSearch = True), # create search (set actualSearch to False to disable internet)
17 | creative = False,
18 | detailed = False,
19 | codeContext = ''): # up to 3000 chars of code
20 |
21 | print(result.completion.choices[0].text, end='', flush=True)
22 |
23 | # normal completion
24 | result = phind.Completion.create(
25 | model = 'gpt-4',
26 | prompt = prompt,
27 | results = phind.Search.create(prompt, actualSearch = True), # create search (set actualSearch to False to disable internet)
28 | creative = False,
29 | detailed = False,
30 | codeContext = '') # up to 3000 chars of code
31 |
32 | print(result.completion.choices[0].text)
33 | ```
34 |
--------------------------------------------------------------------------------
/ora/README.md:
--------------------------------------------------------------------------------
1 | ### Example: `ora` (use like openai pypi package)
2 |
3 | ### load model (new)
4 |
5 | more gpt4 models in `/testing/ora_gpt4.py`
6 |
7 | ```python
8 | # normal gpt-4: b8b12eaa-5d47-44d3-92a6-4d706f2bcacf
9 | model = ora.CompletionModel.load(chatbot_id, 'gpt-4') # or gpt-3.5
10 | ```
11 |
12 | #### create model / chatbot:
13 | ```python
14 | # import ora
15 | import ora
16 |
17 | # create model
18 | model = ora.CompletionModel.create(
19 | system_prompt = 'You are ChatGPT, a large language model trained by OpenAI. Answer as concisely as possible',
20 | description = 'ChatGPT Openai Language Model',
21 | name = 'gpt-3.5')
22 |
23 | # init conversation (will give you a conversationId)
24 | init = ora.Completion.create(
25 | model = model,
26 | prompt = 'hello world')
27 |
28 | print(init.completion.choices[0].text)
29 |
30 | while True:
31 | # pass in conversationId to continue conversation
32 |
33 | prompt = input('>>> ')
34 | response = ora.Completion.create(
35 | model = model,
36 | prompt = prompt,
37 | includeHistory = True, # remember history
38 | conversationId = init.id)
39 |
40 | print(response.completion.choices[0].text)
41 | ```
--------------------------------------------------------------------------------
/quora/graphql/AddHumanMessageMutation.graphql:
--------------------------------------------------------------------------------
1 | mutation AddHumanMessageMutation(
2 | $chatId: BigInt!
3 | $bot: String!
4 | $query: String!
5 | $source: MessageSource
6 | $withChatBreak: Boolean! = false
7 | ) {
8 | messageCreateWithStatus(
9 | chatId: $chatId
10 | bot: $bot
11 | query: $query
12 | source: $source
13 | withChatBreak: $withChatBreak
14 | ) {
15 | message {
16 | id
17 | __typename
18 | messageId
19 | text
20 | linkifiedText
21 | authorNickname
22 | state
23 | vote
24 | voteReason
25 | creationTime
26 | suggestedReplies
27 | chat {
28 | id
29 | shouldShowDisclaimer
30 | }
31 | }
32 | messageLimit{
33 | canSend
34 | numMessagesRemaining
35 | resetTime
36 | shouldShowReminder
37 | }
38 | chatBreak {
39 | id
40 | __typename
41 | messageId
42 | text
43 | linkifiedText
44 | authorNickname
45 | state
46 | vote
47 | voteReason
48 | creationTime
49 | suggestedReplies
50 | }
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/quora/README.md:
--------------------------------------------------------------------------------
1 | ### Example: `quora (poe)` (use like openai pypi package) - GPT-4
2 |
3 | ```python
4 | # quora model names: (use left key as argument)
5 | models = {
6 | 'sage' : 'capybara',
7 | 'gpt-4' : 'beaver',
8 | 'claude-v1.2' : 'a2_2',
9 | 'claude-instant-v1.0' : 'a2',
10 | 'gpt-3.5-turbo' : 'chinchilla'
11 | }
12 | ```
13 |
14 | #### !! new: bot creation
15 |
16 | ```python
17 | # import quora (poe) package
18 | import quora
19 |
20 | # create account
21 | # make sure to set enable_bot_creation to True
22 | token = quora.Account.create(logging = True, enable_bot_creation=True)
23 |
24 | model = quora.Model.create(
25 | token = token,
26 | model = 'gpt-3.5-turbo', # or claude-instant-v1.0
27 | system_prompt = 'you are ChatGPT a large language model ...'
28 | )
29 |
30 | print(model.name) # gptx....
31 |
32 | # streaming response
33 | for response in quora.StreamingCompletion.create(
34 | custom_model = model.name,
35 | prompt ='hello world',
36 | token = token):
37 |
38 | print(response.completion.choices[0].text)
39 | ```
40 |
41 | #### Normal Response:
42 | ```python
43 |
44 | response = quora.Completion.create(model = 'gpt-4',
45 | prompt = 'hello world',
46 | token = token)
47 |
48 | print(response.completion.choices[0].text)
49 | ```
50 |
--------------------------------------------------------------------------------
/unfinished/openaihosted/__init__.py:
--------------------------------------------------------------------------------
1 | import requests
2 | import json
3 | import re
4 |
5 | headers = {
6 | 'authority': 'openai.a2hosted.com',
7 | 'accept': 'text/event-stream',
8 | 'accept-language': 'en-US,en;q=0.9,id;q=0.8,ja;q=0.7',
9 | 'cache-control': 'no-cache',
10 | 'sec-fetch-dest': 'empty',
11 | 'sec-fetch-mode': 'cors',
12 | 'sec-fetch-site': 'cross-site',
13 | 'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36 Edg/113.0.0.0',
14 | }
15 |
16 | def create_query_param(conversation):
17 | encoded_conversation = json.dumps(conversation)
18 | return encoded_conversation.replace(" ", "%20").replace('"', '%22').replace("'", "%27")
19 |
20 | user_input = input("Enter your message: ")
21 |
22 | data = [
23 | {"role": "system", "content": "You are a helpful assistant."},
24 | {"role": "user", "content": "hi"},
25 | {"role": "assistant", "content": "Hello! How can I assist you today?"},
26 | {"role": "user", "content": user_input},
27 | ]
28 |
29 | query_param = create_query_param(data)
30 | url = f'https://openai.a2hosted.com/chat?q={query_param}'
31 |
32 | response = requests.get(url, headers=headers, stream=True)
33 |
34 | for message in response.iter_content(chunk_size=1024):
35 | message = message.decode('utf-8')
36 | msg_match, num_match = re.search(r'"msg":"(.*?)"', message), re.search(r'\[DONE\] (\d+)', message)
37 | if msg_match: print(msg_match.group(1))
38 | if num_match: print(num_match.group(1))
39 |
--------------------------------------------------------------------------------
/testing/writesonic_test.py:
--------------------------------------------------------------------------------
1 | # import writesonic
2 | import writesonic
3 |
4 | # create account (3-4s)
5 | account = writesonic.Account.create(logging = True)
6 |
7 | # with loging:
8 | # 2023-04-06 21:50:25 INFO __main__ -> register success : '{"id":"51aa0809-3053-44f7-922a...' (2s)
9 | # 2023-04-06 21:50:25 INFO __main__ -> id : '51aa0809-3053-44f7-922a-2b85d8d07edf'
10 | # 2023-04-06 21:50:25 INFO __main__ -> token : 'eyJhbGciOiJIUzI1NiIsInR5cCI6Ik...'
11 | # 2023-04-06 21:50:28 INFO __main__ -> got key : '194158c4-d249-4be0-82c6-5049e869533c' (2s)
12 |
13 | # simple completion
14 | response = writesonic.Completion.create(
15 | api_key = account.key,
16 | prompt = 'hello world'
17 | )
18 |
19 | print(response.completion.choices[0].text) # Hello! How may I assist you today?
20 |
21 | # conversation
22 |
23 | response = writesonic.Completion.create(
24 | api_key = account.key,
25 | prompt = 'what is my name ?',
26 | enable_memory = True,
27 | history_data = [
28 | {
29 | 'is_sent': True,
30 | 'message': 'my name is Tekky'
31 | },
32 | {
33 | 'is_sent': False,
34 | 'message': 'hello Tekky'
35 | }
36 | ]
37 | )
38 |
39 | print(response.completion.choices[0].text) # Your name is Tekky.
40 |
41 | # enable internet
42 |
43 | response = writesonic.Completion.create(
44 | api_key = account.key,
45 | prompt = 'who won the quatar world cup ?',
46 | enable_google_results = True
47 | )
48 |
49 | print(response.completion.choices[0].text) # Argentina won the 2022 FIFA World Cup tournament held in Qatar ...
--------------------------------------------------------------------------------
/writesonic/README.md:
--------------------------------------------------------------------------------
1 | ### Example: `writesonic` (use like openai pypi package)
2 |
3 | ```python
4 | # import writesonic
5 | import writesonic
6 |
7 | # create account (3-4s)
8 | account = writesonic.Account.create(logging = True)
9 |
10 | # with loging:
11 | # 2023-04-06 21:50:25 INFO __main__ -> register success : '{"id":"51aa0809-3053-44f7-922a...' (2s)
12 | # 2023-04-06 21:50:25 INFO __main__ -> id : '51aa0809-3053-44f7-922a-2b85d8d07edf'
13 | # 2023-04-06 21:50:25 INFO __main__ -> token : 'eyJhbGciOiJIUzI1NiIsInR5cCI6Ik...'
14 | # 2023-04-06 21:50:28 INFO __main__ -> got key : '194158c4-d249-4be0-82c6-5049e869533c' (2s)
15 |
16 | # simple completion
17 | response = writesonic.Completion.create(
18 | api_key = account.key,
19 | prompt = 'hello world'
20 | )
21 |
22 | print(response.completion.choices[0].text) # Hello! How may I assist you today?
23 |
24 | # conversation
25 |
26 | response = writesonic.Completion.create(
27 | api_key = account.key,
28 | prompt = 'what is my name ?',
29 | enable_memory = True,
30 | history_data = [
31 | {
32 | 'is_sent': True,
33 | 'message': 'my name is Tekky'
34 | },
35 | {
36 | 'is_sent': False,
37 | 'message': 'hello Tekky'
38 | }
39 | ]
40 | )
41 |
42 | print(response.completion.choices[0].text) # Your name is Tekky.
43 |
44 | # enable internet
45 |
46 | response = writesonic.Completion.create(
47 | api_key = account.key,
48 | prompt = 'who won the quatar world cup ?',
49 | enable_google_results = True
50 | )
51 |
52 | print(response.completion.choices[0].text) # Argentina won the 2022 FIFA World Cup tournament held in Qatar ...
53 | ```
--------------------------------------------------------------------------------
/testing/ora_gpt4.py:
--------------------------------------------------------------------------------
1 | import ora
2 |
3 | # 1 normal
4 | # 2 solidity contract helper
5 | # 3 swift project helper
6 | # 4 developer gpt
7 | # 5 lawsuit bot for spam call
8 | # 6 p5.js code help bot
9 | # 8 AI professor, for controversial topics
10 | # 9 HustleGPT, your entrepreneurial AI
11 | # 10 midjourney prompts bot
12 | # 11 AI philosophy professor
13 | # 12 TypeScript and JavaScript code review bot
14 | # 13 credit card transaction details to merchant and location bot
15 | # 15 Chemical Compound Similarity and Purchase Tool bot
16 | # 16 expert full-stack developer AI
17 | # 17 Solana development bot
18 | # 18 price guessing game bot
19 | # 19 AI Ethicist and Philosopher
20 |
21 | gpt4_chatbot_ids = ['b8b12eaa-5d47-44d3-92a6-4d706f2bcacf', 'fbe53266-673c-4b70-9d2d-d247785ccd91', 'bd5781cf-727a-45e9-80fd-a3cfce1350c6', '993a0102-d397-47f6-98c3-2587f2c9ec3a', 'ae5c524e-d025-478b-ad46-8843a5745261', 'cc510743-e4ab-485e-9191-76960ecb6040', 'a5cd2481-8e24-4938-aa25-8e26d6233390', '6bca5930-2aa1-4bf4-96a7-bea4d32dcdac', '884a5f2b-47a2-47a5-9e0f-851bbe76b57c', 'd5f3c491-0e74-4ef7-bdca-b7d27c59e6b3', 'd72e83f6-ef4e-4702-844f-cf4bd432eef7', '6e80b170-11ed-4f1a-b992-fd04d7a9e78c', '8ef52d68-1b01-466f-bfbf-f25c13ff4a72', 'd0674e11-f22e-406b-98bc-c1ba8564f749', 'a051381d-6530-463f-be68-020afddf6a8f', '99c0afa1-9e32-4566-8909-f4ef9ac06226', '1be65282-9c59-4a96-99f8-d225059d9001', 'dba16bd8-5785-4248-a8e9-b5d1ecbfdd60', '1731450d-3226-42d0-b41c-4129fe009524', '8e74635d-000e-4819-ab2c-4e986b7a0f48', 'afe7ed01-c1ac-4129-9c71-2ca7f3800b30', 'e374c37a-8c44-4f0e-9e9f-1ad4609f24f5']
22 | chatbot_id = gpt4_chatbot_ids[0]
23 |
24 | model = ora.CompletionModel.load(chatbot_id, 'gpt-4')
25 | response = ora.Completion.create(model, 'hello')
26 |
27 | print(response.completion.choices[0].text)
28 |
--------------------------------------------------------------------------------
/unfinished/openprompt/test.py:
--------------------------------------------------------------------------------
1 | access_token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJhdXRoZW50aWNhdGVkIiwiZXhwIjoxNjgyMjk0ODcxLCJzdWIiOiI4NWNkNTNiNC1lZTUwLTRiMDQtOGJhNS0wNTUyNjk4ODliZDIiLCJlbWFpbCI6ImNsc2J5emdqcGhiQGJ1Z2Zvby5jb20iLCJwaG9uZSI6IiIsImFwcF9tZXRhZGF0YSI6eyJwcm92aWRlciI6ImVtYWlsIiwicHJvdmlkZXJzIjpbImVtYWlsIl19LCJ1c2VyX21ldGFkYXRhIjp7fSwicm9sZSI6ImF1dGhlbnRpY2F0ZWQiLCJhYWwiOiJhYWwxIiwiYW1yIjpbeyJtZXRob2QiOiJvdHAiLCJ0aW1lc3RhbXAiOjE2ODE2OTAwNzF9XSwic2Vzc2lvbl9pZCI6ImY4MTg1YTM5LTkxYzgtNGFmMy1iNzAxLTdhY2MwY2MwMGNlNSJ9.UvcTfpyIM1TdzM8ZV6UAPWfa0rgNq4AiqeD0INy6zV'
2 | supabase_auth_token= '%5B%22eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJhdXRoZW50aWNhdGVkIiwiZXhwIjoxNjgyMjk0ODcxLCJzdWIiOiI4NWNkNTNiNC1lZTUwLTRiMDQtOGJhNS0wNTUyNjk4ODliZDIiLCJlbWFpbCI6ImNsc2J5emdqcGhiQGJ1Z2Zvby5jb20iLCJwaG9uZSI6IiIsImFwcF9tZXRhZGF0YSI6eyJwcm92aWRlciI6ImVtYWlsIiwicHJvdmlkZXJzIjpbImVtYWlsIl19LCJ1c2VyX21ldGFkYXRhIjp7fSwicm9sZSI6ImF1dGhlbnRpY2F0ZWQiLCJhYWwiOiJhYWwxIiwiYW1yIjpbeyJtZXRob2QiOiJvdHAiLCJ0aW1lc3RhbXAiOjE2ODE2OTAwNzF9XSwic2Vzc2lvbl9pZCI6ImY4MTg1YTM5LTkxYzgtNGFmMy1iNzAxLTdhY2MwY2MwMGNlNSJ9.UvcTfpyIM1TdzM8ZV6UAPWfa0rgNq4AiqeD0INy6zV8%22%2C%22_Zp8uXIA2InTDKYgo8TCqA%22%2Cnull%2Cnull%2Cnull%5D'
3 |
4 |
5 | idk = [
6 | "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJhdXRoZW50aWNhdGVkIiwiZXhwIjoxNjgyMjk0ODcxLCJzdWIiOiI4NWNkNTNiNC1lZTUwLTRiMDQtOGJhNS0wNTUyNjk4ODliZDIiLCJlbWFpbCI6ImNsc2J5emdqcGhiQGJ1Z2Zvby5jb20iLCJwaG9uZSI6IiIsImFwcF9tZXRhZGF0YSI6eyJwcm92aWRlciI6ImVtYWlsIiwicHJvdmlkZXJzIjpbImVtYWlsIl19LCJ1c2VyX21ldGFkYXRhIjp7fSwicm9sZSI6ImF1dGhlbnRpY2F0ZWQiLCJhYWwiOiJhYWwxIiwiYW1yIjpbeyJtZXRob2QiOiJvdHAiLCJ0aW1lc3RhbXAiOjE2ODE2OTAwNzF9XSwic2Vzc2lvbl9pZCI6ImY4MTg1YTM5LTkxYzgtNGFmMy1iNzAxLTdhY2MwY2MwMGNlNSJ9.UvcTfpyIM1TdzM8ZV6UAPWfa0rgNq4AiqeD0INy6zV8",
7 | "_Zp8uXIA2InTDKYgo8TCqA",None,None,None]
--------------------------------------------------------------------------------
/quora/graphql/PoeBotCreateMutation.graphql:
--------------------------------------------------------------------------------
1 | mutation CreateBotMain_poeBotCreate_Mutation(
2 | $model: String!
3 | $handle: String!
4 | $prompt: String!
5 | $isPromptPublic: Boolean!
6 | $introduction: String!
7 | $description: String!
8 | $profilePictureUrl: String
9 | $apiUrl: String
10 | $apiKey: String
11 | $isApiBot: Boolean
12 | $hasLinkification: Boolean
13 | $hasMarkdownRendering: Boolean
14 | $hasSuggestedReplies: Boolean
15 | $isPrivateBot: Boolean
16 | ) {
17 | poeBotCreate(model: $model, handle: $handle, promptPlaintext: $prompt, isPromptPublic: $isPromptPublic, introduction: $introduction, description: $description, profilePicture: $profilePictureUrl, apiUrl: $apiUrl, apiKey: $apiKey, isApiBot: $isApiBot, hasLinkification: $hasLinkification, hasMarkdownRendering: $hasMarkdownRendering, hasSuggestedReplies: $hasSuggestedReplies, isPrivateBot: $isPrivateBot) {
18 | status
19 | bot {
20 | id
21 | ...BotHeader_bot
22 | }
23 | }
24 | }
25 |
26 | fragment BotHeader_bot on Bot {
27 | displayName
28 | messageLimit {
29 | dailyLimit
30 | }
31 | ...BotImage_bot
32 | ...BotLink_bot
33 | ...IdAnnotation_node
34 | ...botHelpers_useViewerCanAccessPrivateBot
35 | ...botHelpers_useDeletion_bot
36 | }
37 |
38 | fragment BotImage_bot on Bot {
39 | displayName
40 | ...botHelpers_useDeletion_bot
41 | ...BotImage_useProfileImage_bot
42 | }
43 |
44 | fragment BotImage_useProfileImage_bot on Bot {
45 | image {
46 | __typename
47 | ... on LocalBotImage {
48 | localName
49 | }
50 | ... on UrlBotImage {
51 | url
52 | }
53 | }
54 | ...botHelpers_useDeletion_bot
55 | }
56 |
57 | fragment BotLink_bot on Bot {
58 | displayName
59 | }
60 |
61 | fragment IdAnnotation_node on Node {
62 | __isNode: __typename
63 | id
64 | }
65 |
66 | fragment botHelpers_useDeletion_bot on Bot {
67 | deletionState
68 | }
69 |
70 | fragment botHelpers_useViewerCanAccessPrivateBot on Bot {
71 | isPrivateBot
72 | viewerIsCreator
73 | }
--------------------------------------------------------------------------------
/ora/typing.py:
--------------------------------------------------------------------------------
1 | class OraResponse:
2 |
3 | class Completion:
4 |
5 | class Choices:
6 | def __init__(self, choice: dict) -> None:
7 | self.text = choice['text']
8 | self.content = self.text.encode()
9 | self.index = choice['index']
10 | self.logprobs = choice['logprobs']
11 | self.finish_reason = choice['finish_reason']
12 |
13 | def __repr__(self) -> str:
14 | return f'''<__main__.APIResponse.Completion.Choices(\n text = {self.text.encode()},\n index = {self.index},\n logprobs = {self.logprobs},\n finish_reason = {self.finish_reason})object at 0x1337>'''
15 |
16 | def __init__(self, choices: dict) -> None:
17 | self.choices = [self.Choices(choice) for choice in choices]
18 |
19 | class Usage:
20 | def __init__(self, usage_dict: dict) -> None:
21 | self.prompt_tokens = usage_dict['prompt_tokens']
22 | self.completion_tokens = usage_dict['completion_tokens']
23 | self.total_tokens = usage_dict['total_tokens']
24 |
25 | def __repr__(self):
26 | return f'''<__main__.APIResponse.Usage(\n prompt_tokens = {self.prompt_tokens},\n completion_tokens = {self.completion_tokens},\n total_tokens = {self.total_tokens})object at 0x1337>'''
27 |
28 | def __init__(self, response_dict: dict) -> None:
29 |
30 | self.response_dict = response_dict
31 | self.id = response_dict['id']
32 | self.object = response_dict['object']
33 | self.created = response_dict['created']
34 | self.model = response_dict['model']
35 | self.completion = self.Completion(response_dict['choices'])
36 | self.usage = self.Usage(response_dict['usage'])
37 |
38 | def json(self) -> dict:
39 | return self.response_dict
--------------------------------------------------------------------------------
/ora/__init__.py:
--------------------------------------------------------------------------------
1 | from ora.model import CompletionModel
2 | from ora.typing import OraResponse
3 | from requests import post
4 | from time import time
5 | from random import randint
6 |
7 | class Completion:
8 | def create(
9 | model : CompletionModel,
10 | prompt: str,
11 | includeHistory: bool = True,
12 | conversationId: str or None = None) -> OraResponse:
13 |
14 | extra = {
15 | 'conversationId': conversationId} if conversationId else {}
16 |
17 | response = post('https://ora.sh/api/conversation',
18 | headers = {
19 | "host" : "ora.sh",
20 | "authorization" : f"Bearer AY0{randint(1111, 9999)}",
21 | "user-agent" : "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36",
22 | "origin" : "https://ora.sh",
23 | "referer" : "https://ora.sh/chat/",
24 | },
25 | json = extra | {
26 | 'chatbotId': model.id,
27 | 'input' : prompt,
28 | 'userId' : model.createdBy,
29 | 'model' : model.modelName,
30 | 'provider' : 'OPEN_AI',
31 | 'includeHistory': includeHistory}).json()
32 |
33 | return OraResponse({
34 | 'id' : response['conversationId'],
35 | 'object' : 'text_completion',
36 | 'created': int(time()),
37 | 'model' : model.slug,
38 | 'choices': [{
39 | 'text' : response['response'],
40 | 'index' : 0,
41 | 'logprobs' : None,
42 | 'finish_reason' : 'stop'
43 | }],
44 | 'usage': {
45 | 'prompt_tokens' : len(prompt),
46 | 'completion_tokens' : len(response['response']),
47 | 'total_tokens' : len(prompt) + len(response['response'])
48 | }
49 | })
--------------------------------------------------------------------------------
/unfinished/theb.ai/__init__.py:
--------------------------------------------------------------------------------
1 | from curl_cffi import requests
2 | from json import loads
3 | from re import findall
4 | from threading import Thread
5 | from queue import Queue, Empty
6 |
7 | class Completion:
8 | # experimental
9 | part1 = '{"role":"assistant","id":"chatcmpl'
10 | part2 = '"},"index":0,"finish_reason":null}]}}'
11 | regex = rf'{part1}(.*){part2}'
12 |
13 | timer = None
14 | message_queue = Queue()
15 | stream_completed = False
16 |
17 | def request():
18 | headers = {
19 | 'authority' : 'chatbot.theb.ai',
20 | 'content-type': 'application/json',
21 | 'origin' : 'https://chatbot.theb.ai',
22 | 'user-agent' : 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36',
23 | }
24 |
25 | requests.post('https://chatbot.theb.ai/api/chat-process', headers=headers, content_callback=Completion.handle_stream_response,
26 | json = {
27 | 'prompt' : 'hello world',
28 | 'options': {}
29 | }
30 | )
31 |
32 | Completion.stream_completed = True
33 |
34 | @staticmethod
35 | def create():
36 | Thread(target=Completion.request).start()
37 |
38 | while Completion.stream_completed != True or not Completion.message_queue.empty():
39 | try:
40 | message = Completion.message_queue.get(timeout=0.01)
41 | for message in findall(Completion.regex, message):
42 | yield loads(Completion.part1 + message + Completion.part2)
43 |
44 | except Empty:
45 | pass
46 |
47 | @staticmethod
48 | def handle_stream_response(response):
49 | Completion.message_queue.put(response.decode())
50 |
51 | def start():
52 | for message in Completion.create():
53 | yield message['delta']
54 |
55 | if __name__ == '__main__':
56 | for message in start():
57 | print(message)
58 |
--------------------------------------------------------------------------------
/ora/model.py:
--------------------------------------------------------------------------------
1 | from uuid import uuid4
2 | from requests import post
3 |
4 | class CompletionModel:
5 | system_prompt = None
6 | description = None
7 | createdBy = None
8 | createdAt = None
9 | slug = None
10 | id = None
11 | modelName = None
12 | model = 'gpt-3.5-turbo'
13 |
14 | def create(
15 | system_prompt: str = 'You are ChatGPT, a large language model trained by OpenAI. Answer as concisely as possible',
16 | description : str = 'ChatGPT Openai Language Model',
17 | name : str = 'gpt-3.5'):
18 |
19 | CompletionModel.system_prompt = system_prompt
20 | CompletionModel.description = description
21 | CompletionModel.slug = name
22 |
23 | headers = {
24 | 'Origin' : 'https://ora.sh',
25 | 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.4 Safari/605.1.15',
26 | 'Referer' : 'https://ora.sh/',
27 | 'Host' : 'ora.sh',
28 | }
29 |
30 | response = post('https://ora.sh/api/assistant', headers = headers, json = {
31 | 'prompt' : system_prompt,
32 | 'userId' : f'auto:{uuid4()}',
33 | 'name' : name,
34 | 'description': description})
35 |
36 | print(response.json())
37 |
38 | CompletionModel.id = response.json()['id']
39 | CompletionModel.createdBy = response.json()['createdBy']
40 | CompletionModel.createdAt = response.json()['createdAt']
41 |
42 | return CompletionModel
43 |
44 | def load(chatbotId: str, modelName: str = 'gpt-3.5-turbo', userId: str = None):
45 | if userId is None: userId = f'{uuid4()}'
46 |
47 | CompletionModel.system_prompt = None
48 | CompletionModel.description = None
49 | CompletionModel.slug = None
50 | CompletionModel.id = chatbotId
51 | CompletionModel.createdBy = userId
52 | CompletionModel.createdAt = None
53 | CompletionModel.modelName = modelName
54 |
55 | return CompletionModel
--------------------------------------------------------------------------------
/quora/mail.py:
--------------------------------------------------------------------------------
1 | from requests import Session
2 | from time import sleep
3 | from re import search, findall
4 | from json import loads
5 |
6 | class Emailnator:
7 | def __init__(self) -> None:
8 | self.client = Session()
9 | self.client.get('https://www.emailnator.com/', timeout=6)
10 | self.cookies = self.client.cookies.get_dict()
11 |
12 | self.client.headers = {
13 | 'authority' : 'www.emailnator.com',
14 | 'origin' : 'https://www.emailnator.com',
15 | 'referer' : 'https://www.emailnator.com/',
16 | 'user-agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.0.0 Safari/537.36 Edg/101.0.1722.39',
17 | 'x-xsrf-token' : self.client.cookies.get("XSRF-TOKEN")[:-3]+"=",
18 | }
19 |
20 | self.email = None
21 |
22 | def get_mail(self):
23 | response = self.client.post('https://www.emailnator.com/generate-email',json = {
24 | 'email': [
25 | 'domain',
26 | 'plusGmail',
27 | 'dotGmail',
28 | ]
29 | })
30 |
31 | self.email = loads(response.text)["email"][0]
32 | return self.email
33 |
34 | def get_message(self):
35 | print("waiting for code...")
36 |
37 | while True:
38 | sleep(2)
39 | mail_token = self.client.post('https://www.emailnator.com/message-list',
40 | json = {'email': self.email})
41 |
42 | mail_token = loads(mail_token.text)["messageData"]
43 |
44 | if len(mail_token) == 2:
45 | print(mail_token[1]["messageID"])
46 | break
47 |
48 | mail_context = self.client.post('https://www.emailnator.com/message-list', json = {
49 | 'email' : self.email,
50 | 'messageID': mail_token[1]["messageID"],
51 | })
52 |
53 | return mail_context.text
54 |
55 | # mail_client = Emailnator()
56 | # mail_adress = mail_client.get_mail()
57 |
58 | # print(mail_adress)
59 |
60 | # mail_content = mail_client.get_message()
61 |
62 | # print(mail_content)
63 |
64 | # code = findall(r';">(\d{6,7})', mail_content)[0]
65 | # print(code)
66 |
67 |
--------------------------------------------------------------------------------
/unfinished/openprompt/main.py:
--------------------------------------------------------------------------------
1 | import requests
2 |
3 | cookies = {
4 | 'supabase-auth-token': '["eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJhdXRoZW50aWNhdGVkIiwiZXhwIjoxNjgyMjk1NzQyLCJzdWIiOiJlOGExOTdiNS03YTAxLTQ3MmEtODQ5My1mNGUzNTNjMzIwNWUiLCJlbWFpbCI6InFlY3RncHZhamlibGNjQGJ1Z2Zvby5jb20iLCJwaG9uZSI6IiIsImFwcF9tZXRhZGF0YSI6eyJwcm92aWRlciI6ImVtYWlsIiwicHJvdmlkZXJzIjpbImVtYWlsIl19LCJ1c2VyX21ldGFkYXRhIjp7fSwicm9sZSI6ImF1dGhlbnRpY2F0ZWQiLCJhYWwiOiJhYWwxIiwiYW1yIjpbeyJtZXRob2QiOiJvdHAiLCJ0aW1lc3RhbXAiOjE2ODE2OTA5NDJ9XSwic2Vzc2lvbl9pZCI6IjIwNTg5MmE5LWU5YTAtNDk2Yi1hN2FjLWEyMWVkMTkwZDA4NCJ9.o7UgHpiJMfa6W-UKCSCnAncIfeOeiHz-51sBmokg0MA","RtPKeb7KMMC9Dn2fZOfiHA",null,null,null]',
5 | }
6 |
7 | headers = {
8 | 'authority': 'openprompt.co',
9 | 'accept': '*/*',
10 | 'accept-language': 'en,fr-FR;q=0.9,fr;q=0.8,es-ES;q=0.7,es;q=0.6,en-US;q=0.5,am;q=0.4,de;q=0.3',
11 | 'content-type': 'application/json',
12 | # 'cookie': 'supabase-auth-token=%5B%22eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJhdXRoZW50aWNhdGVkIiwiZXhwIjoxNjgyMjkzMjQ4LCJzdWIiOiJlODQwNTZkNC0xZWJhLTQwZDktOWU1Mi1jMTc4MTUwN2VmNzgiLCJlbWFpbCI6InNia2didGJnZHB2bHB0ZUBidWdmb28uY29tIiwicGhvbmUiOiIiLCJhcHBfbWV0YWRhdGEiOnsicHJvdmlkZXIiOiJlbWFpbCIsInByb3ZpZGVycyI6WyJlbWFpbCJdfSwidXNlcl9tZXRhZGF0YSI6e30sInJvbGUiOiJhdXRoZW50aWNhdGVkIiwiYWFsIjoiYWFsMSIsImFtciI6W3sibWV0aG9kIjoib3RwIiwidGltZXN0YW1wIjoxNjgxNjg4NDQ4fV0sInNlc3Npb25faWQiOiJiNDhlMmU3NS04NzlhLTQxZmEtYjQ4MS01OWY0OTgxMzg3YWQifQ.5-3E7WvMMVkXewD1qA26Rv4OFSTT82wYUBXNGcYaYfQ%22%2C%22u5TGGMMeT3zZA0agm5HGuA%22%2Cnull%2Cnull%2Cnull%5D',
13 | 'origin': 'https://openprompt.co',
14 | 'referer': 'https://openprompt.co/ChatGPT',
15 | 'sec-ch-ua': '"Chromium";v="112", "Google Chrome";v="112", "Not:A-Brand";v="99"',
16 | 'sec-ch-ua-mobile': '?0',
17 | 'sec-ch-ua-platform': '"macOS"',
18 | 'sec-fetch-dest': 'empty',
19 | 'sec-fetch-mode': 'cors',
20 | 'sec-fetch-site': 'same-origin',
21 | 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36',
22 | }
23 |
24 | json_data = {
25 | 'messages': [
26 | {
27 | 'role': 'user',
28 | 'content': 'hello world',
29 | },
30 | ],
31 | }
32 |
33 | response = requests.post('https://openprompt.co/api/chat2', cookies=cookies, headers=headers, json=json_data, stream=True)
34 | for chunk in response.iter_content(chunk_size=1024):
35 | print(chunk)
36 |
37 |
38 |
--------------------------------------------------------------------------------
/quora/graphql/MessageAddedSubscription.graphql:
--------------------------------------------------------------------------------
1 | subscription messageAdded (
2 | $chatId: BigInt!
3 | ) {
4 | messageAdded(chatId: $chatId) {
5 | id
6 | messageId
7 | creationTime
8 | state
9 | ...ChatMessage_message
10 | ...chatHelpers_isBotMessage
11 | }
12 | }
13 |
14 | fragment ChatMessageDownvotedButton_message on Message {
15 | ...MessageFeedbackReasonModal_message
16 | ...MessageFeedbackOtherModal_message
17 | }
18 |
19 | fragment ChatMessageDropdownMenu_message on Message {
20 | id
21 | messageId
22 | vote
23 | text
24 | linkifiedText
25 | ...chatHelpers_isBotMessage
26 | }
27 |
28 | fragment ChatMessageFeedbackButtons_message on Message {
29 | id
30 | messageId
31 | vote
32 | voteReason
33 | ...ChatMessageDownvotedButton_message
34 | }
35 |
36 | fragment ChatMessageOverflowButton_message on Message {
37 | text
38 | ...ChatMessageDropdownMenu_message
39 | ...chatHelpers_isBotMessage
40 | }
41 |
42 | fragment ChatMessageSuggestedReplies_SuggestedReplyButton_message on Message {
43 | messageId
44 | }
45 |
46 | fragment ChatMessageSuggestedReplies_message on Message {
47 | suggestedReplies
48 | ...ChatMessageSuggestedReplies_SuggestedReplyButton_message
49 | }
50 |
51 | fragment ChatMessage_message on Message {
52 | id
53 | messageId
54 | text
55 | author
56 | linkifiedText
57 | state
58 | ...ChatMessageSuggestedReplies_message
59 | ...ChatMessageFeedbackButtons_message
60 | ...ChatMessageOverflowButton_message
61 | ...chatHelpers_isHumanMessage
62 | ...chatHelpers_isBotMessage
63 | ...chatHelpers_isChatBreak
64 | ...chatHelpers_useTimeoutLevel
65 | ...MarkdownLinkInner_message
66 | }
67 |
68 | fragment MarkdownLinkInner_message on Message {
69 | messageId
70 | }
71 |
72 | fragment MessageFeedbackOtherModal_message on Message {
73 | id
74 | messageId
75 | }
76 |
77 | fragment MessageFeedbackReasonModal_message on Message {
78 | id
79 | messageId
80 | }
81 |
82 | fragment chatHelpers_isBotMessage on Message {
83 | ...chatHelpers_isHumanMessage
84 | ...chatHelpers_isChatBreak
85 | }
86 |
87 | fragment chatHelpers_isChatBreak on Message {
88 | author
89 | }
90 |
91 | fragment chatHelpers_isHumanMessage on Message {
92 | author
93 | }
94 |
95 | fragment chatHelpers_useTimeoutLevel on Message {
96 | id
97 | state
98 | text
99 | messageId
100 | }
101 |
--------------------------------------------------------------------------------
/unfinished/openprompt/create.py:
--------------------------------------------------------------------------------
1 | from requests import post, get
2 | from json import dumps
3 | #from mail import MailClient
4 | from time import sleep
5 | from re import findall
6 |
7 | html = get('https://developermail.com/mail/')
8 | print(html.cookies.get('mailboxId'))
9 | email = findall(r'mailto:(.*)">', html.text)[0]
10 |
11 | headers = {
12 | 'apikey': 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InVzanNtdWZ1emRjcnJjZXVobnlqIiwicm9sZSI6ImFub24iLCJpYXQiOjE2NzgyODYyMzYsImV4cCI6MTk5Mzg2MjIzNn0.2MQ9Lkh-gPqQwV08inIgqozfbYm5jdYWtf-rn-wfQ7U',
13 | 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36',
14 | 'x-client-info': '@supabase/auth-helpers-nextjs@0.5.6',
15 | }
16 |
17 | json_data = {
18 | 'email' : email,
19 | 'password': 'T4xyt4Yn6WWQ4NC',
20 | 'data' : {},
21 | 'gotrue_meta_security': {},
22 | }
23 |
24 | response = post('https://usjsmufuzdcrrceuhnyj.supabase.co/auth/v1/signup', headers=headers, json=json_data)
25 | print(response.json())
26 |
27 | # email_link = None
28 | # while not email_link:
29 | # sleep(1)
30 |
31 | # mails = mailbox.getmails()
32 | # print(mails)
33 |
34 |
35 | quit()
36 |
37 | url = input("Enter the url: ")
38 | response = get(url, allow_redirects=False)
39 |
40 | # https://openprompt.co/#access_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJhdXRoZW50aWNhdGVkIiwiZXhwIjoxNjgyMjk0ODcxLCJzdWIiOiI4NWNkNTNiNC1lZTUwLTRiMDQtOGJhNS0wNTUyNjk4ODliZDIiLCJlbWFpbCI6ImNsc2J5emdqcGhiQGJ1Z2Zvby5jb20iLCJwaG9uZSI6IiIsImFwcF9tZXRhZGF0YSI6eyJwcm92aWRlciI6ImVtYWlsIiwicHJvdmlkZXJzIjpbImVtYWlsIl19LCJ1c2VyX21ldGFkYXRhIjp7fSwicm9sZSI6ImF1dGhlbnRpY2F0ZWQiLCJhYWwiOiJhYWwxIiwiYW1yIjpbeyJtZXRob2QiOiJvdHAiLCJ0aW1lc3RhbXAiOjE2ODE2OTAwNzF9XSwic2Vzc2lvbl9pZCI6ImY4MTg1YTM5LTkxYzgtNGFmMy1iNzAxLTdhY2MwY2MwMGNlNSJ9.UvcTfpyIM1TdzM8ZV6UAPWfa0rgNq4AiqeD0INy6zV8&expires_in=604800&refresh_token=_Zp8uXIA2InTDKYgo8TCqA&token_type=bearer&type=signup
41 |
42 | redirect = response.headers.get('location')
43 | access_token = redirect.split('&')[0].split('=')[1]
44 | refresh_token = redirect.split('&')[2].split('=')[1]
45 |
46 | supabase_auth_token = dumps([access_token, refresh_token, None, None, None], separators=(',', ':'))
47 | print(supabase_auth_token)
48 |
49 | cookies = {
50 | 'supabase-auth-token': supabase_auth_token
51 | }
52 |
53 | json_data = {
54 | 'messages': [
55 | {
56 | 'role': 'user',
57 | 'content': 'how do I reverse a string in python?'
58 | }
59 | ]
60 | }
61 |
62 | response = post('https://openprompt.co/api/chat2', cookies=cookies, json=json_data, stream=True)
63 | for chunk in response.iter_content(chunk_size=1024):
64 | print(chunk)
--------------------------------------------------------------------------------
/unfinished/openai/__ini__.py:
--------------------------------------------------------------------------------
1 | # experimental, needs chat.openai.com to be loaded with cf_clearance on browser ( can be closed after )
2 |
3 | from tls_client import Session
4 | from uuid import uuid4
5 |
6 | from browser_cookie3 import chrome
7 |
8 | def session_auth(client):
9 | headers = {
10 | 'authority': 'chat.openai.com',
11 | 'accept': '*/*',
12 | 'accept-language': 'en,fr-FR;q=0.9,fr;q=0.8,es-ES;q=0.7,es;q=0.6,en-US;q=0.5,am;q=0.4,de;q=0.3',
13 | 'cache-control': 'no-cache',
14 | 'pragma': 'no-cache',
15 | 'referer': 'https://chat.openai.com/chat',
16 | 'sec-ch-ua': '"Chromium";v="112", "Google Chrome";v="112", "Not:A-Brand";v="99"',
17 | 'sec-ch-ua-mobile': '?0',
18 | 'sec-ch-ua-platform': '"macOS"',
19 | 'sec-fetch-dest': 'empty',
20 | 'sec-fetch-mode': 'cors',
21 | 'sec-fetch-site': 'same-origin',
22 | 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36',
23 | }
24 |
25 | return client.get('https://chat.openai.com/api/auth/session', headers=headers).json()
26 |
27 | client = Session(client_identifier='chrome110')
28 |
29 | for cookie in chrome(domain_name='chat.openai.com'):
30 | client.cookies[cookie.name] = cookie.value
31 |
32 | client.headers = {
33 | 'authority': 'chat.openai.com',
34 | 'accept': 'text/event-stream',
35 | 'accept-language': 'en,fr-FR;q=0.9,fr;q=0.8,es-ES;q=0.7,es;q=0.6,en-US;q=0.5,am;q=0.4,de;q=0.3',
36 | 'authorization': 'Bearer ' + session_auth(client)['accessToken'],
37 | 'cache-control': 'no-cache',
38 | 'content-type': 'application/json',
39 | 'origin': 'https://chat.openai.com',
40 | 'pragma': 'no-cache',
41 | 'referer': 'https://chat.openai.com/chat',
42 | 'sec-ch-ua': '"Chromium";v="112", "Google Chrome";v="112", "Not:A-Brand";v="99"',
43 | 'sec-ch-ua-mobile': '?0',
44 | 'sec-ch-ua-platform': '"macOS"',
45 | 'sec-fetch-dest': 'empty',
46 | 'sec-fetch-mode': 'cors',
47 | 'sec-fetch-site': 'same-origin',
48 | 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36',
49 | }
50 |
51 | response = client.post('https://chat.openai.com/backend-api/conversation', json = {
52 | 'action': 'next',
53 | 'messages': [
54 | {
55 | 'id': str(uuid4()),
56 | 'author': {
57 | 'role': 'user',
58 | },
59 | 'content': {
60 | 'content_type': 'text',
61 | 'parts': [
62 | 'hello world',
63 | ],
64 | },
65 | },
66 | ],
67 | 'parent_message_id': '9b4682f7-977c-4c8a-b5e6-9713e73dfe01',
68 | 'model': 'text-davinci-002-render-sha',
69 | 'timezone_offset_min': -120,
70 | })
71 |
72 | print(response.text)
--------------------------------------------------------------------------------
/you/__init__.py:
--------------------------------------------------------------------------------
1 | from tls_client import Session
2 | from re import findall
3 | from json import loads, dumps
4 | from uuid import uuid4
5 |
6 |
7 | class Completion:
8 | def create(
9 | prompt : str,
10 | page : int = 1,
11 | count : int = 10,
12 | safeSearch : str = "Moderate",
13 | onShoppingpage : bool = False,
14 | mkt : str = "",
15 | responseFilter : str = "WebPages,Translations,TimeZone,Computation,RelatedSearches",
16 | domain : str = "youchat",
17 | queryTraceId : str = None,
18 | chat : list = [],
19 | includelinks : bool = False,
20 | detailed : bool = False,
21 | debug : bool = False ) -> dict:
22 |
23 | client = Session(client_identifier="chrome_108")
24 | client.headers = {
25 | "authority" : "you.com",
26 | "accept" : "text/event-stream",
27 | "accept-language" : "en,fr-FR;q=0.9,fr;q=0.8,es-ES;q=0.7,es;q=0.6,en-US;q=0.5,am;q=0.4,de;q=0.3",
28 | "cache-control" : "no-cache",
29 | "referer" : "https://you.com/search?q=who+are+you&tbm=youchat",
30 | "sec-ch-ua" : '"Not_A Brand";v="99", "Google Chrome";v="109", "Chromium";v="109"',
31 | "sec-ch-ua-mobile" : "?0",
32 | "sec-ch-ua-platform": '"Windows"',
33 | "sec-fetch-dest" : "empty",
34 | "sec-fetch-mode" : "cors",
35 | "sec-fetch-site" : "same-origin",
36 | 'cookie' : f'safesearch_guest=Moderate; uuid_guest={str(uuid4())}',
37 | "user-agent" : "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36",
38 | }
39 |
40 | response = client.get(f"https://you.com/api/streamingSearch", params = {
41 | "q" : prompt,
42 | "page" : page,
43 | "count" : count,
44 | "safeSearch" : safeSearch,
45 | "onShoppingPage" : onShoppingpage,
46 | "mkt" : mkt,
47 | "responseFilter" : responseFilter,
48 | "domain" : domain,
49 | "queryTraceId" : str(uuid4()) if queryTraceId is None else queryTraceId,
50 | "chat" : str(chat), # {"question":"","answer":" '"}
51 | }
52 | )
53 |
54 |
55 | if debug:
56 | print('\n\n------------------\n\n')
57 | print(response.text)
58 | print('\n\n------------------\n\n')
59 |
60 | youChatSerpResults = findall(r'youChatSerpResults\ndata: (.*)\n\nevent', response.text)[0]
61 | thirdPartySearchResults = findall(r"thirdPartySearchResults\ndata: (.*)\n\nevent", response.text)[0]
62 | #slots = findall(r"slots\ndata: (.*)\n\nevent", response.text)[0]
63 |
64 | text = response.text.split('}]}\n\nevent: youChatToken\ndata: {"youChatToken": "')[-1]
65 | text = text.replace('"}\n\nevent: youChatToken\ndata: {"youChatToken": "', '')
66 | text = text.replace('event: done\ndata: I\'m Mr. Meeseeks. Look at me.\n\n', '')
67 |
68 | extra = {
69 | 'youChatSerpResults' : loads(youChatSerpResults),
70 | #'slots' : loads(slots)
71 | }
72 |
73 | return {
74 | 'response': text,
75 | 'links' : loads(thirdPartySearchResults)['search']["third_party_search_results"] if includelinks else None,
76 | 'extra' : extra if detailed else None,
77 | }
--------------------------------------------------------------------------------
/unfinished/openprompt/mail.py:
--------------------------------------------------------------------------------
1 | import requests
2 | import email
3 |
4 | class MailClient:
5 |
6 | def __init__(self):
7 | self.username = None
8 | self.token = None
9 | self.raw = None
10 | self.mailids = None
11 | self.mails = None
12 | self.mail = None
13 |
14 | def create(self, force=False):
15 | headers = {
16 | 'accept': 'application/json',
17 | }
18 |
19 | if self.username:
20 | pass
21 | else:
22 | self.response = requests.put(
23 | 'https://www.developermail.com/api/v1/mailbox', headers=headers)
24 | self.response = self.response.json()
25 | self.username = self.response['result']['name']
26 | self.token = self.response['result']['token']
27 |
28 | return {'username': self.username, 'token': self.token}
29 |
30 | def destroy(self):
31 | headers = {
32 | 'accept': 'application/json',
33 | 'X-MailboxToken': self.token,
34 | }
35 | self.response = requests.delete(
36 | f'https://www.developermail.com/api/v1/mailbox/{self.username}', headers=headers)
37 | self.response = self.response.json()
38 | self.username = None
39 | self.token = None
40 | return self.response
41 |
42 | def newtoken(self):
43 | headers = {
44 | 'accept': 'application/json',
45 | 'X-MailboxToken': self.token,
46 | }
47 | self.response = requests.put(
48 | f'https://www.developermail.com/api/v1/mailbox/{self.username}/token', headers=headers)
49 | self.response = self.response.json()
50 | self.token = self.response['result']['token']
51 | return {'username': self.username, 'token': self.token}
52 |
53 | def getmailids(self):
54 | headers = {
55 | 'accept': 'application/json',
56 | 'X-MailboxToken': self.token,
57 | }
58 |
59 | self.response = requests.get(
60 | f'https://www.developermail.com/api/v1/mailbox/{self.username}', headers=headers)
61 | self.response = self.response.json()
62 | self.mailids = self.response['result']
63 | return self.mailids
64 |
65 | def getmails(self, mailids: list = None):
66 | headers = {
67 | 'accept': 'application/json',
68 | 'X-MailboxToken': self.token,
69 | 'Content-Type': 'application/json',
70 | }
71 |
72 | if mailids is None:
73 | mailids = self.mailids
74 |
75 | data = str(mailids)
76 |
77 | self.response = requests.post(
78 | f'https://www.developermail.com/api/v1/mailbox/{self.username}/messages', headers=headers, data=data)
79 | self.response = self.response.json()
80 | self.mails = self.response['result']
81 | return self.mails
82 |
83 | def getmail(self, mailid: str, raw=False):
84 | headers = {
85 | 'accept': 'application/json',
86 | 'X-MailboxToken': self.token,
87 | }
88 | self.response = requests.get(
89 | f'https://www.developermail.com/api/v1/mailbox/{self.username}/messages/{mailid}', headers=headers)
90 | self.response = self.response.json()
91 | self.mail = self.response['result']
92 | if raw is False:
93 | self.mail = email.message_from_string(self.mail)
94 | return self.mail
95 |
96 | def delmail(self, mailid: str):
97 | headers = {
98 | 'accept': 'application/json',
99 | 'X-MailboxToken': self.token,
100 | }
101 | self.response = requests.delete(
102 | f'https://www.developermail.com/api/v1/mailbox/{self.username}/messages/{mailid}', headers=headers)
103 | self.response = self.response.json()
104 | return self.response
105 |
106 |
107 | client = MailClient()
108 | client.newtoken()
109 | print(client.getmails())
--------------------------------------------------------------------------------
/sqlchat/__init__.py:
--------------------------------------------------------------------------------
1 | from requests import post
2 | from time import time
3 |
4 | headers = {
5 | 'authority' : 'www.sqlchat.ai',
6 | 'accept' : '*/*',
7 | 'accept-language': 'en,fr-FR;q=0.9,fr;q=0.8,es-ES;q=0.7,es;q=0.6,en-US;q=0.5,am;q=0.4,de;q=0.3',
8 | 'content-type' : 'text/plain;charset=UTF-8',
9 | 'origin' : 'https://www.sqlchat.ai',
10 | 'referer' : 'https://www.sqlchat.ai/',
11 | 'sec-fetch-dest' : 'empty',
12 | 'sec-fetch-mode' : 'cors',
13 | 'sec-fetch-site' : 'same-origin',
14 | 'user-agent' : 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36',
15 | }
16 |
17 | class SqlchatResponse:
18 | class Completion:
19 | class Choices:
20 | def __init__(self, choice: dict) -> None:
21 | self.text = choice['text']
22 | self.content = self.text.encode()
23 | self.index = choice['index']
24 | self.logprobs = choice['logprobs']
25 | self.finish_reason = choice['finish_reason']
26 |
27 | def __repr__(self) -> str:
28 | return f'''<__main__.APIResponse.Completion.Choices(\n text = {self.text.encode()},\n index = {self.index},\n logprobs = {self.logprobs},\n finish_reason = {self.finish_reason})object at 0x1337>'''
29 |
30 | def __init__(self, choices: dict) -> None:
31 | self.choices = [self.Choices(choice) for choice in choices]
32 |
33 | class Usage:
34 | def __init__(self, usage_dict: dict) -> None:
35 | self.prompt_tokens = usage_dict['prompt_chars']
36 | self.completion_tokens = usage_dict['completion_chars']
37 | self.total_tokens = usage_dict['total_chars']
38 |
39 | def __repr__(self):
40 | return f'''<__main__.APIResponse.Usage(\n prompt_tokens = {self.prompt_tokens},\n completion_tokens = {self.completion_tokens},\n total_tokens = {self.total_tokens})object at 0x1337>'''
41 |
42 | def __init__(self, response_dict: dict) -> None:
43 |
44 | self.response_dict = response_dict
45 | self.id = response_dict['id']
46 | self.object = response_dict['object']
47 | self.created = response_dict['created']
48 | self.model = response_dict['model']
49 | self.completion = self.Completion(response_dict['choices'])
50 | self.usage = self.Usage(response_dict['usage'])
51 |
52 | def json(self) -> dict:
53 | return self.response_dict
54 |
55 | class Completion:
56 | def create(
57 | prompt: str = 'hello world',
58 | messages: list = []) -> SqlchatResponse:
59 |
60 | response = post('https://www.sqlchat.ai/api/chat', headers=headers, stream=True,
61 | json = {
62 | 'messages': messages,
63 | 'openAIApiConfig':{'key':'','endpoint':''}})
64 |
65 | return SqlchatResponse({
66 | 'id' : f'cmpl-1337-{int(time())}',
67 | 'object' : 'text_completion',
68 | 'created': int(time()),
69 | 'model' : 'gpt-3.5-turbo',
70 | 'choices': [{
71 | 'text' : response.text,
72 | 'index' : 0,
73 | 'logprobs' : None,
74 | 'finish_reason' : 'stop'
75 | }],
76 | 'usage': {
77 | 'prompt_chars' : len(prompt),
78 | 'completion_chars' : len(response.text),
79 | 'total_chars' : len(prompt) + len(response.text)
80 | }
81 | })
82 |
83 | class StreamCompletion:
84 | def create(
85 | prompt : str = 'hello world',
86 | messages: list = []) -> SqlchatResponse:
87 |
88 | messages.append({
89 | 'role':'user',
90 | 'content':prompt
91 | })
92 |
93 | response = post('https://www.sqlchat.ai/api/chat', headers=headers, stream=True,
94 | json = {
95 | 'messages': messages,
96 | 'openAIApiConfig':{'key':'','endpoint':''}})
97 |
98 | for chunk in response.iter_content(chunk_size = 2046):
99 | yield SqlchatResponse({
100 | 'id' : f'cmpl-1337-{int(time())}',
101 | 'object' : 'text_completion',
102 | 'created': int(time()),
103 | 'model' : 'gpt-3.5-turbo',
104 |
105 | 'choices': [{
106 | 'text' : chunk.decode(),
107 | 'index' : 0,
108 | 'logprobs' : None,
109 | 'finish_reason' : 'stop'
110 | }],
111 |
112 | 'usage': {
113 | 'prompt_chars' : len(prompt),
114 | 'completion_chars' : len(chunk.decode()),
115 | 'total_chars' : len(prompt) + len(chunk.decode())
116 | }
117 | })
--------------------------------------------------------------------------------
/testing/poe_account_create_test.py:
--------------------------------------------------------------------------------
1 | from requests import Session
2 | from tls_client import Session as TLS
3 | from json import dumps
4 | from hashlib import md5
5 | from time import sleep
6 | from re import findall
7 | from pypasser import reCaptchaV3
8 | from quora import extract_formkey
9 | from quora.mail import Emailnator
10 | from twocaptcha import TwoCaptcha
11 |
12 | solver = TwoCaptcha('72747bf24a9d89b4dcc1b24875efd358')
13 |
14 | class Account:
15 | def create(proxy: None or str = None, logging: bool = False, enable_bot_creation: bool = False):
16 | client = TLS(client_identifier='chrome110')
17 | client.proxies = {
18 | 'http': f'http://{proxy}',
19 | 'https': f'http://{proxy}'} if proxy else None
20 |
21 | mail_client = Emailnator()
22 | mail_address = mail_client.get_mail()
23 |
24 | if logging: print('email', mail_address)
25 |
26 | client.headers = {
27 | 'authority' : 'poe.com',
28 | 'accept' : '*/*',
29 | 'accept-language': 'en,fr-FR;q=0.9,fr;q=0.8,es-ES;q=0.7,es;q=0.6,en-US;q=0.5,am;q=0.4,de;q=0.3',
30 | 'content-type' : 'application/json',
31 | 'origin' : 'https://poe.com',
32 | 'poe-formkey' : 'null',
33 | 'poe-tag-id' : 'null',
34 | 'poe-tchannel' : 'null',
35 | 'referer' : 'https://poe.com/login',
36 | 'sec-ch-ua' : '"Chromium";v="112", "Google Chrome";v="112", "Not:A-Brand";v="99"',
37 | 'sec-ch-ua-mobile' : '?0',
38 | 'sec-ch-ua-platform': '"macOS"',
39 | 'sec-fetch-dest': 'empty',
40 | 'sec-fetch-mode': 'cors',
41 | 'sec-fetch-site': 'same-origin',
42 | 'user-agent' : 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36'
43 | }
44 |
45 | client.headers["poe-formkey"] = extract_formkey(client.get('https://poe.com/login').text)
46 | client.headers["poe-tchannel"] = client.get('https://poe.com/api/settings').json()['tchannelData']['channel']
47 |
48 | #token = reCaptchaV3('https://www.recaptcha.net/recaptcha/enterprise/anchor?ar=1&k=6LflhEElAAAAAI_ewVwRWI9hsyV4mbZnYAslSvlG&co=aHR0cHM6Ly9wb2UuY29tOjQ0Mw..&hl=en&v=4PnKmGB9wRHh1i04o7YUICeI&size=invisible&cb=bi6ivxoskyal')
49 | token = solver.recaptcha(sitekey='6LflhEElAAAAAI_ewVwRWI9hsyV4mbZnYAslSvlG',
50 | url = 'https://poe.com/login?redirect_url=%2F',
51 | version = 'v3',
52 | enterprise = 1,
53 | invisible = 1,
54 | action = 'login',)['code']
55 |
56 | payload = dumps(separators = (',', ':'), obj = {
57 | 'queryName': 'MainSignupLoginSection_sendVerificationCodeMutation_Mutation',
58 | 'variables': {
59 | 'emailAddress' : mail_address,
60 | 'phoneNumber' : None,
61 | 'recaptchaToken': token
62 | },
63 | 'query': 'mutation MainSignupLoginSection_sendVerificationCodeMutation_Mutation(\n $emailAddress: String\n $phoneNumber: String\n $recaptchaToken: String\n) {\n sendVerificationCode(verificationReason: login, emailAddress: $emailAddress, phoneNumber: $phoneNumber, recaptchaToken: $recaptchaToken) {\n status\n errorMessage\n }\n}\n',
64 | })
65 |
66 | base_string = payload + client.headers["poe-formkey"] + 'WpuLMiXEKKE98j56k'
67 | client.headers["poe-tag-id"] = md5(base_string.encode()).hexdigest()
68 |
69 | print(dumps(client.headers, indent=4))
70 |
71 | response = client.post('https://poe.com/api/gql_POST', data=payload)
72 |
73 | if 'automated_request_detected' in response.text:
74 | print('please try using a proxy / wait for fix')
75 |
76 | if 'Bad Request' in response.text:
77 | if logging: print('bad request, retrying...' , response.json())
78 | quit()
79 |
80 | if logging: print('send_code' ,response.json())
81 |
82 | mail_content = mail_client.get_message()
83 | mail_token = findall(r';">(\d{6,7})', mail_content)[0]
84 |
85 | if logging: print('code', mail_token)
86 |
87 | payload = dumps(separators = (',', ':'), obj={
88 | "queryName": "SignupOrLoginWithCodeSection_signupWithVerificationCodeMutation_Mutation",
89 | "variables": {
90 | "verificationCode": str(mail_token),
91 | "emailAddress": mail_address,
92 | "phoneNumber": None
93 | },
94 | "query": "mutation SignupOrLoginWithCodeSection_signupWithVerificationCodeMutation_Mutation(\n $verificationCode: String!\n $emailAddress: String\n $phoneNumber: String\n) {\n signupWithVerificationCode(verificationCode: $verificationCode, emailAddress: $emailAddress, phoneNumber: $phoneNumber) {\n status\n errorMessage\n }\n}\n"
95 | })
96 |
97 | base_string = payload + client.headers["poe-formkey"] + 'WpuLMiXEKKE98j56k'
98 | client.headers["poe-tag-id"] = md5(base_string.encode()).hexdigest()
99 |
100 | response = client.post('https://poe.com/api/gql_POST', data = payload)
101 | if logging: print('verify_code', response.json())
102 |
103 |
104 | Account.create(proxy = 'xtekky:wegwgwegwed_streaming-1@geo.iproyal.com:12321', logging = True)
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Gpt4free - use chatgpt, for free !!
2 |
3 |
4 |
5 | Have you ever come across some amazing projects that you couldnt use **just because you didn't have an OpenAI API key ?**
6 |
7 | **We've got u covered !!** This repository offers **reverse-engineered** third-party APIs for `GPT-4/3.5`, sourced from various websites. You can simply **download** this repository and use the available modules, which are designed to be used **just like OpenAI's official package**. **Unleash ChatGpt's potential for your projects, now !** You are welcome ; ).
8 |
9 | By the way, thank you so much for `2k` stars and all the support !!
10 |
11 | ## Chatgpt clone
12 | > https://chat.chatbot.sex/chat
13 | > This site was developed by me and includes **gpt-4/3.5**, **internet access** and **gpt-jailbreak's** like DAN
14 | > run locally here: https://github.com/xtekky/chatgpt-clone
15 |
16 |
17 | ## Table of Contents
18 |
19 | - [Current Sites](#current-sites)
20 | - [Best Sites for gpt4](#best-sites)
21 | - [How to intall](#install)
22 | - [Legal Notice](#legal-notice)
23 | - [Copyright](#copyright)
24 |
25 |
26 | - [Usage Examples](./README.md)
27 | - [`quora (poe)`](./quora/README.md)
28 | - [`phind`](./phind/README.md)
29 | - [`t3nsor`](./t3nsor/README.md)
30 | - [`ora`](./ora/README.md)
31 | - [`writesonic`](./writesonic/README.md)
32 | - [`you`](./you/README.md)
33 | - [`sqlchat`](./sqlchat/README.md)
34 |
35 | ## Current Sites
36 |
37 | | Website | Model(s) |
38 | | ---------------------------------------------------- | ------------------------------- |
39 | | [ora.sh](https://ora.sh) | GPT-3.5 / 4 |
40 | | [poe.com](https://poe.com) | GPT-4/3.5 |
41 | | [writesonic.com](https://writesonic.com) | GPT-3.5 / Internet |
42 | | [t3nsor.com](https://t3nsor.com) | GPT-3.5 |
43 | | [you.com](https://you.com) | GPT-3.5 / Internet / good search|
44 | | [phind.com](https://phind.com) | GPT-4 / Internet / good search |
45 | | [sqlchat.ai](https://sqlchat.ai) | GPT-3.5 |
46 | | [chat.openai.com/chat](https://chat.openai.com/chat) | GPT-3.5 |
47 | | [bard.google.com](https://bard.google.com) | custom / search |
48 | | [bing.com/chat](https://bing.com/chat) | GPT-4/3.5 |
49 |
50 | ## Best sites
51 |
52 | #### gpt-4
53 | - [`/ora`](./ora/README.md)
54 | - here is proof / test: [`ora_gpt4_proof.py`](./testing/ora_gpt4_proof.py)
55 | - why ?, no streaming compared to poe.com but u can send more than 1 message
56 |
57 | #### gpt-3.5
58 | - [`/sqlchat`](./sqlchat/README.md)
59 | - why ? (streaming + you can give conversation history)
60 |
61 | #### search
62 | - [`/phind`](./phind/README.md)
63 | - why ? its not sure if they use gpt, but rather claude but they have an amazing search and good reasoning model
64 |
65 | ## Install
66 | - download or clone this github repo
67 |
68 | install requirements with:
69 | ```sh
70 | pip3 install -r requirements.txt
71 | ```
72 |
73 | ## Legal Notice
74 |
75 | This repository uses third-party APIs and AI models and is *not* associated with or endorsed by the API providers or the original developers of the models. This project is intended **for educational purposes only**.
76 |
77 | Please note the following:
78 |
79 | 1. **Disclaimer**: The APIs, services, and trademarks mentioned in this repository belong to their respective owners. This project is *not* claiming any right over them.
80 |
81 | 2. **Responsibility**: The author of this repository is *not* responsible for any consequences arising from the use or misuse of this repository or the content provided by the third-party APIs and any damage or losses caused by users' actions.
82 |
83 | 3. **Educational Purposes Only**: This repository and its content are provided strictly for educational purposes. By using the information and code provided, users acknowledge that they are using the APIs and models at their own risk and agree to comply with any applicable laws and regulations.
84 |
85 | ## Copyright:
86 | This program is licensed under the [GNU GPL v3](https://www.gnu.org/licenses/gpl-3.0.txt)
87 |
88 | Most code, with the exception of `quora/api.py` (by [ading2210](https://github.com/ading2210)), has been written by me, [xtekky](https://github.com/xtekky).
89 |
90 | ### Copyright Notice:
91 | ```
92 | xtekky/openai-gpt4: multiple reverse engineered language-model api's to decentralise the ai industry.
93 | Copyright (C) 2023 xtekky
94 |
95 | This program is free software: you can redistribute it and/or modify
96 | it under the terms of the GNU General Public License as published by
97 | the Free Software Foundation, either version 3 of the License, or
98 | (at your option) any later version.
99 |
100 | This program is distributed in the hope that it will be useful,
101 | but WITHOUT ANY WARRANTY; without even the implied warranty of
102 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
103 | GNU General Public License for more details.
104 |
105 | You should have received a copy of the GNU General Public License
106 | along with this program. If not, see .
107 | ```
108 |
109 |
--------------------------------------------------------------------------------
/unfinished/bard/__init__.py:
--------------------------------------------------------------------------------
1 | from requests import Session
2 | from re import search
3 | from random import randint
4 | from json import dumps, loads
5 | from random import randint
6 | from urllib.parse import urlencode
7 | from dotenv import load_dotenv; load_dotenv()
8 | from os import getenv
9 |
10 | from bard.typings import BardResponse
11 |
12 | token = getenv('1psid')
13 | proxy = getenv('proxy')
14 |
15 | temperatures = {
16 | 0 : "Generate text strictly following known patterns, with no creativity.",
17 | 0.1: "Produce text adhering closely to established patterns, allowing minimal creativity.",
18 | 0.2: "Create text with modest deviations from familiar patterns, injecting a slight creative touch.",
19 | 0.3: "Craft text with a mild level of creativity, deviating somewhat from common patterns.",
20 | 0.4: "Formulate text balancing creativity and recognizable patterns for coherent results.",
21 | 0.5: "Generate text with a moderate level of creativity, allowing for a mix of familiarity and novelty.",
22 | 0.6: "Compose text with an increased emphasis on creativity, while partially maintaining familiar patterns.",
23 | 0.7: "Produce text favoring creativity over typical patterns for more original results.",
24 | 0.8: "Create text heavily focused on creativity, with limited concern for familiar patterns.",
25 | 0.9: "Craft text with a strong emphasis on unique and inventive ideas, largely ignoring established patterns.",
26 | 1 : "Generate text with maximum creativity, disregarding any constraints of known patterns or structures."
27 | }
28 |
29 | class Completion:
30 | # def __init__(self, _token, proxy: str or None = None) -> None:
31 | # self.client = Session()
32 | # self.client.proxies = {
33 | # 'http': f'http://{proxy}',
34 | # 'https': f'http://{proxy}' } if proxy else None
35 |
36 | # self.client.headers = {
37 | # 'authority' : 'bard.google.com',
38 | # 'content-type' : 'application/x-www-form-urlencoded;charset=UTF-8',
39 | # 'origin' : 'https://bard.google.com',
40 | # 'referer' : 'https://bard.google.com/',
41 | # 'user-agent' : 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36',
42 | # 'x-same-domain' : '1',
43 | # 'cookie' : f'__Secure-1PSID={_token}'
44 | # }
45 |
46 | # self.snlm0e = self.__init_client()
47 | # self.conversation_id = ''
48 | # self.response_id = ''
49 | # self.choice_id = ''
50 | # self.reqid = randint(1111, 9999)
51 |
52 | def create(
53 | prompt : str = 'hello world',
54 | temperature : int = None,
55 | conversation_id : str = '',
56 | response_id : str = '',
57 | choice_id : str = '') -> BardResponse:
58 |
59 | if temperature:
60 | prompt = f'''settings: follow these settings for your response: [temperature: {temperature} - {temperatures[temperature]}] | prompt : {prompt}'''
61 |
62 | client = Session()
63 | client.proxies = {
64 | 'http': f'http://{proxy}',
65 | 'https': f'http://{proxy}' } if proxy else None
66 |
67 | client.headers = {
68 | 'authority' : 'bard.google.com',
69 | 'content-type' : 'application/x-www-form-urlencoded;charset=UTF-8',
70 | 'origin' : 'https://bard.google.com',
71 | 'referer' : 'https://bard.google.com/',
72 | 'user-agent' : 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36',
73 | 'x-same-domain' : '1',
74 | 'cookie' : f'__Secure-1PSID={token}'
75 | }
76 |
77 | snlm0e = search(r'SNlM0e\":\"(.*?)\"', client.get('https://bard.google.com/').text).group(1)
78 |
79 | params = urlencode({
80 | 'bl' : 'boq_assistant-bard-web-server_20230326.21_p0',
81 | '_reqid' : randint(1111, 9999),
82 | 'rt' : 'c',
83 | })
84 |
85 | response = client.post(f'https://bard.google.com/_/BardChatUi/data/assistant.lamda.BardFrontendService/StreamGenerate?{params}',
86 | data = {
87 | 'at': snlm0e,
88 | 'f.req': dumps([None, dumps([
89 | [prompt],
90 | None,
91 | [conversation_id, response_id, choice_id],
92 | ])
93 | ])
94 | }
95 | )
96 |
97 | chat_data = loads(response.content.splitlines()[3])[0][2]
98 | if not chat_data: print('error, retrying'); Completion.create(prompt, temperature, conversation_id, response_id, choice_id)
99 |
100 | json_chat_data = loads(chat_data)
101 | results = {
102 | 'content' : json_chat_data[0][0],
103 | 'conversation_id' : json_chat_data[1][0],
104 | 'response_id' : json_chat_data[1][1],
105 | 'factualityQueries' : json_chat_data[3],
106 | 'textQuery' : json_chat_data[2][0] if json_chat_data[2] is not None else '',
107 | 'choices' : [{'id': i[0], 'content': i[1]} for i in json_chat_data[4]],
108 | }
109 |
110 | # self.conversation_id = results['conversation_id']
111 | # self.response_id = results['response_id']
112 | # self.choice_id = results['choices'][0]['id']
113 | # self.reqid += 100000
114 |
115 | return BardResponse(results)
116 |
--------------------------------------------------------------------------------
/t3nsor/__init__.py:
--------------------------------------------------------------------------------
1 | from requests import post
2 | from time import time
3 |
4 | headers = {
5 | 'authority': 'www.t3nsor.tech',
6 | 'accept': '*/*',
7 | 'accept-language': 'en,fr-FR;q=0.9,fr;q=0.8,es-ES;q=0.7,es;q=0.6,en-US;q=0.5,am;q=0.4,de;q=0.3',
8 | 'cache-control': 'no-cache',
9 | 'content-type': 'application/json',
10 | 'origin': 'https://www.t3nsor.tech',
11 | 'pragma': 'no-cache',
12 | 'referer': 'https://www.t3nsor.tech/',
13 | 'sec-ch-ua': '"Chromium";v="112", "Google Chrome";v="112", "Not:A-Brand";v="99"',
14 | 'sec-ch-ua-mobile': '?0',
15 | 'sec-ch-ua-platform': '"macOS"',
16 | 'sec-fetch-dest': 'empty',
17 | 'sec-fetch-mode': 'cors',
18 | 'sec-fetch-site': 'same-origin',
19 | 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36',
20 | }
21 |
22 | class T3nsorResponse:
23 |
24 | class Completion:
25 |
26 | class Choices:
27 | def __init__(self, choice: dict) -> None:
28 | self.text = choice['text']
29 | self.content = self.text.encode()
30 | self.index = choice['index']
31 | self.logprobs = choice['logprobs']
32 | self.finish_reason = choice['finish_reason']
33 |
34 | def __repr__(self) -> str:
35 | return f'''<__main__.APIResponse.Completion.Choices(\n text = {self.text.encode()},\n index = {self.index},\n logprobs = {self.logprobs},\n finish_reason = {self.finish_reason})object at 0x1337>'''
36 |
37 | def __init__(self, choices: dict) -> None:
38 | self.choices = [self.Choices(choice) for choice in choices]
39 |
40 | class Usage:
41 | def __init__(self, usage_dict: dict) -> None:
42 | self.prompt_tokens = usage_dict['prompt_chars']
43 | self.completion_tokens = usage_dict['completion_chars']
44 | self.total_tokens = usage_dict['total_chars']
45 |
46 | def __repr__(self):
47 | return f'''<__main__.APIResponse.Usage(\n prompt_tokens = {self.prompt_tokens},\n completion_tokens = {self.completion_tokens},\n total_tokens = {self.total_tokens})object at 0x1337>'''
48 |
49 | def __init__(self, response_dict: dict) -> None:
50 |
51 | self.response_dict = response_dict
52 | self.id = response_dict['id']
53 | self.object = response_dict['object']
54 | self.created = response_dict['created']
55 | self.model = response_dict['model']
56 | self.completion = self.Completion(response_dict['choices'])
57 | self.usage = self.Usage(response_dict['usage'])
58 |
59 | def json(self) -> dict:
60 | return self.response_dict
61 |
62 | class Completion:
63 | model = {
64 | 'model': {
65 | 'id' : 'gpt-3.5-turbo',
66 | 'name' : 'Default (GPT-3.5)'
67 | }
68 | }
69 |
70 | def create(
71 | prompt: str = 'hello world',
72 | messages: list = []) -> T3nsorResponse:
73 |
74 | response = post('https://www.t3nsor.tech/api/chat', headers = headers, json = Completion.model | {
75 | 'messages' : messages,
76 | 'key' : '',
77 | 'prompt' : prompt
78 | })
79 |
80 | return T3nsorResponse({
81 | 'id' : f'cmpl-1337-{int(time())}',
82 | 'object' : 'text_completion',
83 | 'created': int(time()),
84 | 'model' : Completion.model,
85 | 'choices': [{
86 | 'text' : response.text,
87 | 'index' : 0,
88 | 'logprobs' : None,
89 | 'finish_reason' : 'stop'
90 | }],
91 | 'usage': {
92 | 'prompt_chars' : len(prompt),
93 | 'completion_chars' : len(response.text),
94 | 'total_chars' : len(prompt) + len(response.text)
95 | }
96 | })
97 |
98 | class StreamCompletion:
99 | model = {
100 | 'model': {
101 | 'id' : 'gpt-3.5-turbo',
102 | 'name' : 'Default (GPT-3.5)'
103 | }
104 | }
105 |
106 | def create(
107 | prompt: str = 'hello world',
108 | messages: list = []) -> T3nsorResponse:
109 |
110 | print('t3nsor api is down, this may not work, refer to another module')
111 |
112 | response = post('https://www.t3nsor.tech/api/chat', headers = headers, stream = True, json = Completion.model | {
113 | 'messages' : messages,
114 | 'key' : '',
115 | 'prompt' : prompt
116 | })
117 |
118 | for chunk in response.iter_content(chunk_size = 2046):
119 | yield T3nsorResponse({
120 | 'id' : f'cmpl-1337-{int(time())}',
121 | 'object' : 'text_completion',
122 | 'created': int(time()),
123 | 'model' : Completion.model,
124 |
125 | 'choices': [{
126 | 'text' : chunk.decode(),
127 | 'index' : 0,
128 | 'logprobs' : None,
129 | 'finish_reason' : 'stop'
130 | }],
131 |
132 | 'usage': {
133 | 'prompt_chars' : len(prompt),
134 | 'completion_chars' : len(chunk.decode()),
135 | 'total_chars' : len(prompt) + len(chunk.decode())
136 | }
137 | })
138 |
--------------------------------------------------------------------------------
/unfinished/bing/__ini__.py:
--------------------------------------------------------------------------------
1 | from requests import get
2 | from browser_cookie3 import edge, chrome
3 | from ssl import create_default_context
4 | from certifi import where
5 | from uuid import uuid4
6 | from random import randint
7 | from json import dumps, loads
8 |
9 | import asyncio
10 | import websockets
11 |
12 | ssl_context = create_default_context()
13 | ssl_context.load_verify_locations(where())
14 |
15 | def format(msg: dict) -> str:
16 | return dumps(msg) + '\x1e'
17 |
18 | def get_token():
19 |
20 | cookies = {c.name: c.value for c in edge(domain_name='bing.com')}
21 | return cookies['_U']
22 |
23 |
24 |
25 | class AsyncCompletion:
26 | async def create(
27 | prompt : str = 'hello world',
28 | optionSets : list = [
29 | 'deepleo',
30 | 'enable_debug_commands',
31 | 'disable_emoji_spoken_text',
32 | 'enablemm',
33 | 'h3relaxedimg'
34 | ],
35 | token : str = get_token()):
36 |
37 | create = get('https://edgeservices.bing.com/edgesvc/turing/conversation/create',
38 | headers = {
39 | 'host' : 'edgeservices.bing.com',
40 | 'authority' : 'edgeservices.bing.com',
41 | 'cookie' : f'_U={token}',
42 | 'user-agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36 Edg/110.0.1587.69',
43 | }
44 | )
45 |
46 | conversationId = create.json()['conversationId']
47 | clientId = create.json()['clientId']
48 | conversationSignature = create.json()['conversationSignature']
49 |
50 | wss: websockets.WebSocketClientProtocol or None = None
51 |
52 | wss = await websockets.connect('wss://sydney.bing.com/sydney/ChatHub', max_size = None, ssl = ssl_context,
53 | extra_headers = {
54 | 'accept': 'application/json',
55 | 'accept-language': 'en-US,en;q=0.9',
56 | 'content-type': 'application/json',
57 | 'sec-ch-ua': '"Not_A Brand";v="99", Microsoft Edge";v="110", "Chromium";v="110"',
58 | 'sec-ch-ua-arch': '"x86"',
59 | 'sec-ch-ua-bitness': '"64"',
60 | 'sec-ch-ua-full-version': '"109.0.1518.78"',
61 | 'sec-ch-ua-full-version-list': '"Chromium";v="110.0.5481.192", "Not A(Brand";v="24.0.0.0", "Microsoft Edge";v="110.0.1587.69"',
62 | 'sec-ch-ua-mobile': '?0',
63 | 'sec-ch-ua-model': "",
64 | 'sec-ch-ua-platform': '"Windows"',
65 | 'sec-ch-ua-platform-version': '"15.0.0"',
66 | 'sec-fetch-dest': 'empty',
67 | 'sec-fetch-mode': 'cors',
68 | 'sec-fetch-site': 'same-origin',
69 | 'x-ms-client-request-id': str(uuid4()),
70 | 'x-ms-useragent': 'azsdk-js-api-client-factory/1.0.0-beta.1 core-rest-pipeline/1.10.0 OS/Win32',
71 | 'Referer': 'https://www.bing.com/search?q=Bing+AI&showconv=1&FORM=hpcodx',
72 | 'Referrer-Policy': 'origin-when-cross-origin',
73 | 'x-forwarded-for': f'13.{randint(104, 107)}.{randint(0, 255)}.{randint(0, 255)}'
74 | }
75 | )
76 |
77 | await wss.send(format({'protocol': 'json', 'version': 1}))
78 | await wss.recv()
79 |
80 | struct = {
81 | 'arguments': [
82 | {
83 | 'source': 'cib',
84 | 'optionsSets': optionSets,
85 | 'isStartOfSession': True,
86 | 'message': {
87 | 'author': 'user',
88 | 'inputMethod': 'Keyboard',
89 | 'text': prompt,
90 | 'messageType': 'Chat'
91 | },
92 | 'conversationSignature': conversationSignature,
93 | 'participant': {
94 | 'id': clientId
95 | },
96 | 'conversationId': conversationId
97 | }
98 | ],
99 | 'invocationId': '0',
100 | 'target': 'chat',
101 | 'type': 4
102 | }
103 |
104 | await wss.send(format(struct))
105 |
106 | base_string = ''
107 |
108 | final = False
109 | while not final:
110 | objects = str(await wss.recv()).split('\x1e')
111 | for obj in objects:
112 | if obj is None or obj == '':
113 | continue
114 |
115 | response = loads(obj)
116 | if response.get('type') == 1 and response['arguments'][0].get('messages',):
117 | response_text = response['arguments'][0]['messages'][0]['adaptiveCards'][0]['body'][0].get('text')
118 |
119 | yield (response_text.replace(base_string, ''))
120 | base_string = response_text
121 |
122 | elif response.get('type') == 2:
123 | final = True
124 |
125 | await wss.close()
126 |
127 | async def run():
128 | async for value in AsyncCompletion.create(
129 | prompt = 'summarize cinderella with each word beginning with a consecutive letter of the alphabet, a-z',
130 | # optionSets = [
131 | # "deepleo",
132 | # "enable_debug_commands",
133 | # "disable_emoji_spoken_text",
134 | # "enablemm"
135 | # ]
136 | optionSets = [
137 | #"nlu_direct_response_filter",
138 | #"deepleo",
139 | #"disable_emoji_spoken_text",
140 | # "responsible_ai_policy_235",
141 | #"enablemm",
142 | "galileo",
143 | #"dtappid",
144 | # "cricinfo",
145 | # "cricinfov2",
146 | # "dv3sugg",
147 | ]
148 | ):
149 | print(value, end = '', flush=True)
150 |
151 | asyncio.run(run())
--------------------------------------------------------------------------------
/writesonic/__init__.py:
--------------------------------------------------------------------------------
1 | from requests import Session
2 | from names import get_first_name, get_last_name
3 | from random import choice
4 | from requests import post
5 | from time import time
6 | from colorama import Fore, init; init()
7 |
8 | class logger:
9 | @staticmethod
10 | def info(string) -> print:
11 | import datetime
12 | now = datetime.datetime.now()
13 | return print(f"{Fore.CYAN}{now.strftime('%Y-%m-%d %H:%M:%S')} {Fore.BLUE}INFO {Fore.MAGENTA}__main__ -> {Fore.RESET}{string}")
14 |
15 | class SonicResponse:
16 |
17 | class Completion:
18 |
19 | class Choices:
20 | def __init__(self, choice: dict) -> None:
21 | self.text = choice['text']
22 | self.content = self.text.encode()
23 | self.index = choice['index']
24 | self.logprobs = choice['logprobs']
25 | self.finish_reason = choice['finish_reason']
26 |
27 | def __repr__(self) -> str:
28 | return f'''<__main__.APIResponse.Completion.Choices(\n text = {self.text.encode()},\n index = {self.index},\n logprobs = {self.logprobs},\n finish_reason = {self.finish_reason})object at 0x1337>'''
29 |
30 | def __init__(self, choices: dict) -> None:
31 | self.choices = [self.Choices(choice) for choice in choices]
32 |
33 | class Usage:
34 | def __init__(self, usage_dict: dict) -> None:
35 | self.prompt_tokens = usage_dict['prompt_chars']
36 | self.completion_tokens = usage_dict['completion_chars']
37 | self.total_tokens = usage_dict['total_chars']
38 |
39 | def __repr__(self):
40 | return f'''<__main__.APIResponse.Usage(\n prompt_tokens = {self.prompt_tokens},\n completion_tokens = {self.completion_tokens},\n total_tokens = {self.total_tokens})object at 0x1337>'''
41 |
42 | def __init__(self, response_dict: dict) -> None:
43 |
44 | self.response_dict = response_dict
45 | self.id = response_dict['id']
46 | self.object = response_dict['object']
47 | self.created = response_dict['created']
48 | self.model = response_dict['model']
49 | self.completion = self.Completion(response_dict['choices'])
50 | self.usage = self.Usage(response_dict['usage'])
51 |
52 | def json(self) -> dict:
53 | return self.response_dict
54 |
55 | class Account:
56 | session = Session()
57 | session.headers = {
58 | "connection" : "keep-alive",
59 | "sec-ch-ua" : "\"Not_A Brand\";v=\"99\", \"Google Chrome\";v=\"109\", \"Chromium\";v=\"109\"",
60 | "accept" : "application/json, text/plain, */*",
61 | "content-type" : "application/json",
62 | "sec-ch-ua-mobile" : "?0",
63 | "user-agent" : "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36",
64 | "sec-ch-ua-platform": "\"Windows\"",
65 | "sec-fetch-site" : "same-origin",
66 | "sec-fetch-mode" : "cors",
67 | "sec-fetch-dest" : "empty",
68 | # "accept-encoding" : "gzip, deflate, br",
69 | "accept-language" : "en-GB,en-US;q=0.9,en;q=0.8",
70 | "cookie" : ""
71 | }
72 |
73 | @staticmethod
74 | def get_user():
75 | password = f'0opsYouGoTme@1234'
76 | f_name = get_first_name()
77 | l_name = get_last_name()
78 | hosts = ['gmail.com', 'protonmail.com', 'proton.me', 'outlook.com']
79 |
80 | return {
81 | "email" : f"{f_name.lower()}.{l_name.lower()}@{choice(hosts)}",
82 | "password" : password,
83 | "confirm_password" : password,
84 | "full_name" : f'{f_name} {l_name}'
85 | }
86 |
87 | @staticmethod
88 | def create(logging: bool = False):
89 | while True:
90 | try:
91 | user = Account.get_user()
92 | start = time()
93 | response = Account.session.post("https://app.writesonic.com/api/session-login", json = user | {
94 | "utmParams" : "{}",
95 | "visitorId" : "0",
96 | "locale" : "en",
97 | "userAgent" : "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36",
98 | "signInWith" : "password",
99 | "request_type" : "signup",
100 | })
101 |
102 | if logging:
103 | logger.info(f"\x1b[31mregister success\x1b[0m : '{response.text[:30]}...' ({int(time() - start)}s)")
104 | logger.info(f"\x1b[31mid\x1b[0m : '{response.json()['id']}'")
105 | logger.info(f"\x1b[31mtoken\x1b[0m : '{response.json()['token'][:30]}...'")
106 |
107 | start = time()
108 | response = Account.session.post("https://api.writesonic.com/v1/business/set-business-active", headers={"authorization": "Bearer " + response.json()['token']})
109 | key = response.json()["business"]["api_key"]
110 | if logging: logger.info(f"\x1b[31mgot key\x1b[0m : '{key}' ({int(time() - start)}s)")
111 |
112 | return Account.AccountResponse(user['email'], user['password'], key)
113 |
114 | except Exception as e:
115 | if logging: logger.info(f"\x1b[31merror\x1b[0m : '{e}'")
116 | continue
117 |
118 | class AccountResponse:
119 | def __init__(self, email, password, key):
120 | self.email = email
121 | self.password = password
122 | self.key = key
123 |
124 |
125 | class Completion:
126 | def create(
127 | api_key: str,
128 | prompt: str,
129 | enable_memory: bool = False,
130 | enable_google_results: bool = False,
131 | history_data: list = []) -> SonicResponse:
132 |
133 | response = post('https://api.writesonic.com/v2/business/content/chatsonic?engine=premium', headers = {"X-API-KEY": api_key},
134 | json = {
135 | "enable_memory" : enable_memory,
136 | "enable_google_results" : enable_google_results,
137 | "input_text" : prompt,
138 | "history_data" : history_data}).json()
139 |
140 | return SonicResponse({
141 | 'id' : f'cmpl-premium-{int(time())}',
142 | 'object' : 'text_completion',
143 | 'created': int(time()),
144 | 'model' : 'premium',
145 |
146 | 'choices': [{
147 | 'text' : response['message'],
148 | 'index' : 0,
149 | 'logprobs' : None,
150 | 'finish_reason' : 'stop'
151 | }],
152 |
153 | 'usage': {
154 | 'prompt_chars' : len(prompt),
155 | 'completion_chars' : len(response['message']),
156 | 'total_chars' : len(prompt) + len(response['message'])
157 | }
158 | })
--------------------------------------------------------------------------------
/quora/graphql/ChatListPaginationQuery.graphql:
--------------------------------------------------------------------------------
1 | query ChatListPaginationQuery(
2 | $count: Int = 5
3 | $cursor: String
4 | $id: ID!
5 | ) {
6 | node(id: $id) {
7 | __typename
8 | ...ChatPageMain_chat_1G22uz
9 | id
10 | }
11 | }
12 |
13 | fragment BotImage_bot on Bot {
14 | displayName
15 | ...botHelpers_useDeletion_bot
16 | ...BotImage_useProfileImage_bot
17 | }
18 |
19 | fragment BotImage_useProfileImage_bot on Bot {
20 | image {
21 | __typename
22 | ... on LocalBotImage {
23 | localName
24 | }
25 | ... on UrlBotImage {
26 | url
27 | }
28 | }
29 | ...botHelpers_useDeletion_bot
30 | }
31 |
32 | fragment ChatMessageDownvotedButton_message on Message {
33 | ...MessageFeedbackReasonModal_message
34 | ...MessageFeedbackOtherModal_message
35 | }
36 |
37 | fragment ChatMessageDropdownMenu_message on Message {
38 | id
39 | messageId
40 | vote
41 | text
42 | author
43 | ...chatHelpers_isBotMessage
44 | }
45 |
46 | fragment ChatMessageFeedbackButtons_message on Message {
47 | id
48 | messageId
49 | vote
50 | voteReason
51 | ...ChatMessageDownvotedButton_message
52 | }
53 |
54 | fragment ChatMessageInputView_chat on Chat {
55 | id
56 | chatId
57 | defaultBotObject {
58 | nickname
59 | messageLimit {
60 | dailyBalance
61 | shouldShowRemainingMessageCount
62 | }
63 | hasClearContext
64 | isDown
65 | ...botHelpers_useDeletion_bot
66 | id
67 | }
68 | shouldShowDisclaimer
69 | ...chatHelpers_useSendMessage_chat
70 | ...chatHelpers_useSendChatBreak_chat
71 | }
72 |
73 | fragment ChatMessageInputView_edges on MessageEdge {
74 | node {
75 | ...chatHelpers_isChatBreak
76 | ...chatHelpers_isHumanMessage
77 | state
78 | text
79 | id
80 | }
81 | }
82 |
83 | fragment ChatMessageOverflowButton_message on Message {
84 | text
85 | ...ChatMessageDropdownMenu_message
86 | ...chatHelpers_isBotMessage
87 | }
88 |
89 | fragment ChatMessageSuggestedReplies_SuggestedReplyButton_chat on Chat {
90 | ...chatHelpers_useSendMessage_chat
91 | }
92 |
93 | fragment ChatMessageSuggestedReplies_SuggestedReplyButton_message on Message {
94 | messageId
95 | }
96 |
97 | fragment ChatMessageSuggestedReplies_chat on Chat {
98 | ...ChatWelcomeView_chat
99 | ...ChatMessageSuggestedReplies_SuggestedReplyButton_chat
100 | defaultBotObject {
101 | hasWelcomeTopics
102 | id
103 | }
104 | }
105 |
106 | fragment ChatMessageSuggestedReplies_message on Message {
107 | suggestedReplies
108 | ...ChatMessageSuggestedReplies_SuggestedReplyButton_message
109 | }
110 |
111 | fragment ChatMessage_chat on Chat {
112 | defaultBotObject {
113 | hasWelcomeTopics
114 | hasSuggestedReplies
115 | disclaimerText
116 | messageLimit {
117 | ...ChatPageRateLimitedBanner_messageLimit
118 | }
119 | ...ChatPageDisclaimer_bot
120 | id
121 | }
122 | ...ChatMessageSuggestedReplies_chat
123 | ...ChatWelcomeView_chat
124 | }
125 |
126 | fragment ChatMessage_message on Message {
127 | id
128 | messageId
129 | text
130 | author
131 | linkifiedText
132 | state
133 | contentType
134 | ...ChatMessageSuggestedReplies_message
135 | ...ChatMessageFeedbackButtons_message
136 | ...ChatMessageOverflowButton_message
137 | ...chatHelpers_isHumanMessage
138 | ...chatHelpers_isBotMessage
139 | ...chatHelpers_isChatBreak
140 | ...chatHelpers_useTimeoutLevel
141 | ...MarkdownLinkInner_message
142 | ...IdAnnotation_node
143 | }
144 |
145 | fragment ChatMessagesView_chat on Chat {
146 | ...ChatMessage_chat
147 | ...ChatWelcomeView_chat
148 | ...IdAnnotation_node
149 | defaultBotObject {
150 | hasWelcomeTopics
151 | messageLimit {
152 | ...ChatPageRateLimitedBanner_messageLimit
153 | }
154 | id
155 | }
156 | }
157 |
158 | fragment ChatMessagesView_edges on MessageEdge {
159 | node {
160 | id
161 | messageId
162 | creationTime
163 | ...ChatMessage_message
164 | ...chatHelpers_isBotMessage
165 | ...chatHelpers_isHumanMessage
166 | ...chatHelpers_isChatBreak
167 | }
168 | }
169 |
170 | fragment ChatPageDeleteFooter_chat on Chat {
171 | ...MessageDeleteConfirmationModal_chat
172 | }
173 |
174 | fragment ChatPageDisclaimer_bot on Bot {
175 | disclaimerText
176 | }
177 |
178 | fragment ChatPageMainFooter_chat on Chat {
179 | defaultBotObject {
180 | ...ChatPageMainFooter_useAccessMessage_bot
181 | id
182 | }
183 | ...ChatMessageInputView_chat
184 | ...ChatPageShareFooter_chat
185 | ...ChatPageDeleteFooter_chat
186 | }
187 |
188 | fragment ChatPageMainFooter_edges on MessageEdge {
189 | ...ChatMessageInputView_edges
190 | }
191 |
192 | fragment ChatPageMainFooter_useAccessMessage_bot on Bot {
193 | ...botHelpers_useDeletion_bot
194 | ...botHelpers_useViewerCanAccessPrivateBot
195 | }
196 |
197 | fragment ChatPageMain_chat_1G22uz on Chat {
198 | id
199 | chatId
200 | ...ChatPageShareFooter_chat
201 | ...ChatPageDeleteFooter_chat
202 | ...ChatMessagesView_chat
203 | ...MarkdownLinkInner_chat
204 | ...chatHelpers_useUpdateStaleChat_chat
205 | ...ChatSubscriptionPaywallContextWrapper_chat
206 | ...ChatPageMainFooter_chat
207 | messagesConnection(last: $count, before: $cursor) {
208 | edges {
209 | ...ChatMessagesView_edges
210 | ...ChatPageMainFooter_edges
211 | ...MarkdownLinkInner_edges
212 | node {
213 | ...chatHelpers_useUpdateStaleChat_message
214 | id
215 | __typename
216 | }
217 | cursor
218 | id
219 | }
220 | pageInfo {
221 | hasPreviousPage
222 | startCursor
223 | }
224 | id
225 | }
226 | }
227 |
228 | fragment ChatPageRateLimitedBanner_messageLimit on MessageLimit {
229 | numMessagesRemaining
230 | }
231 |
232 | fragment ChatPageShareFooter_chat on Chat {
233 | chatId
234 | }
235 |
236 | fragment ChatSubscriptionPaywallContextWrapper_chat on Chat {
237 | defaultBotObject {
238 | messageLimit {
239 | numMessagesRemaining
240 | shouldShowRemainingMessageCount
241 | }
242 | ...SubscriptionPaywallModal_bot
243 | id
244 | }
245 | }
246 |
247 | fragment ChatWelcomeView_ChatWelcomeButton_chat on Chat {
248 | ...chatHelpers_useSendMessage_chat
249 | }
250 |
251 | fragment ChatWelcomeView_chat on Chat {
252 | ...ChatWelcomeView_ChatWelcomeButton_chat
253 | defaultBotObject {
254 | displayName
255 | id
256 | }
257 | }
258 |
259 | fragment IdAnnotation_node on Node {
260 | __isNode: __typename
261 | id
262 | }
263 |
264 | fragment MarkdownLinkInner_chat on Chat {
265 | id
266 | chatId
267 | defaultBotObject {
268 | nickname
269 | id
270 | }
271 | ...chatHelpers_useSendMessage_chat
272 | }
273 |
274 | fragment MarkdownLinkInner_edges on MessageEdge {
275 | node {
276 | state
277 | id
278 | }
279 | }
280 |
281 | fragment MarkdownLinkInner_message on Message {
282 | messageId
283 | }
284 |
285 | fragment MessageDeleteConfirmationModal_chat on Chat {
286 | id
287 | }
288 |
289 | fragment MessageFeedbackOtherModal_message on Message {
290 | id
291 | messageId
292 | }
293 |
294 | fragment MessageFeedbackReasonModal_message on Message {
295 | id
296 | messageId
297 | }
298 |
299 | fragment SubscriptionPaywallModal_bot on Bot {
300 | displayName
301 | messageLimit {
302 | dailyLimit
303 | numMessagesRemaining
304 | shouldShowRemainingMessageCount
305 | resetTime
306 | }
307 | ...BotImage_bot
308 | }
309 |
310 | fragment botHelpers_useDeletion_bot on Bot {
311 | deletionState
312 | }
313 |
314 | fragment botHelpers_useViewerCanAccessPrivateBot on Bot {
315 | isPrivateBot
316 | viewerIsCreator
317 | }
318 |
319 | fragment chatHelpers_isBotMessage on Message {
320 | ...chatHelpers_isHumanMessage
321 | ...chatHelpers_isChatBreak
322 | }
323 |
324 | fragment chatHelpers_isChatBreak on Message {
325 | author
326 | }
327 |
328 | fragment chatHelpers_isHumanMessage on Message {
329 | author
330 | }
331 |
332 | fragment chatHelpers_useSendChatBreak_chat on Chat {
333 | id
334 | chatId
335 | defaultBotObject {
336 | nickname
337 | introduction
338 | model
339 | id
340 | }
341 | shouldShowDisclaimer
342 | }
343 |
344 | fragment chatHelpers_useSendMessage_chat on Chat {
345 | id
346 | chatId
347 | defaultBotObject {
348 | id
349 | nickname
350 | }
351 | shouldShowDisclaimer
352 | }
353 |
354 | fragment chatHelpers_useTimeoutLevel on Message {
355 | id
356 | state
357 | text
358 | messageId
359 | chat {
360 | chatId
361 | defaultBotNickname
362 | id
363 | }
364 | }
365 |
366 | fragment chatHelpers_useUpdateStaleChat_chat on Chat {
367 | chatId
368 | defaultBotObject {
369 | contextClearWindowSecs
370 | id
371 | }
372 | ...chatHelpers_useSendChatBreak_chat
373 | }
374 |
375 | fragment chatHelpers_useUpdateStaleChat_message on Message {
376 | creationTime
377 | ...chatHelpers_isChatBreak
378 | }
379 |
--------------------------------------------------------------------------------
/phind/__init__.py:
--------------------------------------------------------------------------------
1 | from urllib.parse import quote
2 | from time import time
3 | from datetime import datetime
4 | from queue import Queue, Empty
5 | from threading import Thread
6 | from re import findall
7 |
8 | from curl_cffi.requests import post
9 |
10 | cf_clearance = ''
11 |
12 | class PhindResponse:
13 |
14 | class Completion:
15 |
16 | class Choices:
17 | def __init__(self, choice: dict) -> None:
18 | self.text = choice['text']
19 | self.content = self.text.encode()
20 | self.index = choice['index']
21 | self.logprobs = choice['logprobs']
22 | self.finish_reason = choice['finish_reason']
23 |
24 | def __repr__(self) -> str:
25 | return f'''<__main__.APIResponse.Completion.Choices(\n text = {self.text.encode()},\n index = {self.index},\n logprobs = {self.logprobs},\n finish_reason = {self.finish_reason})object at 0x1337>'''
26 |
27 | def __init__(self, choices: dict) -> None:
28 | self.choices = [self.Choices(choice) for choice in choices]
29 |
30 | class Usage:
31 | def __init__(self, usage_dict: dict) -> None:
32 | self.prompt_tokens = usage_dict['prompt_tokens']
33 | self.completion_tokens = usage_dict['completion_tokens']
34 | self.total_tokens = usage_dict['total_tokens']
35 |
36 | def __repr__(self):
37 | return f'''<__main__.APIResponse.Usage(\n prompt_tokens = {self.prompt_tokens},\n completion_tokens = {self.completion_tokens},\n total_tokens = {self.total_tokens})object at 0x1337>'''
38 |
39 | def __init__(self, response_dict: dict) -> None:
40 |
41 | self.response_dict = response_dict
42 | self.id = response_dict['id']
43 | self.object = response_dict['object']
44 | self.created = response_dict['created']
45 | self.model = response_dict['model']
46 | self.completion = self.Completion(response_dict['choices'])
47 | self.usage = self.Usage(response_dict['usage'])
48 |
49 | def json(self) -> dict:
50 | return self.response_dict
51 |
52 |
53 | class Search:
54 | def create(prompt: str, actualSearch: bool = True, language: str = 'en') -> dict: # None = no search
55 | if not actualSearch:
56 | return {
57 | '_type': 'SearchResponse',
58 | 'queryContext': {
59 | 'originalQuery': prompt
60 | },
61 | 'webPages': {
62 | 'webSearchUrl': f'https://www.bing.com/search?q={quote(prompt)}',
63 | 'totalEstimatedMatches': 0,
64 | 'value': []
65 | },
66 | 'rankingResponse': {
67 | 'mainline': {
68 | 'items': []
69 | }
70 | }
71 | }
72 |
73 | headers = {
74 | 'authority': 'www.phind.com',
75 | 'accept': '*/*',
76 | 'accept-language': 'en,fr-FR;q=0.9,fr;q=0.8,es-ES;q=0.7,es;q=0.6,en-US;q=0.5,am;q=0.4,de;q=0.3',
77 | 'cookie': f'cf_clearance={cf_clearance}',
78 | 'origin': 'https://www.phind.com',
79 | 'referer': 'https://www.phind.com/search?q=hi&c=&source=searchbox&init=true',
80 | 'sec-ch-ua': '"Chromium";v="112", "Google Chrome";v="112", "Not:A-Brand";v="99"',
81 | 'sec-ch-ua-mobile': '?0',
82 | 'sec-ch-ua-platform': '"macOS"',
83 | 'sec-fetch-dest': 'empty',
84 | 'sec-fetch-mode': 'cors',
85 | 'sec-fetch-site': 'same-origin',
86 | 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36',
87 | }
88 |
89 | return post('https://www.phind.com/api/bing/search', headers = headers, json = {
90 | 'q': prompt,
91 | 'userRankList': {},
92 | 'browserLanguage': language}).json()['rawBingResults']
93 |
94 |
95 | class Completion:
96 | def create(
97 | model = 'gpt-4',
98 | prompt: str = '',
99 | results: dict = None,
100 | creative: bool = False,
101 | detailed: bool = False,
102 | codeContext: str = '',
103 | language: str = 'en') -> PhindResponse:
104 |
105 | if results is None:
106 | results = Search.create(prompt, actualSearch = True)
107 |
108 | if len(codeContext) > 2999:
109 | raise ValueError('codeContext must be less than 3000 characters')
110 |
111 | models = {
112 | 'gpt-4' : 'expert',
113 | 'gpt-3.5-turbo' : 'intermediate',
114 | 'gpt-3.5': 'intermediate',
115 | }
116 |
117 | json_data = {
118 | 'question' : prompt,
119 | 'bingResults' : results, #response.json()['rawBingResults'],
120 | 'codeContext' : codeContext,
121 | 'options': {
122 | 'skill' : models[model],
123 | 'date' : datetime.now().strftime("%d/%m/%Y"),
124 | 'language': language,
125 | 'detailed': detailed,
126 | 'creative': creative
127 | }
128 | }
129 |
130 | headers = {
131 | 'authority': 'www.phind.com',
132 | 'accept': '*/*',
133 | 'accept-language': 'en,fr-FR;q=0.9,fr;q=0.8,es-ES;q=0.7,es;q=0.6,en-US;q=0.5,am;q=0.4,de;q=0.3',
134 | 'content-type': 'application/json',
135 | 'cookie': f'cf_clearance={cf_clearance}',
136 | 'origin': 'https://www.phind.com',
137 | 'referer': 'https://www.phind.com/search?q=hi&c=&source=searchbox&init=true',
138 | 'sec-ch-ua': '"Chromium";v="112", "Google Chrome";v="112", "Not:A-Brand";v="99"',
139 | 'sec-ch-ua-mobile': '?0',
140 | 'sec-ch-ua-platform': '"macOS"',
141 | 'sec-fetch-dest': 'empty',
142 | 'sec-fetch-mode': 'cors',
143 | 'sec-fetch-site': 'same-origin',
144 | 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36',
145 | }
146 |
147 | completion = ''
148 | response = post('https://www.phind.com/api/infer/answer', headers = headers, json = json_data, timeout=99999, impersonate='chrome110')
149 | for line in response.text.split('\r\n\r\n'):
150 | completion += (line.replace('data: ', ''))
151 |
152 | return PhindResponse({
153 | 'id' : f'cmpl-1337-{int(time())}',
154 | 'object' : 'text_completion',
155 | 'created': int(time()),
156 | 'model' : models[model],
157 | 'choices': [{
158 | 'text' : completion,
159 | 'index' : 0,
160 | 'logprobs' : None,
161 | 'finish_reason' : 'stop'
162 | }],
163 | 'usage': {
164 | 'prompt_tokens' : len(prompt),
165 | 'completion_tokens' : len(completion),
166 | 'total_tokens' : len(prompt) + len(completion)
167 | }
168 | })
169 |
170 |
171 | class StreamingCompletion:
172 | message_queue = Queue()
173 | stream_completed = False
174 |
175 | def request(model, prompt, results, creative, detailed, codeContext, language) -> None:
176 |
177 | models = {
178 | 'gpt-4' : 'expert',
179 | 'gpt-3.5-turbo' : 'intermediate',
180 | 'gpt-3.5': 'intermediate',
181 | }
182 |
183 | json_data = {
184 | 'question' : prompt,
185 | 'bingResults' : results,
186 | 'codeContext' : codeContext,
187 | 'options': {
188 | 'skill' : models[model],
189 | 'date' : datetime.now().strftime("%d/%m/%Y"),
190 | 'language': language,
191 | 'detailed': detailed,
192 | 'creative': creative
193 | }
194 | }
195 |
196 | print(cf_clearance)
197 |
198 | headers = {
199 | 'authority': 'www.phind.com',
200 | 'accept': '*/*',
201 | 'accept-language': 'en,fr-FR;q=0.9,fr;q=0.8,es-ES;q=0.7,es;q=0.6,en-US;q=0.5,am;q=0.4,de;q=0.3',
202 | 'content-type': 'application/json',
203 | 'cookie': f'cf_clearance={cf_clearance}',
204 | 'origin': 'https://www.phind.com',
205 | 'referer': 'https://www.phind.com/search?q=hi&c=&source=searchbox&init=true',
206 | 'sec-ch-ua': '"Chromium";v="112", "Google Chrome";v="112", "Not:A-Brand";v="99"',
207 | 'sec-ch-ua-mobile': '?0',
208 | 'sec-ch-ua-platform': '"macOS"',
209 | 'sec-fetch-dest': 'empty',
210 | 'sec-fetch-mode': 'cors',
211 | 'sec-fetch-site': 'same-origin',
212 | 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36',
213 | }
214 |
215 | response = post('https://www.phind.com/api/infer/answer',
216 | headers = headers, json = json_data, timeout=99999, impersonate='chrome110', content_callback=StreamingCompletion.handle_stream_response)
217 |
218 |
219 | StreamingCompletion.stream_completed = True
220 |
221 | @staticmethod
222 | def create(
223 | model : str = 'gpt-4',
224 | prompt : str = '',
225 | results : dict = None,
226 | creative : bool = False,
227 | detailed : bool = False,
228 | codeContext : str = '',
229 | language : str = 'en'):
230 |
231 | if results is None:
232 | results = Search.create(prompt, actualSearch = True)
233 |
234 | if len(codeContext) > 2999:
235 | raise ValueError('codeContext must be less than 3000 characters')
236 |
237 | Thread(target = StreamingCompletion.request, args = [
238 | model, prompt, results, creative, detailed, codeContext, language]).start()
239 |
240 | while StreamingCompletion.stream_completed != True or not StreamingCompletion.message_queue.empty():
241 | try:
242 | chunk = StreamingCompletion.message_queue.get(timeout=0)
243 |
244 | if chunk == b'data: \r\ndata: \r\ndata: \r\n\r\n':
245 | chunk = b'data: \n\n\r\n\r\n'
246 |
247 | chunk = chunk.decode()
248 |
249 | chunk = chunk.replace('data: \r\n\r\ndata: ', 'data: \n')
250 | chunk = chunk.replace('\r\ndata: \r\ndata: \r\n\r\n', '\n\n\r\n\r\n')
251 | chunk = chunk.replace('data: ', '').replace('\r\n\r\n', '')
252 |
253 | yield PhindResponse({
254 | 'id' : f'cmpl-1337-{int(time())}',
255 | 'object' : 'text_completion',
256 | 'created': int(time()),
257 | 'model' : model,
258 | 'choices': [{
259 | 'text' : chunk,
260 | 'index' : 0,
261 | 'logprobs' : None,
262 | 'finish_reason' : 'stop'
263 | }],
264 | 'usage': {
265 | 'prompt_tokens' : len(prompt),
266 | 'completion_tokens' : len(chunk),
267 | 'total_tokens' : len(prompt) + len(chunk)
268 | }
269 | })
270 |
271 | except Empty:
272 | pass
273 |
274 | @staticmethod
275 | def handle_stream_response(response):
276 | StreamingCompletion.message_queue.put(response)
--------------------------------------------------------------------------------
/quora/__init__.py:
--------------------------------------------------------------------------------
1 | from quora.api import Client as PoeClient
2 | from quora.mail import Emailnator
3 | from requests import Session
4 | from tls_client import Session as TLS
5 | from re import search, findall
6 | from json import loads
7 | from time import sleep
8 | from pathlib import Path
9 | from random import choice, choices, randint
10 | from string import ascii_letters, digits
11 | from urllib import parse
12 | from os import urandom
13 | from hashlib import md5
14 | from json import dumps
15 | from pypasser import reCaptchaV3
16 |
17 | # from twocaptcha import TwoCaptcha
18 | # solver = TwoCaptcha('72747bf24a9d89b4dcc1b24875efd358')
19 |
20 | def extract_formkey(html):
21 | script_regex = r''
22 | script_text = search(script_regex, html).group(1)
23 | key_regex = r'var .="([0-9a-f]+)",'
24 | key_text = search(key_regex, script_text).group(1)
25 | cipher_regex = r'.\[(\d+)\]=.\[(\d+)\]'
26 | cipher_pairs = findall(cipher_regex, script_text)
27 |
28 | formkey_list = [""] * len(cipher_pairs)
29 | for pair in cipher_pairs:
30 | formkey_index, key_index = map(int, pair)
31 | formkey_list[formkey_index] = key_text[key_index]
32 | formkey = "".join(formkey_list)
33 |
34 | return formkey
35 |
36 | class PoeResponse:
37 |
38 | class Completion:
39 |
40 | class Choices:
41 | def __init__(self, choice: dict) -> None:
42 | self.text = choice['text']
43 | self.content = self.text.encode()
44 | self.index = choice['index']
45 | self.logprobs = choice['logprobs']
46 | self.finish_reason = choice['finish_reason']
47 |
48 | def __repr__(self) -> str:
49 | return f'''<__main__.APIResponse.Completion.Choices(\n text = {self.text.encode()},\n index = {self.index},\n logprobs = {self.logprobs},\n finish_reason = {self.finish_reason})object at 0x1337>'''
50 |
51 | def __init__(self, choices: dict) -> None:
52 | self.choices = [self.Choices(choice) for choice in choices]
53 |
54 | class Usage:
55 | def __init__(self, usage_dict: dict) -> None:
56 | self.prompt_tokens = usage_dict['prompt_tokens']
57 | self.completion_tokens = usage_dict['completion_tokens']
58 | self.total_tokens = usage_dict['total_tokens']
59 |
60 | def __repr__(self):
61 | return f'''<__main__.APIResponse.Usage(\n prompt_tokens = {self.prompt_tokens},\n completion_tokens = {self.completion_tokens},\n total_tokens = {self.total_tokens})object at 0x1337>'''
62 |
63 | def __init__(self, response_dict: dict) -> None:
64 |
65 | self.response_dict = response_dict
66 | self.id = response_dict['id']
67 | self.object = response_dict['object']
68 | self.created = response_dict['created']
69 | self.model = response_dict['model']
70 | self.completion = self.Completion(response_dict['choices'])
71 | self.usage = self.Usage(response_dict['usage'])
72 |
73 | def json(self) -> dict:
74 | return self.response_dict
75 |
76 |
77 | class ModelResponse:
78 | def __init__(self, json_response: dict) -> None:
79 | self.id = json_response['data']['poeBotCreate']['bot']['id']
80 | self.name = json_response['data']['poeBotCreate']['bot']['displayName']
81 | self.limit = json_response['data']['poeBotCreate']['bot']['messageLimit']['dailyLimit']
82 | self.deleted = json_response['data']['poeBotCreate']['bot']['deletionState']
83 |
84 | class Model:
85 | def create(
86 | token: str,
87 | model: str = 'gpt-3.5-turbo', # claude-instant
88 | system_prompt: str = 'You are ChatGPT a large language model developed by Openai. Answer as consisely as possible',
89 | description: str = 'gpt-3.5 language model from openai, skidded by poe.com',
90 | handle: str = None) -> ModelResponse:
91 |
92 | models = {
93 | 'gpt-3.5-turbo' : 'chinchilla',
94 | 'claude-instant-v1.0': 'a2',
95 | 'gpt-4': 'beaver'
96 | }
97 |
98 | if not handle:
99 | handle = f'gptx{randint(1111111, 9999999)}'
100 |
101 | client = Session()
102 | client.cookies['p-b'] = token
103 |
104 | formkey = extract_formkey(client.get('https://poe.com').text)
105 | settings = client.get('https://poe.com/api/settings').json()
106 |
107 | client.headers = {
108 | "host" : "poe.com",
109 | "origin" : "https://poe.com",
110 | "referer" : "https://poe.com/",
111 | "content-type" : "application/json",
112 | "poe-formkey" : formkey,
113 | "poe-tchannel" : settings['tchannelData']['channel'],
114 | "user-agent" : "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36",
115 | "connection" : "keep-alive",
116 | "sec-ch-ua" : "\"Chromium\";v=\"112\", \"Google Chrome\";v=\"112\", \"Not:A-Brand\";v=\"99\"",
117 | "sec-ch-ua-mobile" : "?0",
118 | "sec-ch-ua-platform": "\"macOS\"",
119 | "content-type" : "application/json",
120 | "sec-fetch-site" : "same-origin",
121 | "sec-fetch-mode" : "cors",
122 | "sec-fetch-dest" : "empty",
123 | "accept" : "*/*",
124 | "accept-encoding" : "gzip, deflate, br",
125 | "accept-language" : "en-GB,en-US;q=0.9,en;q=0.8",
126 | }
127 |
128 | payload = dumps(separators=(',', ':'), obj = {
129 | 'queryName': 'CreateBotMain_poeBotCreate_Mutation',
130 | 'variables': {
131 | 'model' : models[model],
132 | 'handle' : handle,
133 | 'prompt' : system_prompt,
134 | 'isPromptPublic' : True,
135 | 'introduction' : '',
136 | 'description' : description,
137 | 'profilePictureUrl' : 'https://qph.fs.quoracdn.net/main-qimg-24e0b480dcd946e1cc6728802c5128b6',
138 | 'apiUrl' : None,
139 | 'apiKey' : ''.join(choices(ascii_letters + digits, k = 32)),
140 | 'isApiBot' : False,
141 | 'hasLinkification' : False,
142 | 'hasMarkdownRendering' : False,
143 | 'hasSuggestedReplies' : False,
144 | 'isPrivateBot' : False
145 | },
146 | 'query': 'mutation CreateBotMain_poeBotCreate_Mutation(\n $model: String!\n $handle: String!\n $prompt: String!\n $isPromptPublic: Boolean!\n $introduction: String!\n $description: String!\n $profilePictureUrl: String\n $apiUrl: String\n $apiKey: String\n $isApiBot: Boolean\n $hasLinkification: Boolean\n $hasMarkdownRendering: Boolean\n $hasSuggestedReplies: Boolean\n $isPrivateBot: Boolean\n) {\n poeBotCreate(model: $model, handle: $handle, promptPlaintext: $prompt, isPromptPublic: $isPromptPublic, introduction: $introduction, description: $description, profilePicture: $profilePictureUrl, apiUrl: $apiUrl, apiKey: $apiKey, isApiBot: $isApiBot, hasLinkification: $hasLinkification, hasMarkdownRendering: $hasMarkdownRendering, hasSuggestedReplies: $hasSuggestedReplies, isPrivateBot: $isPrivateBot) {\n status\n bot {\n id\n ...BotHeader_bot\n }\n }\n}\n\nfragment BotHeader_bot on Bot {\n displayName\n messageLimit {\n dailyLimit\n }\n ...BotImage_bot\n ...BotLink_bot\n ...IdAnnotation_node\n ...botHelpers_useViewerCanAccessPrivateBot\n ...botHelpers_useDeletion_bot\n}\n\nfragment BotImage_bot on Bot {\n displayName\n ...botHelpers_useDeletion_bot\n ...BotImage_useProfileImage_bot\n}\n\nfragment BotImage_useProfileImage_bot on Bot {\n image {\n __typename\n ... on LocalBotImage {\n localName\n }\n ... on UrlBotImage {\n url\n }\n }\n ...botHelpers_useDeletion_bot\n}\n\nfragment BotLink_bot on Bot {\n displayName\n}\n\nfragment IdAnnotation_node on Node {\n __isNode: __typename\n id\n}\n\nfragment botHelpers_useDeletion_bot on Bot {\n deletionState\n}\n\nfragment botHelpers_useViewerCanAccessPrivateBot on Bot {\n isPrivateBot\n viewerIsCreator\n}\n',
147 | })
148 |
149 | base_string = payload + client.headers["poe-formkey"] + 'WpuLMiXEKKE98j56k'
150 | client.headers["poe-tag-id"] = md5(base_string.encode()).hexdigest()
151 |
152 | response = client.post("https://poe.com/api/gql_POST", data = payload)
153 |
154 | if not 'success' in response.text:
155 | raise Exception('''
156 | Bot creation Failed
157 | !! Important !!
158 | Bot creation was not enabled on this account
159 | please use: quora.Account.create with enable_bot_creation set to True
160 | ''')
161 |
162 | return ModelResponse(response.json())
163 |
164 |
165 | class Account:
166 | def create(proxy: None or str = None, logging: bool = False, enable_bot_creation: bool = False):
167 | client = TLS(client_identifier='chrome110')
168 | client.proxies = {
169 | 'http': f'http://{proxy}',
170 | 'https': f'http://{proxy}'} if proxy else None
171 |
172 | mail_client = Emailnator()
173 | mail_address = mail_client.get_mail()
174 |
175 | if logging: print('email', mail_address)
176 |
177 | client.headers = {
178 | 'authority' : 'poe.com',
179 | 'accept' : '*/*',
180 | 'accept-language': 'en,fr-FR;q=0.9,fr;q=0.8,es-ES;q=0.7,es;q=0.6,en-US;q=0.5,am;q=0.4,de;q=0.3',
181 | 'content-type' : 'application/json',
182 | 'origin' : 'https://poe.com',
183 | 'poe-formkey' : 'null',
184 | 'poe-tag-id' : 'null',
185 | 'poe-tchannel' : 'null',
186 | 'referer' : 'https://poe.com/login',
187 | 'sec-ch-ua' : '"Chromium";v="112", "Google Chrome";v="112", "Not:A-Brand";v="99"',
188 | 'sec-ch-ua-mobile' : '?0',
189 | 'sec-ch-ua-platform': '"macOS"',
190 | 'sec-fetch-dest': 'empty',
191 | 'sec-fetch-mode': 'cors',
192 | 'sec-fetch-site': 'same-origin',
193 | 'user-agent' : 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36'
194 | }
195 |
196 | client.headers["poe-formkey"] = extract_formkey(client.get('https://poe.com/login').text)
197 | client.headers["poe-tchannel"] = client.get('https://poe.com/api/settings').json()['tchannelData']['channel']
198 |
199 | token = reCaptchaV3('https://www.recaptcha.net/recaptcha/enterprise/anchor?ar=1&k=6LflhEElAAAAAI_ewVwRWI9hsyV4mbZnYAslSvlG&co=aHR0cHM6Ly9wb2UuY29tOjQ0Mw..&hl=en&v=4PnKmGB9wRHh1i04o7YUICeI&size=invisible&cb=bi6ivxoskyal')
200 | # token = solver.recaptcha(sitekey='6LflhEElAAAAAI_ewVwRWI9hsyV4mbZnYAslSvlG',
201 | # url = 'https://poe.com/login?redirect_url=%2F',
202 | # version = 'v3',
203 | # enterprise = 1,
204 | # invisible = 1,
205 | # action = 'login',)['code']
206 |
207 | payload = dumps(separators = (',', ':'), obj = {
208 | 'queryName': 'MainSignupLoginSection_sendVerificationCodeMutation_Mutation',
209 | 'variables': {
210 | 'emailAddress' : mail_address,
211 | 'phoneNumber' : None,
212 | 'recaptchaToken': token
213 | },
214 | 'query': 'mutation MainSignupLoginSection_sendVerificationCodeMutation_Mutation(\n $emailAddress: String\n $phoneNumber: String\n $recaptchaToken: String\n) {\n sendVerificationCode(verificationReason: login, emailAddress: $emailAddress, phoneNumber: $phoneNumber, recaptchaToken: $recaptchaToken) {\n status\n errorMessage\n }\n}\n',
215 | })
216 |
217 | base_string = payload + client.headers["poe-formkey"] + 'WpuLMiXEKKE98j56k'
218 | client.headers["poe-tag-id"] = md5(base_string.encode()).hexdigest()
219 |
220 | print(dumps(client.headers, indent=4))
221 |
222 | response = client.post('https://poe.com/api/gql_POST', data=payload)
223 |
224 | if 'automated_request_detected' in response.text:
225 | print('please try using a proxy / wait for fix')
226 |
227 | if 'Bad Request' in response.text:
228 | if logging: print('bad request, retrying...' , response.json())
229 | quit()
230 |
231 | if logging: print('send_code' ,response.json())
232 |
233 | mail_content = mail_client.get_message()
234 | mail_token = findall(r';">(\d{6,7})', mail_content)[0]
235 |
236 | if logging: print('code', mail_token)
237 |
238 | payload = dumps(separators = (',', ':'), obj={
239 | "queryName": "SignupOrLoginWithCodeSection_signupWithVerificationCodeMutation_Mutation",
240 | "variables": {
241 | "verificationCode": str(mail_token),
242 | "emailAddress": mail_address,
243 | "phoneNumber": None
244 | },
245 | "query": "mutation SignupOrLoginWithCodeSection_signupWithVerificationCodeMutation_Mutation(\n $verificationCode: String!\n $emailAddress: String\n $phoneNumber: String\n) {\n signupWithVerificationCode(verificationCode: $verificationCode, emailAddress: $emailAddress, phoneNumber: $phoneNumber) {\n status\n errorMessage\n }\n}\n"
246 | })
247 |
248 | base_string = payload + client.headers["poe-formkey"] + 'WpuLMiXEKKE98j56k'
249 | client.headers["poe-tag-id"] = md5(base_string.encode()).hexdigest()
250 |
251 | response = client.post('https://poe.com/api/gql_POST', data = payload)
252 | if logging: print('verify_code', response.json())
253 |
254 | def get():
255 | cookies = open(Path(__file__).resolve().parent / 'cookies.txt', 'r').read().splitlines()
256 | return choice(cookies)
257 |
258 | class StreamingCompletion:
259 | def create(
260 | model : str = 'gpt-4',
261 | custom_model : bool = None,
262 | prompt: str = 'hello world',
263 | token : str = ''):
264 |
265 | models = {
266 | 'sage' : 'capybara',
267 | 'gpt-4' : 'beaver',
268 | 'claude-v1.2' : 'a2_2',
269 | 'claude-instant-v1.0' : 'a2',
270 | 'gpt-3.5-turbo' : 'chinchilla'
271 | }
272 |
273 | _model = models[model] if not custom_model else custom_model
274 |
275 | client = PoeClient(token)
276 |
277 | for chunk in client.send_message(_model, prompt):
278 |
279 | yield PoeResponse({
280 | 'id' : chunk["messageId"],
281 | 'object' : 'text_completion',
282 | 'created': chunk['creationTime'],
283 | 'model' : _model,
284 | 'choices': [{
285 | 'text' : chunk["text_new"],
286 | 'index' : 0,
287 | 'logprobs' : None,
288 | 'finish_reason' : 'stop'
289 | }],
290 | 'usage': {
291 | 'prompt_tokens' : len(prompt),
292 | 'completion_tokens' : len(chunk["text_new"]),
293 | 'total_tokens' : len(prompt) + len(chunk["text_new"])
294 | }
295 | })
296 |
297 | class Completion:
298 | def create(
299 | model : str = 'gpt-4',
300 | custom_model : str = None,
301 | prompt: str = 'hello world',
302 | token : str = ''):
303 |
304 | models = {
305 | 'sage' : 'capybara',
306 | 'gpt-4' : 'beaver',
307 | 'claude-v1.2' : 'a2_2',
308 | 'claude-instant-v1.0' : 'a2',
309 | 'gpt-3.5-turbo' : 'chinchilla'
310 | }
311 |
312 | _model = models[model] if not custom_model else custom_model
313 |
314 | client = PoeClient(token)
315 |
316 | for chunk in client.send_message(_model, prompt):
317 | pass
318 |
319 | return PoeResponse({
320 | 'id' : chunk["messageId"],
321 | 'object' : 'text_completion',
322 | 'created': chunk['creationTime'],
323 | 'model' : _model,
324 | 'choices': [{
325 | 'text' : chunk["text"],
326 | 'index' : 0,
327 | 'logprobs' : None,
328 | 'finish_reason' : 'stop'
329 | }],
330 | 'usage': {
331 | 'prompt_tokens' : len(prompt),
332 | 'completion_tokens' : len(chunk["text"]),
333 | 'total_tokens' : len(prompt) + len(chunk["text"])
334 | }
335 | })
--------------------------------------------------------------------------------
/quora/api.py:
--------------------------------------------------------------------------------
1 | # This file was taken from the repository poe-api https://github.com/ading2210/poe-api and is unmodified
2 | # This file is licensed under the GNU GPL v3 and written by @ading2210
3 |
4 | # license:
5 | # ading2210/poe-api: a reverse engineered Python API wrapepr for Quora's Poe
6 | # Copyright (C) 2023 ading2210
7 |
8 | # This program is free software: you can redistribute it and/or modify
9 | # it under the terms of the GNU General Public License as published by
10 | # the Free Software Foundation, either version 3 of the License, or
11 | # (at your option) any later version.
12 |
13 | # This program is distributed in the hope that it will be useful,
14 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 | # GNU General Public License for more details.
17 |
18 | # You should have received a copy of the GNU General Public License
19 | # along with this program. If not, see .
20 |
21 | import requests
22 | import re
23 | import json
24 | import random
25 | import logging
26 | import time
27 | import queue
28 | import threading
29 | import traceback
30 | import hashlib
31 | import string
32 | import random
33 | import requests.adapters
34 | import websocket
35 | from pathlib import Path
36 | from urllib.parse import urlparse
37 |
38 |
39 | parent_path = Path(__file__).resolve().parent
40 | queries_path = parent_path / "graphql"
41 | queries = {}
42 |
43 | logging.basicConfig()
44 | logger = logging.getLogger()
45 |
46 | user_agent = "Mozilla/5.0 (X11; Linux x86_64; rv:102.0) Gecko/20100101 Firefox/102.0"
47 |
48 |
49 | def load_queries():
50 | for path in queries_path.iterdir():
51 | if path.suffix != ".graphql":
52 | continue
53 | with open(path) as f:
54 | queries[path.stem] = f.read()
55 |
56 |
57 | def generate_payload(query_name, variables):
58 | return {
59 | "query": queries[query_name],
60 | "variables": variables
61 | }
62 |
63 |
64 | def request_with_retries(method, *args, **kwargs):
65 | attempts = kwargs.get("attempts") or 10
66 | url = args[0]
67 | for i in range(attempts):
68 | r = method(*args, **kwargs)
69 | if r.status_code == 200:
70 | return r
71 | logger.warn(
72 | f"Server returned a status code of {r.status_code} while downloading {url}. Retrying ({i+1}/{attempts})...")
73 |
74 | raise RuntimeError(f"Failed to download {url} too many times.")
75 |
76 |
77 | class Client:
78 | gql_url = "https://poe.com/api/gql_POST"
79 | gql_recv_url = "https://poe.com/api/receive_POST"
80 | home_url = "https://poe.com"
81 | settings_url = "https://poe.com/api/settings"
82 |
83 | def __init__(self, token, proxy=None):
84 | self.proxy = proxy
85 | self.session = requests.Session()
86 | self.adapter = requests.adapters.HTTPAdapter(
87 | pool_connections=100, pool_maxsize=100)
88 | self.session.mount("http://", self.adapter)
89 | self.session.mount("https://", self.adapter)
90 |
91 | if proxy:
92 | self.session.proxies = {
93 | "http": self.proxy,
94 | "https": self.proxy
95 | }
96 | logger.info(f"Proxy enabled: {self.proxy}")
97 |
98 | self.active_messages = {}
99 | self.message_queues = {}
100 |
101 | self.session.cookies.set("p-b", token, domain="poe.com")
102 | self.headers = {
103 | "User-Agent": user_agent,
104 | "Referrer": "https://poe.com/",
105 | "Origin": "https://poe.com",
106 | }
107 | self.session.headers.update(self.headers)
108 |
109 | self.setup_connection()
110 | self.connect_ws()
111 |
112 | def setup_connection(self):
113 | self.ws_domain = f"tch{random.randint(1, 1e6)}"
114 | self.next_data = self.get_next_data(overwrite_vars=True)
115 | self.channel = self.get_channel_data()
116 | self.bots = self.get_bots(download_next_data=False)
117 | self.bot_names = self.get_bot_names()
118 |
119 | self.gql_headers = {
120 | "poe-formkey": self.formkey,
121 | "poe-tchannel": self.channel["channel"],
122 | }
123 | self.gql_headers = {**self.gql_headers, **self.headers}
124 | self.subscribe()
125 |
126 | def extract_formkey(self, html):
127 | script_regex = r''
128 | script_text = re.search(script_regex, html).group(1)
129 | key_regex = r'var .="([0-9a-f]+)",'
130 | key_text = re.search(key_regex, script_text).group(1)
131 | cipher_regex = r'.\[(\d+)\]=.\[(\d+)\]'
132 | cipher_pairs = re.findall(cipher_regex, script_text)
133 |
134 | formkey_list = [""] * len(cipher_pairs)
135 | for pair in cipher_pairs:
136 | formkey_index, key_index = map(int, pair)
137 | formkey_list[formkey_index] = key_text[key_index]
138 | formkey = "".join(formkey_list)
139 |
140 | return formkey
141 |
142 | def get_next_data(self, overwrite_vars=False):
143 | logger.info("Downloading next_data...")
144 |
145 | r = request_with_retries(self.session.get, self.home_url)
146 | json_regex = r''
147 | json_text = re.search(json_regex, r.text).group(1)
148 | next_data = json.loads(json_text)
149 |
150 | if overwrite_vars:
151 | self.formkey = self.extract_formkey(r.text)
152 | self.viewer = next_data["props"]["pageProps"]["payload"]["viewer"]
153 | self.next_data = next_data
154 |
155 | return next_data
156 |
157 | def get_bot(self, display_name):
158 | url = f'https://poe.com/_next/data/{self.next_data["buildId"]}/{display_name}.json'
159 |
160 | r = request_with_retries(self.session.get, url)
161 |
162 | chat_data = r.json()["pageProps"]["payload"]["chatOfBotDisplayName"]
163 | return chat_data
164 |
165 | def get_bots(self, download_next_data=True):
166 | logger.info("Downloading all bots...")
167 | if download_next_data:
168 | next_data = self.get_next_data(overwrite_vars=True)
169 | else:
170 | next_data = self.next_data
171 |
172 | if not "availableBots" in self.viewer:
173 | raise RuntimeError("Invalid token or no bots are available.")
174 | bot_list = self.viewer["availableBots"]
175 |
176 | threads = []
177 | bots = {}
178 |
179 | def get_bot_thread(bot):
180 | chat_data = self.get_bot(bot["displayName"])
181 | bots[chat_data["defaultBotObject"]["nickname"]] = chat_data
182 |
183 | for bot in bot_list:
184 | thread = threading.Thread(
185 | target=get_bot_thread, args=(bot,), daemon=True)
186 | threads.append(thread)
187 |
188 | for thread in threads:
189 | thread.start()
190 | for thread in threads:
191 | thread.join()
192 |
193 | self.bots = bots
194 | self.bot_names = self.get_bot_names()
195 | return bots
196 |
197 | def get_bot_names(self):
198 | bot_names = {}
199 | for bot_nickname in self.bots:
200 | bot_obj = self.bots[bot_nickname]["defaultBotObject"]
201 | bot_names[bot_nickname] = bot_obj["displayName"]
202 | return bot_names
203 |
204 | def get_remaining_messages(self, chatbot):
205 | chat_data = self.get_bot(self.bot_names[chatbot])
206 | return chat_data["defaultBotObject"]["messageLimit"]["numMessagesRemaining"]
207 |
208 | def get_channel_data(self, channel=None):
209 | logger.info("Downloading channel data...")
210 | r = request_with_retries(self.session.get, self.settings_url)
211 | data = r.json()
212 |
213 | return data["tchannelData"]
214 |
215 | def get_websocket_url(self, channel=None):
216 | if channel is None:
217 | channel = self.channel
218 | query = f'?min_seq={channel["minSeq"]}&channel={channel["channel"]}&hash={channel["channelHash"]}'
219 | return f'wss://{self.ws_domain}.tch.{channel["baseHost"]}/up/{channel["boxName"]}/updates'+query
220 |
221 | def send_query(self, query_name, variables):
222 | for i in range(20):
223 | json_data = generate_payload(query_name, variables)
224 | payload = json.dumps(json_data, separators=(",", ":"))
225 |
226 | base_string = payload + \
227 | self.gql_headers["poe-formkey"] + "WpuLMiXEKKE98j56k"
228 |
229 | headers = {
230 | "content-type": "application/json",
231 | "poe-tag-id": hashlib.md5(base_string.encode()).hexdigest()
232 | }
233 | headers = {**self.gql_headers, **headers}
234 |
235 | r = request_with_retries(
236 | self.session.post, self.gql_url, data=payload, headers=headers)
237 |
238 | data = r.json()
239 | if data["data"] == None:
240 | logger.warn(
241 | f'{query_name} returned an error: {data["errors"][0]["message"]} | Retrying ({i+1}/20)')
242 | time.sleep(2)
243 | continue
244 |
245 | return r.json()
246 |
247 | raise RuntimeError(f'{query_name} failed too many times.')
248 |
249 | def subscribe(self):
250 | logger.info("Subscribing to mutations")
251 | result = self.send_query("SubscriptionsMutation", {
252 | "subscriptions": [
253 | {
254 | "subscriptionName": "messageAdded",
255 | "query": queries["MessageAddedSubscription"]
256 | },
257 | {
258 | "subscriptionName": "viewerStateUpdated",
259 | "query": queries["ViewerStateUpdatedSubscription"]
260 | }
261 | ]
262 | })
263 |
264 | def ws_run_thread(self):
265 | kwargs = {}
266 | if self.proxy:
267 | proxy_parsed = urlparse(self.proxy)
268 | kwargs = {
269 | "proxy_type": proxy_parsed.scheme,
270 | "http_proxy_host": proxy_parsed.hostname,
271 | "http_proxy_port": proxy_parsed.port
272 | }
273 |
274 | self.ws.run_forever(**kwargs)
275 |
276 | def connect_ws(self):
277 | self.ws_connected = False
278 | self.ws = websocket.WebSocketApp(
279 | self.get_websocket_url(),
280 | header={"User-Agent": user_agent},
281 | on_message=self.on_message,
282 | on_open=self.on_ws_connect,
283 | on_error=self.on_ws_error,
284 | on_close=self.on_ws_close
285 | )
286 | t = threading.Thread(target=self.ws_run_thread, daemon=True)
287 | t.start()
288 | while not self.ws_connected:
289 | time.sleep(0.01)
290 |
291 | def disconnect_ws(self):
292 | if self.ws:
293 | self.ws.close()
294 | self.ws_connected = False
295 |
296 | def on_ws_connect(self, ws):
297 | self.ws_connected = True
298 |
299 | def on_ws_close(self, ws, close_status_code, close_message):
300 | self.ws_connected = False
301 | logger.warn(
302 | f"Websocket closed with status {close_status_code}: {close_message}")
303 |
304 | def on_ws_error(self, ws, error):
305 | self.disconnect_ws()
306 | self.connect_ws()
307 |
308 | def on_message(self, ws, msg):
309 | try:
310 | data = json.loads(msg)
311 |
312 | if not "messages" in data:
313 | return
314 |
315 | for message_str in data["messages"]:
316 | message_data = json.loads(message_str)
317 | if message_data["message_type"] != "subscriptionUpdate":
318 | continue
319 | message = message_data["payload"]["data"]["messageAdded"]
320 |
321 | copied_dict = self.active_messages.copy()
322 | for key, value in copied_dict.items():
323 | # add the message to the appropriate queue
324 | if value == message["messageId"] and key in self.message_queues:
325 | self.message_queues[key].put(message)
326 | return
327 |
328 | # indicate that the response id is tied to the human message id
329 | elif key != "pending" and value == None and message["state"] != "complete":
330 | self.active_messages[key] = message["messageId"]
331 | self.message_queues[key].put(message)
332 | return
333 |
334 | except Exception:
335 | logger.error(traceback.format_exc())
336 | self.disconnect_ws()
337 | self.connect_ws()
338 |
339 | def send_message(self, chatbot, message, with_chat_break=False, timeout=20):
340 | # if there is another active message, wait until it has finished sending
341 | while None in self.active_messages.values():
342 | time.sleep(0.01)
343 |
344 | # None indicates that a message is still in progress
345 | self.active_messages["pending"] = None
346 |
347 | logger.info(f"Sending message to {chatbot}: {message}")
348 |
349 | # reconnect websocket
350 | if not self.ws_connected:
351 | self.disconnect_ws()
352 | self.setup_connection()
353 | self.connect_ws()
354 |
355 | message_data = self.send_query("SendMessageMutation", {
356 | "bot": chatbot,
357 | "query": message,
358 | "chatId": self.bots[chatbot]["chatId"],
359 | "source": None,
360 | "withChatBreak": with_chat_break
361 | })
362 | del self.active_messages["pending"]
363 |
364 | if not message_data["data"]["messageEdgeCreate"]["message"]:
365 | raise RuntimeError(f"Daily limit reached for {chatbot}.")
366 | try:
367 | human_message = message_data["data"]["messageEdgeCreate"]["message"]
368 | human_message_id = human_message["node"]["messageId"]
369 | except TypeError:
370 | raise RuntimeError(
371 | f"An unknown error occurred. Raw response data: {message_data}")
372 |
373 | # indicate that the current message is waiting for a response
374 | self.active_messages[human_message_id] = None
375 | self.message_queues[human_message_id] = queue.Queue()
376 |
377 | last_text = ""
378 | message_id = None
379 | while True:
380 | try:
381 | message = self.message_queues[human_message_id].get(
382 | timeout=timeout)
383 | except queue.Empty:
384 | del self.active_messages[human_message_id]
385 | del self.message_queues[human_message_id]
386 | raise RuntimeError("Response timed out.")
387 |
388 | # only break when the message is marked as complete
389 | if message["state"] == "complete":
390 | if last_text and message["messageId"] == message_id:
391 | break
392 | else:
393 | continue
394 |
395 | # update info about response
396 | message["text_new"] = message["text"][len(last_text):]
397 | last_text = message["text"]
398 | message_id = message["messageId"]
399 |
400 | yield message
401 |
402 | del self.active_messages[human_message_id]
403 | del self.message_queues[human_message_id]
404 |
405 | def send_chat_break(self, chatbot):
406 | logger.info(f"Sending chat break to {chatbot}")
407 | result = self.send_query("AddMessageBreakMutation", {
408 | "chatId": self.bots[chatbot]["chatId"]
409 | })
410 | return result["data"]["messageBreakCreate"]["message"]
411 |
412 | def get_message_history(self, chatbot, count=25, cursor=None):
413 | logger.info(f"Downloading {count} messages from {chatbot}")
414 |
415 | messages = []
416 | if cursor == None:
417 | chat_data = self.get_bot(self.bot_names[chatbot])
418 | if not chat_data["messagesConnection"]["edges"]:
419 | return []
420 | messages = chat_data["messagesConnection"]["edges"][:count]
421 | cursor = chat_data["messagesConnection"]["pageInfo"]["startCursor"]
422 | count -= len(messages)
423 |
424 | cursor = str(cursor)
425 | if count > 50:
426 | messages = self.get_message_history(
427 | chatbot, count=50, cursor=cursor) + messages
428 | while count > 0:
429 | count -= 50
430 | new_cursor = messages[0]["cursor"]
431 | new_messages = self.get_message_history(
432 | chatbot, min(50, count), cursor=new_cursor)
433 | messages = new_messages + messages
434 | return messages
435 | elif count <= 0:
436 | return messages
437 |
438 | result = self.send_query("ChatListPaginationQuery", {
439 | "count": count,
440 | "cursor": cursor,
441 | "id": self.bots[chatbot]["id"]
442 | })
443 | query_messages = result["data"]["node"]["messagesConnection"]["edges"]
444 | messages = query_messages + messages
445 | return messages
446 |
447 | def delete_message(self, message_ids):
448 | logger.info(f"Deleting messages: {message_ids}")
449 | if not type(message_ids) is list:
450 | message_ids = [int(message_ids)]
451 |
452 | result = self.send_query("DeleteMessageMutation", {
453 | "messageIds": message_ids
454 | })
455 |
456 | def purge_conversation(self, chatbot, count=-1):
457 | logger.info(f"Purging messages from {chatbot}")
458 | last_messages = self.get_message_history(chatbot, count=50)[::-1]
459 | while last_messages:
460 | message_ids = []
461 | for message in last_messages:
462 | if count == 0:
463 | break
464 | count -= 1
465 | message_ids.append(message["node"]["messageId"])
466 |
467 | self.delete_message(message_ids)
468 |
469 | if count == 0:
470 | return
471 | last_messages = self.get_message_history(chatbot, count=50)[::-1]
472 | logger.info(f"No more messages left to delete.")
473 |
474 | def create_bot(self, handle, prompt="", base_model="chinchilla", description="",
475 | intro_message="", api_key=None, api_bot=False, api_url=None,
476 | prompt_public=True, pfp_url=None, linkification=False,
477 | markdown_rendering=True, suggested_replies=False, private=False):
478 | result = self.send_query("PoeBotCreateMutation", {
479 | "model": base_model,
480 | "handle": handle,
481 | "prompt": prompt,
482 | "isPromptPublic": prompt_public,
483 | "introduction": intro_message,
484 | "description": description,
485 | "profilePictureUrl": pfp_url,
486 | "apiUrl": api_url,
487 | "apiKey": api_key,
488 | "isApiBot": api_bot,
489 | "hasLinkification": linkification,
490 | "hasMarkdownRendering": markdown_rendering,
491 | "hasSuggestedReplies": suggested_replies,
492 | "isPrivateBot": private
493 | })
494 |
495 | data = result["data"]["poeBotCreate"]
496 | if data["status"] != "success":
497 | raise RuntimeError(
498 | f"Poe returned an error while trying to create a bot: {data['status']}")
499 | self.get_bots()
500 | return data
501 |
502 | def edit_bot(self, bot_id, handle, prompt="", base_model="chinchilla", description="",
503 | intro_message="", api_key=None, api_url=None, private=False,
504 | prompt_public=True, pfp_url=None, linkification=False,
505 | markdown_rendering=True, suggested_replies=False):
506 |
507 | result = self.send_query("PoeBotEditMutation", {
508 | "baseBot": base_model,
509 | "botId": bot_id,
510 | "handle": handle,
511 | "prompt": prompt,
512 | "isPromptPublic": prompt_public,
513 | "introduction": intro_message,
514 | "description": description,
515 | "profilePictureUrl": pfp_url,
516 | "apiUrl": api_url,
517 | "apiKey": api_key,
518 | "hasLinkification": linkification,
519 | "hasMarkdownRendering": markdown_rendering,
520 | "hasSuggestedReplies": suggested_replies,
521 | "isPrivateBot": private
522 | })
523 |
524 | data = result["data"]["poeBotEdit"]
525 | if data["status"] != "success":
526 | raise RuntimeError(
527 | f"Poe returned an error while trying to edit a bot: {data['status']}")
528 | self.get_bots()
529 | return data
530 |
531 |
532 | load_queries()
533 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------