File size: 13,588 Bytes
800c3fe
eb66930
 
 
 
059b687
800c3fe
5b050cd
eb66930
2534873
728813a
 
 
 
 
358e5eb
 
d8fdacf
eb66930
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
800c3fe
eb66930
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
800c3fe
eb66930
 
 
 
 
059b687
 
 
 
 
 
 
 
 
 
 
 
 
 
2712829
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
059b687
 
 
316cb3c
059b687
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1784e62
 
059b687
 
800c3fe
059b687
 
 
 
 
 
 
f7dbd93
fe6b177
 
 
059b687
 
f7dbd93
059b687
 
f7dbd93
059b687
 
 
a02b434
059b687
439916b
fe6b177
 
 
 
059b687
 
 
 
 
 
eb66930
 
 
 
 
 
 
 
 
 
 
87ac6bc
eafcc29
eb66930
eafcc29
3406933
87ac6bc
3406933
 
eb66930
 
 
3406933
0080433
 
87ac6bc
3406933
 
 
 
87ac6bc
3406933
 
 
 
 
 
 
 
 
7d152fb
eb66930
 
 
 
eafcc29
eb66930
 
 
 
 
 
 
059b687
eb66930
 
0080433
eb66930
 
 
 
 
 
 
 
2534873
7260287
 
2534873
7260287
 
880cff7
2534873
30abb48
 
 
 
 
 
 
 
 
 
eb66930
 
 
30abb48
 
eb66930
 
 
 
 
 
 
 
 
 
 
 
 
 
f7dbd93
 
 
 
 
 
 
eb66930
 
 
 
 
 
416f85b
eb66930
 
 
 
 
416f85b
eb66930
 
 
 
 
 
 
416f85b
 
 
eb66930
 
 
 
 
 
 
76adc9d
 
eb66930
 
 
 
 
 
 
 
 
 
 
 
f7dbd93
eb66930
f7dbd93
eb66930
 
 
9e49dff
 
 
 
 
 
eb66930
 
 
 
2534873
 
eb66930
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
import json
import gradio as gr
import uuid
import time
import random
import os
from curl_cffi import requests
import re

proxies = None
# proxies = {
#     'http': 'http://127.0.0.1:7680',
#     'https': 'https://127.0.0.1:7680',
#     # 'socks5':"socks5://127.0.0.1:10808",
# }
 
print(f"服务器地址:{requests.get('http://ip.klinson.com/').text}")

# 创建新的聊天频道
def generate_uuid():
    random_uuid = uuid.uuid4()
    random_uuid_str = str(random_uuid)
    formatted_uuid = f"{random_uuid_str[0:8]}-{random_uuid_str[9:13]}-{random_uuid_str[14:18]}-{random_uuid_str[19:23]}-{random_uuid_str[24:]}"
    return formatted_uuid


# Deletes the conversation
def delete_conversation(user_id,channel_id,cookie):
    url = f"https://claude.ai/api/organizations/{user_id}/chat_conversations/{channel_id}"

    payload = json.dumps(f"{channel_id}")
    headers = {
        'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36 Edg/114.0.1823.82',
        'Accept-Language': 'en-US,en;q=0.5',
        'Content-Type': 'application/json',
        'Content-Length': '38',
        'Referer': 'https://claude.ai/chats',
        'Origin': 'https://claude.ai',
        'Sec-Fetch-Dest': 'empty',
        'Sec-Fetch-Mode': 'cors',
        'Sec-Fetch-Site': 'same-origin',
        'Connection': 'keep-alive',
        'Cookie': f'{cookie}',
        'TE': 'trailers'
    }

    response = requests.delete(url, headers=headers, data=payload,impersonate="chrome110")
    # Returns True if deleted or False if any error in deleting
    if response.status_code == 204:
        return True
    else:
        return False

def create_new_chat(user_id,cookie):
    url = f"https://claude.ai/api/organizations/{user_id}/chat_conversations"
    uuid = generate_uuid()

    payload = json.dumps({"uuid": uuid, "name": ""})
    headers = {
        'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36 Edg/114.0.1823.82',
        'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
        'Referer': 'https://claude.ai/chats',
        'Content-Type': 'application/json',
        'Origin': 'https://claude.ai',
        'Connection': 'keep-alive',
        'Cookie': cookie,
        'Sec-Fetch-Dest': 'empty',
        'Sec-Fetch-Mode': 'cors',
        'Sec-Fetch-Site': 'same-origin',
    }

    # response = requests.request("POST", url, headers=headers, data=payload)
    # 使用代理,解决国内网络不能访问问题
    # response = request("POST", url, headers=headers, data=payload, proxies=proxies)
    response = requests.post(url, headers=headers, data=payload,impersonate="chrome110")
    print(f"新的对话页面:{response.json()}")

    # Returns JSON of the newly created conversation information
    return response.json()

def get_content_type(file_path):
    # Function to determine content type based on file extension
    extension = os.path.splitext(file_path)[-1].lower()
    if extension == '.pdf':
        return 'application/pdf'
    elif extension == '.txt':
        return 'text/plain'
    elif extension == '.csv':
        return 'text/csv'
    # Add more content types as needed for other file types
    else:
        return 'application/octet-stream'

def upload_attachment(cookie ,organization_id,file_path):
    ## 自己解析
    if file_path.endswith(('.txt', '.pdf', '.csv')):
        file_name = os.path.basename(file_path)
        file_size = os.path.getsize(file_path)
        file_type = "text/plain"
        with open(file_path, 'r', encoding='utf-8') as file:
            file_content = file.read()
            print({
            "file_name": file_name,
            "file_type": file_type,
            "file_size": file_size,
            "extracted_content": file_content})

        return {
            "file_name": file_name,
            "file_type": file_type,
            "file_size": file_size,
            "extracted_content": file_content
        }



    url = 'https://claude.ai/api/convert_document'
    headers = {
        'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36 Edg/114.0.1823.82',
        'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
        'Referer': 'https://claude.ai/chats',
        'Origin': 'https://claude.ai',
        'Sec-Fetch-Dest': 'empty',
        'Sec-Fetch-Mode': 'cors',
        'Sec-Fetch-Site': 'same-origin',
        'Connection': 'keep-alive',
        'Cookie': f'{cookie}',
        'TE': 'trailers'
    }

    file_name = os.path.basename(file_path)
    print(file_name)
    content_type = get_content_type(file_path)
    print(content_type)
    files = {
        'file': (file_name, open(file_path, 'rb'), content_type),
        'orgUuid': (None, organization_id)
        # 'orgUuid': organization_id
    }
    print(files)
    response = requests.post(url, headers=headers, files=files,impersonate="chrome110")
    if response.status_code == 200:
        return response.json()
    else:
        return False



def request_to_v2(message, cookie, user_id,attachment=None,delst=True,context=[]):
    context = [message]
    
    
    ## 是否加入文件
    # Upload attachment if provided
    
    attachments = []
    if attachment:
        attachment = attachment.name
        attachment_response = upload_attachment(cookie,user_id,attachment)
        if attachment_response:
            attachments = [attachment_response]
            print(f"attachment_response:{attachment_response}")
        else:
            bots = "\nError: Invalid file format. Please try again."
            print(bots)
            context += [bots]
            responses = [(u, b) for u, b in zip(context[::2], context[1::2])]
            return responses, context

    # Ensure attachments is an empty list when no attachment is provided
    if not attachment:
        attachments = []        



    response_json = create_new_chat(user_id,cookie)
    channel_id = response_json.get('uuid',"")
    print(channel_id)

    
    timeout = 5*60 #5分钟不回复,显示超时
    context = [message]
    headers = {
        'Content-Type': 'application/json',
        'Origin': 'https://claude.ai',
        # 'Referer': f'https://claude.ai/chat/{channel_id}',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36 Edg/114.0.1823.82',
        'Cookie': cookie,
        'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
        'Accept': 'text/event-stream, text/event-stream',
        # 'Sec-Ch-Ua': '"Not.A/Brand";v="8", "Chromium";v="114", "Microsoft Edge";v="114"',
        'Sec-Ch-Ua-Mobile': '?0',
        'Sec-Ch-Ua-Platform': '"Windows"',
        'Sec-Fetch-Dest': 'empty',
        'Sec-Fetch-Mode': 'cors',
        'Sec-Fetch-Site': 'same-origin',
        'Connection': 'keep-alive',
        'TE': 'trailers',
        'DNT': '1',
       

        # 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/115.0',
        # 'Accept': 'text/event-stream, text/event-stream',
        # 'Accept-Language': 'en-US,en;q=0.5',
        'Referer': 'https://claude.ai/chats',
        # 'Content-Type': 'application/json',
        # 'Origin': 'https://claude.ai',
        # 'DNT': '1',
        # 'Connection': 'keep-alive',
        # 'Cookie': cookie,
        # 'Sec-Fetch-Dest': 'empty',
        # 'Sec-Fetch-Mode': 'cors',
        # 'Sec-Fetch-Site': 'same-origin',
        # 'TE': 'trailers'
        
    }
    post_msg_url = 'https://claude.ai/api/append_message'
    post_msg_data = {
        "completion":{
            # "incremental":True,
            "prompt": message,
            "timezone":"Asia/Shanghai",
            "model":"claude-2"
        },
        "organization_uuid": user_id,
        "conversation_uuid": channel_id,
        "text": message,
        "attachments": attachments
    }
    post_msg_data = json.dumps(post_msg_data)
    print(post_msg_data)

    response = {
        "status_code":-1,
        "text":"报错啦"
    }

    try:
        print(f"输入的问题:{message}")
        if proxies:
            # response = requests.post(post_msg_url, headers=headers, data=post_msg_data, verify=False, stream=False,timeout = timeout)
            print("使用代理.")
            response = requests.post(post_msg_url, headers=headers, data=post_msg_data, verify=False, stream=False,timeout = timeout, proxies=proxies)
        else:
            print("******不使用代理.")
            response = requests.post(post_msg_url, headers=headers, data=post_msg_data, verify=False,timeout = timeout,impersonate="chrome110")
            
        decoded_data = response.content.decode("utf-8")
        decoded_data = re.sub('\n+', '\n', decoded_data).strip()
        data_strings = decoded_data.split('\n')
        completions = []
        for data_string in data_strings:
            json_str = data_string[6:].strip()
            data = json.loads(json_str)
            if 'completion' in data:
                completions.append(data['completion'])
        bots = ''.join(completions)
        print(bots)
        context += [bots]
        responses = [(u, b) for u, b in zip(context[::2], context[1::2])]
        print("a"*100)
        
        return responses, context

    except Exception as e:
        print(">>>>>> 查询失败")
        print(e)
        print(response.text)

        response =">>>>>> 查询失败\n报错信息为:"+ str(e) + f"\n response信息:\n错误代码:{response.status_code}\n错误信息{response.text}"
        context += [response]
        responses = [(u, b) for u, b in zip(context[::2], context[1::2])]

        return responses, context

    finally:
        if delst:
            time.sleep(random.uniform(1,2))
            ds = delete_conversation(user_id,channel_id,cookie)
            if ds:
                print(f"成功删除")
            else:
                print(f"删除失败")

        print("*-"*100)



with gr.Blocks() as dialog_app:
    gr.HTML("""<h1 align="center">Claude2-API-xiaolv-第3版-单轮对话-支持文件知识库</h1>""")
    with gr.Tab("Claude2 API xiaolv"):
        gr.Markdown("""
        ## 需要传入的参数有:
        1.cookie:intercom-device-id-lupk8zyo=8888
        2.user_id:对应 organization_uuid
        3.file:上传文件,可传可不传,如果需要基于文件进行问答,可以选择上传(支持:txt、csv、pdf格式)
        ## 特点:
        1. 根据传入的cookie 和 user_id 自动创建一个新的聊天频道(conversation_uuid/channel_id);
        2. 在新的聊天聊天频道进行对话;
        3. 请求放回后,自动删除新的聊天频道,避免频繁调用导致页面太多记录。
        4. 模型只能进行一次聊天,对于特定场景比较有用,防止模型记住历史数据,影响模型对实际数据的输出额判断。
        """)
        gr.HTML(
        """<p>5.如果想多轮对话的话,可以参考以下这个地址:<a href="https://huggingface.co/spaces/xiaolv/claude2_xiaolv">Claude2-API-xiaolv-第1版-多轮对话</a></p>"""
        """<p>6.如果只想回复一次的话,可以参考以下这个地址:<a href="https://huggingface.co/spaces/xiaolv/claude2_xiaolv_api_updata">Claude2-API-xiaolv-第2版-单轮对话</a></p>"""
        """<p>如果喜欢请给个 💖 </p>"""
        )
        

        with gr.Row():
            with gr.Column(scale=0.4):
                cookies = gr.Textbox(lines=2, label="输入cookies")
                user_id = gr.Textbox(lines=2, label="输入user_id/organization_uuid")
                file = gr.File(label='请上传知识库文件, 目前支持txt、csv、pdf格式,不超过10M,可传可不传',file_types=['.txt', '.csv', '.pdf'])
                delst = gr.Checkbox(label="是", info="在该对话回复后,是否要删除该对话?(默认会删除)",value = True)
                # channel_id = gr.Textbox(lines=2, label="输入channel_id/conversation_uuid")
                # chatbot = gr.Chatbot()
            with gr.Column(scale=0.6):
                chatbot = gr.Chatbot([])

            state = gr.State([])

        with gr.Row():
            inputs = gr.Textbox(
                label="输入问题",
                placeholder="请输入你的文本,确保已经正确填入cookies、user_id"
            )
        inputs.submit(request_to_v2, [inputs, cookies, user_id,file,delst,state], [chatbot, state])
        send = gr.Button("发送请求.....")
        send.click(request_to_v2, [inputs, cookies, user_id,file,delst,state], [chatbot, state], api_name="xiaolvgpt", show_progress=True)


        gr.Markdown("""
        清除历史记录是,请输入:```/resrt```
        >>> 2023-08-21:修复“We are unable to serve your request ”问题,替换成curl_cffi 模拟浏览器模式。
        
        ** 参考github资料 **
        <a href="https://github.com/wwwzhouhui/Claude2-PyAPI">1. Claude2-PyAPI源码魔改地址</a>
        """)     
        
# 为网站设置密码防止滥用
# dialog_app.launch(auth=("admin", "2240560729"),show_error=True,show_api=True,share=True)
# dialog_app.launch(auth=("admin", "2240560729"),show_error=True)
# dialog_app.launch(show_error=True,server_port = 7861)
dialog_app.launch(show_error=True)
# dialog_app.launch(show_error=True,show_api=True,share=True)