magicboris commited on
Commit
8fbc2e8
·
verified ·
1 Parent(s): 0433c79

Delete hf_private_boris.ipynb

Browse files
Files changed (1) hide show
  1. hf_private_boris.ipynb +0 -355
hf_private_boris.ipynb DELETED
@@ -1,355 +0,0 @@
1
- {
2
- "cells": [
3
- {
4
- "cell_type": "code",
5
- "execution_count": 1,
6
- "metadata": {},
7
- "outputs": [
8
- {
9
- "ename": "ModuleNotFoundError",
10
- "evalue": "No module named 'random_user_agent'",
11
- "output_type": "error",
12
- "traceback": [
13
- "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
14
- "\u001b[1;31mModuleNotFoundError\u001b[0m Traceback (most recent call last)",
15
- "Cell \u001b[1;32mIn[1], line 3\u001b[0m\n\u001b[0;32m 1\u001b[0m \u001b[38;5;28;01mimport\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[38;5;21;01mrequests\u001b[39;00m\u001b[38;5;241m,\u001b[39m\u001b[38;5;250m \u001b[39m\u001b[38;5;21;01mjson\u001b[39;00m\u001b[38;5;241m,\u001b[39m\u001b[38;5;250m \u001b[39m\u001b[38;5;21;01muuid\u001b[39;00m\u001b[38;5;241m,\u001b[39m\u001b[38;5;250m \u001b[39m\u001b[38;5;21;01mtime\u001b[39;00m\n\u001b[0;32m 2\u001b[0m \u001b[38;5;28;01mfrom\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[38;5;21;01mflask\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[38;5;28;01mimport\u001b[39;00m Flask, request, Response, stream_with_context, jsonify\n\u001b[1;32m----> 3\u001b[0m \u001b[38;5;28;01mfrom\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[38;5;21;01mrandom_user_agent\u001b[39;00m\u001b[38;5;21;01m.\u001b[39;00m\u001b[38;5;21;01muser_agent\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[38;5;28;01mimport\u001b[39;00m UserAgent\n\u001b[0;32m 4\u001b[0m \u001b[38;5;28;01mfrom\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[38;5;21;01mrandom_user_agent\u001b[39;00m\u001b[38;5;21;01m.\u001b[39;00m\u001b[38;5;21;01mparams\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[38;5;28;01mimport\u001b[39;00m SoftwareName, OperatingSystem\n\u001b[0;32m 5\u001b[0m \u001b[38;5;28;01mfrom\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[38;5;21;01mtime\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[38;5;28;01mimport\u001b[39;00m time \u001b[38;5;28;01mas\u001b[39;00m current_time\n",
16
- "\u001b[1;31mModuleNotFoundError\u001b[0m: No module named 'random_user_agent'"
17
- ]
18
- }
19
- ],
20
- "source": [
21
- "import requests, json, uuid, time\n",
22
- "from flask import Flask, request, Response, stream_with_context, jsonify\n",
23
- "from random_user_agent.user_agent import UserAgent\n",
24
- "from random_user_agent.params import SoftwareName, OperatingSystem\n",
25
- "from time import time as current_time\n",
26
- "import os\n",
27
- "from functools import wraps\n",
28
- "from dotenv import load_dotenv\n",
29
- "\n",
30
- "load_dotenv()\n",
31
- "\n",
32
- "app = Flask(__name__)\n",
33
- "\n",
34
- "completed_prompts = 0\n",
35
- "active_streams = 0\n",
36
- "total_duration = 0.0\n",
37
- "\n",
38
- "software_names = [SoftwareName.CHROME.value]\n",
39
- "operating_systems = [OperatingSystem.WINDOWS.value, OperatingSystem.LINUX.value]\n",
40
- "user_agent_rotator = UserAgent(software_names=software_names, operating_systems=operating_systems)\n",
41
- "user_agent = f\"{user_agent_rotator.get_random_user_agent()} VSCode/1.96.4\"\n",
42
- "\n",
43
- "PROXY_PASSWORD = os.getenv('PROXY_PASSWORD')\n",
44
- "key = os.getenv('ACCESS_TOKEN')\n",
45
- "API_ENDPOINT = \"https://codestory-provider-dot-anton-390822.ue.r.appspot.com/openrouter-api\"\n",
46
- "\n",
47
- "def get_external_url_for_huggingface_space(space_id: str) -> str:\n",
48
- " try:\n",
49
- " username, spacename = space_id.split(\"/\")\n",
50
- " return f\"https://{username}-{spacename.replace('_', '-')}.hf.space\"\n",
51
- " except Exception as e:\n",
52
- " print(f\"Error generating Hugging Face Space URL: {e}\")\n",
53
- " return \"\"\n",
54
- "\n",
55
- "def get_base_url(request) -> str:\n",
56
- " space_id = os.getenv('SPACE_ID')\n",
57
- " if space_id and \"hf.space\" not in request.host:\n",
58
- " return get_external_url_for_huggingface_space(space_id)\n",
59
- " return request.base_url\n",
60
- "\n",
61
- "def require_password(view_func):\n",
62
- " @wraps(view_func)\n",
63
- " def wrapper(*args, **kwargs):\n",
64
- " auth_header = request.headers.get(\"Authorization\")\n",
65
- " if auth_header and auth_header.startswith(\"Bearer \"):\n",
66
- " token = auth_header.split(\" \")[1]\n",
67
- " if token == PROXY_PASSWORD:\n",
68
- " return view_func(*args, **kwargs)\n",
69
- " api_key = request.headers.get(\"x-api-key\")\n",
70
- " if api_key and api_key == PROXY_PASSWORD:\n",
71
- " return view_func(*args, **kwargs)\n",
72
- " return jsonify({\"error\": \"Unauthorized\"}), 401\n",
73
- " return wrapper\n",
74
- "\n",
75
- "def chat_request(messages, temp, system, model=None):\n",
76
- " if not system:\n",
77
- " system = [{\"type\": \"text\", \"text\": \"You are a helpful assistant that follows all user instructions.\"}]\n",
78
- " \n",
79
- " # anthropic/claude-3-5-sonnet:beta doesn't work\n",
80
- " if model == \"anthropic/claude-3-5-sonnet:beta\":\n",
81
- " model = \"claude-3-5-sonnet-20241022\"\n",
82
- " else:\n",
83
- " model = model or \"claude-3-5-sonnet-20241022\"\n",
84
- "\n",
85
- " payload = {\n",
86
- " \"model\": model,\n",
87
- " \"temperature\": temp,\n",
88
- " \"stream\": True,\n",
89
- " \"messages\": [\n",
90
- " {\"role\": \"system\", \"content\": system},\n",
91
- " _messages\n",
92
- " ]\n",
93
- " }\n",
94
- " resp = requests.post(\n",
95
- " API_ENDPOINT,\n",
96
- " headers={\n",
97
- " \"authorization\": f\"Bearer {key}\",\n",
98
- " \"content-type\": \"application/json\",\n",
99
- " \"User-Agent\": user_agent\n",
100
- " },\n",
101
- " json=payload, stream=True\n",
102
- " )\n",
103
- " return resp if resp.ok else None\n",
104
- "\n",
105
- "@app.route(\"/\", methods=[\"GET\"])\n",
106
- "def root():\n",
107
- " global completed_prompts, active_streams, total_duration\n",
108
- " average_duration = total_duration / completed_prompts if completed_prompts > 0 else 0\n",
109
- " base_url = get_base_url(request).rstrip('/')\n",
110
- " if base_url.startswith(\"http://\"):\n",
111
- " base_url = base_url.replace(\"http://\", \"https://\", 1)\n",
112
- " response_data = {\n",
113
- " \"Total Requests\": completed_prompts,\n",
114
- " \"Active Requests\": active_streams,\n",
115
- " \"Average Duration\": average_duration,\n",
116
- " \"Proxy Endpoint\": base_url\n",
117
- " }\n",
118
- " pretty_json = json.dumps(response_data, indent=4, sort_keys=False)\n",
119
- " html_content = f\"\"\"\n",
120
- "<!DOCTYPE html>\n",
121
- "<html lang=\"en\">\n",
122
- "<head>\n",
123
- " <meta charset=\"UTF-8\">\n",
124
- " <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n",
125
- " <title>Proxy Status</title>\n",
126
- " <style>\n",
127
- " body {{\n",
128
- " font-family: Arial, sans-serif;\n",
129
- " margin: 20px;\n",
130
- " background-color: #f4f4f9;\n",
131
- " color: #333;\n",
132
- " display: flex;\n",
133
- " flex-direction: column;\n",
134
- " align-items: center;\n",
135
- " }}\n",
136
- " h1 {{\n",
137
- " color: #444;\n",
138
- " }}\n",
139
- " pre {{\n",
140
- " background-color: #fff;\n",
141
- " padding: 15px;\n",
142
- " border-radius: 5px;\n",
143
- " border: 1px solid #ddd;\n",
144
- " max-width: 600px;\n",
145
- " overflow-x: auto;\n",
146
- " width: 100%;\n",
147
- " box-sizing: border-box;\n",
148
- " }}\n",
149
- " </style>\n",
150
- "</head>\n",
151
- "<body>\n",
152
- " <pre>{pretty_json}</pre>\n",
153
- "</body>\n",
154
- "</html>\n",
155
- "\"\"\"\n",
156
- " return Response(html_content, content_type='text/html')\n",
157
- "\n",
158
- "@app.route(\"/chat/completions\", methods=[\"POST\"])\n",
159
- "@app.route(\"/v1/chat/completions\", methods=[\"POST\"])\n",
160
- "@require_password\n",
161
- "def handle_openai_chat():\n",
162
- " global completed_prompts, active_streams, total_duration\n",
163
- " data = request.json\n",
164
- " streaming = data.get(\"stream\", True)\n",
165
- " start_time = current_time()\n",
166
- " \n",
167
- " result = chat_request(\n",
168
- " messages=data.get(\"messages\"),\n",
169
- " temp=data.get(\"temperature\"),\n",
170
- " system=data.get(\"system\"),\n",
171
- " model=data.get(\"model\")\n",
172
- " )\n",
173
- " \n",
174
- " if not result:\n",
175
- " return {\"error\": \"Request failed\"}\n",
176
- " \n",
177
- " if streaming:\n",
178
- " active_streams += 1\n",
179
- " def generate():\n",
180
- " nonlocal start_time\n",
181
- " global active_streams, completed_prompts, total_duration\n",
182
- " try:\n",
183
- " for l in result.iter_lines():\n",
184
- " if not l:\n",
185
- " continue\n",
186
- " try:\n",
187
- " d = json.loads(l.decode('utf-8').replace('data: ', ''))\n",
188
- " if 'choices' in d and len(d['choices']) > 0:\n",
189
- " chunk = d['choices'][0].get('delta', {}).get('content', '')\n",
190
- " if chunk:\n",
191
- " yield f\"data: {json.dumps({'choices': [{'delta': {'content': chunk}}]})}\\n\\n\"\n",
192
- " if d.get('choices', [{}])[0].get('finish_reason') is not None:\n",
193
- " yield f\"data: {json.dumps({'choices': [{'finish_reason': 'stop'}]})}\\n\\n\"\n",
194
- " break\n",
195
- " except json.JSONDecodeError as e:\n",
196
- " print(f\"JSON decode error: {e}\")\n",
197
- " continue\n",
198
- " except GeneratorExit:\n",
199
- " print(\"Generator closed prematurely\")\n",
200
- " except Exception as e:\n",
201
- " print(f\"Error in generator: {e}\")\n",
202
- " finally:\n",
203
- " active_streams -= 1\n",
204
- " duration = current_time() - start_time\n",
205
- " total_duration += duration\n",
206
- " completed_prompts += 1\n",
207
- " print(\"Generator cleanup complete\")\n",
208
- " \n",
209
- " return Response(stream_with_context(generate()), content_type='text/event-stream', headers={'Cache-Control': 'no-cache', 'Connection': 'keep-alive'})\n",
210
- " else:\n",
211
- " txt = \"\"\n",
212
- " for l in result.iter_lines():\n",
213
- " if not l:\n",
214
- " continue\n",
215
- " try:\n",
216
- " d = json.loads(l.decode('utf-8').replace('data: ', ''))\n",
217
- " if 'choices' in d and len(d['choices']) > 0:\n",
218
- " chunk = d['choices'][0].get('delta', {}).get('content', '')\n",
219
- " if chunk:\n",
220
- " txt += chunk\n",
221
- " if d.get('choices', [{}])[0].get('finish_reason') is not None:\n",
222
- " break\n",
223
- " except:\n",
224
- " continue\n",
225
- " duration = current_time() - start_time\n",
226
- " total_duration += duration\n",
227
- " completed_prompts += 1\n",
228
- " return {\"type\": \"message\", \"content\": [{\"type\": \"text\", \"text\": txt}]}\n",
229
- "\n",
230
- "@app.route(\"/messages\", methods=[\"POST\"])\n",
231
- "@app.route(\"/v1/messages\", methods=[\"POST\"])\n",
232
- "@require_password\n",
233
- "def handle_anthropic_chat():\n",
234
- " global completed_prompts, active_streams, total_duration\n",
235
- " data = request.json\n",
236
- " streaming = data.get(\"stream\", True)\n",
237
- " start_time = current_time()\n",
238
- " \n",
239
- " result = chat_request(\n",
240
- " messages=data.get(\"messages\"),\n",
241
- " temp=data.get(\"temperature\"),\n",
242
- " system=data.get(\"system\"),\n",
243
- " model=data.get(\"model\")\n",
244
- " )\n",
245
- " \n",
246
- " if not result:\n",
247
- " return {\"error\": \"Request failed\"}\n",
248
- " \n",
249
- " if streaming:\n",
250
- " active_streams += 1\n",
251
- " def generate():\n",
252
- " nonlocal start_time\n",
253
- " global active_streams, completed_prompts, total_duration\n",
254
- " try:\n",
255
- " yield f\"event: message_start\\ndata: {json.dumps({'type': 'message_start', 'message': {{'id': str(uuid.uuid4()), 'type': 'message', 'role': 'assistant', 'content': [], 'model': data.get('model'), 'stop_reason': None, 'stop_sequence': None, 'usage': {{'input_tokens': 0, 'output_tokens': 0}}}}})}\\n\\n\"\n",
256
- " \n",
257
- " for l in result.iter_lines():\n",
258
- " if not l:\n",
259
- " continue\n",
260
- " try:\n",
261
- " d = json.loads(l.decode('utf-8').replace('data: ', ''))\n",
262
- " if 'choices' in d and len(d['choices']) > 0:\n",
263
- " chunk = d['choices'][0].get('delta', {}).get('content', '')\n",
264
- " if chunk:\n",
265
- " yield f\"event: content_block_delta\\ndata: {json.dumps({'type': 'content_block_delta', 'index': 0, 'delta': {{'type': 'text_delta', 'text': chunk}}})}\\n\\n\"\n",
266
- " if d.get('choices', [{}])[0].get('finish_reason') is not None:\n",
267
- " yield f\"event: content_block_stop\\ndata: {json.dumps({'type': 'content_block_stop', 'index': 0})}\\n\\n\"\n",
268
- " yield f\"event: message_delta\\ndata: {json.dumps({'type': 'message_delta', 'delta': {{'stop_reason': 'end_turn', 'stop_sequence': None}}, 'usage': {{'output_tokens': 0}}})}\\n\\n\"\n",
269
- " yield f\"event: message_stop\\ndata: {json.dumps({'type': 'message_stop'})}\\n\\n\"\n",
270
- " break\n",
271
- " except json.JSONDecodeError as e:\n",
272
- " print(f\"JSON decode error: {e}\")\n",
273
- " continue\n",
274
- " except GeneratorExit:\n",
275
- " print(\"Generator closed prematurely\")\n",
276
- " except Exception as e:\n",
277
- " print(f\"Error in generator: {e}\")\n",
278
- " finally:\n",
279
- " active_streams -= 1\n",
280
- " duration = current_time() - start_time\n",
281
- " total_duration += duration\n",
282
- " completed_prompts += 1\n",
283
- " print(\"Generator cleanup complete\")\n",
284
- " \n",
285
- " return Response(stream_with_context(generate()), content_type='text/event-stream', headers={'Cache-Control': 'no-cache', 'Connection': 'keep-alive'})\n",
286
- " else:\n",
287
- " txt = \"\"\n",
288
- " for l in result.iter_lines():\n",
289
- " if not l:\n",
290
- " continue\n",
291
- " try:\n",
292
- " d = json.loads(l.decode('utf-8').replace('data: ', ''))\n",
293
- " if 'choices' in d and len(d['choices']) > 0:\n",
294
- " chunk = d['choices'][0].get('delta', {}).get('content', '')\n",
295
- " if chunk:\n",
296
- " txt += chunk\n",
297
- " if d.get('choices', [{}])[0].get('finish_reason') is not None:\n",
298
- " break\n",
299
- " except:\n",
300
- " continue\n",
301
- " duration = current_time() - start_time\n",
302
- " total_duration += duration\n",
303
- " completed_prompts += 1\n",
304
- " return {\n",
305
- " \"content\": [{\"text\": txt, \"type\": \"text\"}],\n",
306
- " \"id\": str(uuid.uuid4()),\n",
307
- " \"model\": data.get(\"model\"),\n",
308
- " \"role\": \"assistant\",\n",
309
- " \"stop_reason\": \"end_turn\",\n",
310
- " \"stop_sequence\": None,\n",
311
- " \"type\": \"message\",\n",
312
- " \"usage\": {\n",
313
- " \"input_tokens\": 0,\n",
314
- " \"output_tokens\": len(txt.split())\n",
315
- " }\n",
316
- " }\n",
317
- "\n",
318
- "@app.route(\"/models\", methods=[\"GET\"])\n",
319
- "def list_models():\n",
320
- " try:\n",
321
- " response = requests.get(\"https://openrouter.ai/api/v1/models\", headers={\"User-Agent\": user_agent})\n",
322
- " if response.ok:\n",
323
- " return response.json()\n",
324
- " else:\n",
325
- " return {\"error\": \"Failed to fetch models\"}, response.status_code\n",
326
- " except requests.RequestException as e:\n",
327
- " return {\"error\": str(e)}, 500\n",
328
- "\n",
329
- "if __name__ == \"__main__\":\n",
330
- " app.run(port=7860)"
331
- ]
332
- }
333
- ],
334
- "metadata": {
335
- "kernelspec": {
336
- "display_name": "Python 3",
337
- "language": "python",
338
- "name": "python3"
339
- },
340
- "language_info": {
341
- "codemirror_mode": {
342
- "name": "ipython",
343
- "version": 3
344
- },
345
- "file_extension": ".py",
346
- "mimetype": "text/x-python",
347
- "name": "python",
348
- "nbconvert_exporter": "python",
349
- "pygments_lexer": "ipython3",
350
- "version": "3.13.1"
351
- }
352
- },
353
- "nbformat": 4,
354
- "nbformat_minor": 2
355
- }