Spaces:
Runtime error
Runtime error
File size: 31,440 Bytes
8892199 7515e7a 8892199 7515e7a 8892199 7515e7a 8892199 7515e7a 8892199 7515e7a 8892199 7515e7a 8892199 7515e7a 8892199 7515e7a 8892199 7515e7a 8892199 7515e7a 8892199 7515e7a 8892199 7515e7a 8892199 7515e7a 8892199 7515e7a 8892199 7515e7a 8892199 7515e7a 8892199 7515e7a 8892199 7515e7a 8892199 7515e7a 8892199 7515e7a 8892199 7515e7a 8892199 7515e7a 8892199 7515e7a 8892199 |
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 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 |
{
"cells": [
{
"cell_type": "code",
"execution_count": 8,
"id": "4fca2e60",
"metadata": {},
"outputs": [],
"source": [
"!pip -q install gradio fastapi 'fastapi-users-db-sqlalchemy<5.0.0' openai uvicorn httpx requests pydantic sqlalchemy python-dotenv asyncpg pipreqs"
]
},
{
"cell_type": "code",
"execution_count": 9,
"id": "a4ffa93a",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Overwriting app/db.py\n"
]
}
],
"source": [
"%%writefile app/db.py\n",
"from typing import AsyncGenerator\n",
"\n",
"from fastapi import Depends\n",
"from fastapi_users.db import SQLAlchemyBaseUserTableUUID, SQLAlchemyUserDatabase\n",
"from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine\n",
"from sqlalchemy.ext.declarative import DeclarativeMeta, declarative_base\n",
"from sqlalchemy.orm import sessionmaker\n",
"from dotenv import load_dotenv\n",
"import os\n",
"\n",
"# Get the current environment from the environment variable\n",
"current_environment = os.getenv(\"APP_ENV\", \"dev\")\n",
"\n",
"# Load the appropriate .env file based on the current environment\n",
"if current_environment == \"dev\":\n",
" load_dotenv(\".env.dev\")\n",
"elif current_environment == \"test\":\n",
" load_dotenv(\".env.test\")\n",
"elif current_environment == \"prod\":\n",
" load_dotenv(\".env.prod\")\n",
"else:\n",
" raise ValueError(\"Invalid environment specified\")\n",
"\n",
"db_connection_string = os.getenv(\"DB_CONNECTION_STRING\")\n",
"\n",
"DATABASE_URL = db_connection_string\n",
"Base: DeclarativeMeta = declarative_base()\n",
"\n",
" \n",
"class User(SQLAlchemyBaseUserTableUUID, Base):\n",
" pass\n",
"\n",
"\n",
"engine = create_async_engine(DATABASE_URL)\n",
"async_session_maker = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)\n",
"\n",
"\n",
"async def create_db_and_tables():\n",
" async with engine.begin() as conn:\n",
" await conn.run_sync(Base.metadata.create_all)\n",
"\n",
"\n",
"async def get_async_session() -> AsyncGenerator[AsyncSession, None]:\n",
" async with async_session_maker() as session:\n",
" yield session\n",
"\n",
"\n",
"async def get_user_db(session: AsyncSession = Depends(get_async_session)):\n",
" yield SQLAlchemyUserDatabase(session, User)\n"
]
},
{
"cell_type": "code",
"execution_count": 10,
"id": "d2a08335",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Overwriting app/schemas.py\n"
]
}
],
"source": [
"%%writefile app/schemas.py\n",
"import uuid\n",
"\n",
"from fastapi_users import schemas\n",
"\n",
"\n",
"class UserRead(schemas.BaseUser[uuid.UUID]):\n",
" pass\n",
"\n",
"\n",
"class UserCreate(schemas.BaseUserCreate):\n",
" pass\n",
"\n",
"\n",
"class UserUpdate(schemas.BaseUserUpdate):\n",
" pass\n"
]
},
{
"cell_type": "code",
"execution_count": 11,
"id": "9d649fcc",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Overwriting app/users.py\n"
]
}
],
"source": [
"%%writefile app/users.py\n",
"import uuid\n",
"import os\n",
"from typing import Optional\n",
"from fastapi import Depends, Request\n",
"from fastapi_users import BaseUserManager, FastAPIUsers, UUIDIDMixin\n",
"from fastapi_users.authentication import (\n",
" AuthenticationBackend,\n",
" BearerTransport,\n",
" JWTStrategy,\n",
")\n",
"from fastapi_users.db import SQLAlchemyUserDatabase\n",
"from app.db import User, get_user_db\n",
"from dotenv import load_dotenv\n",
"\n",
"# Get the current environment from the environment variable\n",
"current_environment = os.getenv(\"APP_ENV\", \"dev\")\n",
"\n",
"# Load the appropriate .env file based on the current environment\n",
"if current_environment == \"dev\":\n",
" load_dotenv(\".env.dev\")\n",
"elif current_environment == \"test\":\n",
" load_dotenv(\".env.test\")\n",
"elif current_environment == \"prod\":\n",
" load_dotenv(\".env.prod\")\n",
"else:\n",
" raise ValueError(\"Invalid environment specified\")\n",
"\n",
"SECRET = os.getenv(\"APP_SECRET\")\n",
"\n",
"\n",
"class UserManager(UUIDIDMixin, BaseUserManager[User, uuid.UUID]):\n",
" reset_password_token_secret = SECRET\n",
" verification_token_secret = SECRET\n",
"\n",
" async def on_after_register(self, user: User, request: Optional[Request] = None):\n",
" print(f\"User {user.id} has registered.\")\n",
"\n",
" async def on_after_forgot_password(\n",
" self, user: User, token: str, request: Optional[Request] = None\n",
" ):\n",
" print(f\"User {user.id} has forgot their password. Reset token: {token}\")\n",
"\n",
" async def on_after_request_verify(\n",
" self, user: User, token: str, request: Optional[Request] = None\n",
" ):\n",
" print(f\"Verification requested for user {user.id}. Verification token: {token}\")\n",
"\n",
"\n",
"async def get_user_manager(user_db: SQLAlchemyUserDatabase = Depends(get_user_db)):\n",
" yield UserManager(user_db)\n",
"\n",
"\n",
"bearer_transport = BearerTransport(tokenUrl=\"auth/jwt/login\")\n",
"\n",
"\n",
"def get_jwt_strategy() -> JWTStrategy:\n",
" return JWTStrategy(secret=SECRET, lifetime_seconds=3600)\n",
"\n",
"\n",
"auth_backend = AuthenticationBackend(\n",
" name=\"jwt\",\n",
" transport=bearer_transport,\n",
" get_strategy=get_jwt_strategy,\n",
")\n",
"\n",
"fastapi_users = FastAPIUsers[User, uuid.UUID](get_user_manager, [auth_backend])\n",
"\n",
"current_active_user = fastapi_users.current_user(active=True)\n"
]
},
{
"cell_type": "code",
"execution_count": 38,
"id": "d2250413",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Overwriting app/app.py\n"
]
}
],
"source": [
"%%writefile app/app.py\n",
"import httpx\n",
"import os\n",
"import requests\n",
"import gradio as gr\n",
"import openai\n",
"\n",
"from fastapi import Depends, FastAPI, Request\n",
"from app.db import User, create_db_and_tables\n",
"from app.schemas import UserCreate, UserRead, UserUpdate\n",
"from app.users import auth_backend, current_active_user, fastapi_users\n",
"from dotenv import load_dotenv\n",
"import examples as chatbot_examples\n",
"\n",
"# Get the current environment from the environment variable\n",
"current_environment = os.getenv(\"APP_ENV\", \"dev\")\n",
"\n",
"# Load the appropriate .env file based on the current environment\n",
"if current_environment == \"dev\":\n",
" load_dotenv(\".env.dev\")\n",
"elif current_environment == \"test\":\n",
" load_dotenv(\".env.test\")\n",
"elif current_environment == \"prod\":\n",
" load_dotenv(\".env.prod\")\n",
"else:\n",
" raise ValueError(\"Invalid environment specified\")\n",
" \n",
" \n",
"def api_login(email, password):\n",
" port = os.getenv(\"APP_PORT\")\n",
" scheme = os.getenv(\"APP_SCHEME\")\n",
" host = os.getenv(\"APP_HOST\")\n",
"\n",
" url = f\"{scheme}://{host}:{port}/auth/jwt/login\"\n",
" payload = {\n",
" 'username': email,\n",
" 'password': password\n",
" }\n",
" headers = {\n",
" 'Content-Type': 'application/x-www-form-urlencoded'\n",
" }\n",
"\n",
" response = requests.post(\n",
" url,\n",
" data=payload,\n",
" headers=headers\n",
" )\n",
" \n",
" if(response.status_code==200):\n",
" response_json = response.json()\n",
" api_key = response_json['access_token']\n",
" return True, api_key\n",
" else:\n",
" response_json = response.json()\n",
" detail = response_json['detail']\n",
" return False, detail\n",
" \n",
"\n",
"def get_api_key(email, password):\n",
" successful, message = api_login(email, password)\n",
" \n",
" if(successful):\n",
" return os.getenv(\"APP_API_BASE\"), message\n",
" else:\n",
" raise gr.Error(message)\n",
" return \"\", \"\"\n",
" \n",
"# Define a function to get the AI's reply using the OpenAI API\n",
"def get_ai_reply(message, model=\"gpt-3.5-turbo\", system_message=None, temperature=0, message_history=[]):\n",
" # Initialize the messages list\n",
" messages = []\n",
" \n",
" # Add the system message to the messages list\n",
" if system_message is not None:\n",
" messages += [{\"role\": \"system\", \"content\": system_message}]\n",
"\n",
" # Add the message history to the messages list\n",
" if message_history is not None:\n",
" messages += message_history\n",
" \n",
" # Add the user's message to the messages list\n",
" messages += [{\"role\": \"user\", \"content\": message}]\n",
" \n",
" # Make an API call to the OpenAI ChatCompletion endpoint with the model and messages\n",
" completion = openai.ChatCompletion.create(\n",
" model=model,\n",
" messages=messages,\n",
" temperature=temperature\n",
" )\n",
" \n",
" # Extract and return the AI's response from the API response\n",
" return completion.choices[0].message.content.strip()\n",
"\n",
"def get_ai_image(prompt, size=\"512x512\"):\n",
" response = openai.Image.create(\n",
" prompt=prompt,\n",
" n=1,\n",
" size=size\n",
" )\n",
" image_1_url = response.data[0]['url']\n",
" return image_1_url\n",
"\n",
"def get_ai_transcript(path_to_audio, language=None):\n",
" audio_file= open(path_to_audio, \"rb\")\n",
" transcript = openai.Audio.transcribe(\"whisper-1\", audio_file, language=language)\n",
" return transcript.text\n",
"\n",
"def generate_transcription(path_to_audio_file):\n",
" try:\n",
" transcript = get_ai_transcript(path_to_audio_file)\n",
" return transcript\n",
" except Exception as e:\n",
" raise gr.Error(e)\n",
" return \"\"\n",
" \n",
"def generate_image(prompt):\n",
" try:\n",
" image_url = get_ai_image(prompt)\n",
" return image_url\n",
" except Exception as e:\n",
" raise gr.Error(e)\n",
" return None\n",
" \n",
"# Define a function to handle the chat interaction with the AI model\n",
"def chat(model, system_message, message, chatbot_messages, history_state):\n",
" # Initialize chatbot_messages and history_state if they are not provided\n",
" chatbot_messages = chatbot_messages or []\n",
" history_state = history_state or []\n",
" \n",
" # Try to get the AI's reply using the get_ai_reply function\n",
" try:\n",
" ai_reply = get_ai_reply(message, model=model, system_message=system_message, message_history=history_state)\n",
" except Exception as e:\n",
" # If an error occurs, raise a Gradio error\n",
" raise gr.Error(e)\n",
" \n",
" # Append the user's message and the AI's reply to the chatbot_messages list\n",
" chatbot_messages.append((message, ai_reply))\n",
" \n",
" # Append the user's message and the AI's reply to the history_state list\n",
" history_state.append({\"role\": \"user\", \"content\": message})\n",
" history_state.append({\"role\": \"assistant\", \"content\": ai_reply})\n",
" \n",
" # Return None (empty out the user's message textbox), the updated chatbot_messages, and the updated history_state\n",
" return None, chatbot_messages, history_state\n",
"\n",
"# Define a function to launch the chatbot interface using Gradio\n",
"def get_chatbot_app(additional_examples=[]):\n",
" # Load chatbot examples and merge with any additional examples provided\n",
" examples = chatbot_examples.load_examples(additional=additional_examples)\n",
" \n",
" # Define a function to get the names of the examples\n",
" def get_examples():\n",
" return [example[\"name\"] for example in examples]\n",
"\n",
" # Define a function to choose an example based on the index\n",
" def choose_example(index):\n",
" if(index!=None):\n",
" system_message = examples[index][\"system_message\"].strip()\n",
" user_message = examples[index][\"message\"].strip()\n",
" return system_message, user_message, [], []\n",
" else:\n",
" return \"\", \"\", [], []\n",
"\n",
" # Create the Gradio interface using the Blocks layout\n",
" with gr.Blocks() as app:\n",
" with gr.Tab(\"Conversation\"):\n",
" with gr.Row():\n",
" with gr.Column():\n",
" # Create a dropdown to select examples\n",
" example_dropdown = gr.Dropdown(get_examples(), label=\"Examples\", type=\"index\")\n",
" # Create a button to load the selected example\n",
" example_load_btn = gr.Button(value=\"Load\")\n",
" # Create a textbox for the system message (prompt)\n",
" system_message = gr.TextArea(label=\"System Message (Prompt)\", value=\"You are a helpful assistant.\", lines=20, max_lines=400)\n",
" with gr.Column():\n",
" # Create a dropdown to select the AI model\n",
" model_selector = gr.Dropdown(\n",
" [\"gpt-3.5-turbo\"],\n",
" label=\"Model\",\n",
" value=\"gpt-3.5-turbo\"\n",
" )\n",
" # Create a chatbot interface for the conversation\n",
" chatbot = gr.Chatbot(label=\"Conversation\")\n",
" # Create a textbox for the user's message\n",
" message = gr.Textbox(label=\"Message\")\n",
" # Create a state object to store the conversation history\n",
" history_state = gr.State()\n",
" # Create a button to send the user's message\n",
" btn = gr.Button(value=\"Send\")\n",
"\n",
" # Connect the example load button to the choose_example function\n",
" example_load_btn.click(choose_example, inputs=[example_dropdown], outputs=[system_message, message, chatbot, history_state])\n",
" # Connect the send button to the chat function\n",
" btn.click(chat, inputs=[model_selector, system_message, message, chatbot, history_state], outputs=[message, chatbot, history_state])\n",
" with gr.Tab(\"Image Generation\"):\n",
" image_prompt = gr.Textbox(label=\"Prompt\", placeholder=\"A cute puppy wearing sunglasses.\")\n",
" image_btn = gr.Button(value=\"Generate\")\n",
" image = gr.Image(label=\"Result\", interactive=False, type=\"filepath\")\n",
" image_btn.click(generate_image, inputs=[image_prompt], outputs=[image])\n",
" with gr.Tab(\"Speech-to-text\"):\n",
" audio_file = gr.Audio(label=\"Audio\", source=\"microphone\", type=\"filepath\")\n",
" transcribe = gr.Button(value=\"Transcribe\")\n",
" audio_transcript = gr.Textbox(label=\"Transcription\", interactive=False)\n",
" transcribe.click(generate_transcription, inputs=[audio_file], outputs=[audio_transcript])\n",
" with gr.Tab(\"Get API Key\"):\n",
" email_box = gr.Textbox(label=\"Email Address\", placeholder=\"Student Email\")\n",
" password_box = gr.Textbox(label=\"Password\", type=\"password\", placeholder=\"Student ID\")\n",
" btn = gr.Button(value =\"Generate\")\n",
" api_host_box = gr.Textbox(label=\"OpenAI API Base\", interactive=False)\n",
" api_key_box = gr.Textbox(label=\"OpenAI API Key\", interactive=False)\n",
" btn.click(get_api_key, inputs = [email_box, password_box], outputs = [api_host_box, api_key_box])\n",
" # Return the app\n",
" return app\n",
"\n",
"app = FastAPI()\n",
"\n",
"app.include_router(\n",
" fastapi_users.get_auth_router(auth_backend), prefix=\"/auth/jwt\", tags=[\"auth\"]\n",
")\n",
"app.include_router(\n",
" fastapi_users.get_register_router(UserRead, UserCreate),\n",
" prefix=\"/auth\",\n",
" tags=[\"auth\"],\n",
")\n",
"app.include_router(\n",
" fastapi_users.get_users_router(UserRead, UserUpdate),\n",
" prefix=\"/users\",\n",
" tags=[\"users\"],\n",
")\n",
"\n",
"@app.get(\"/authenticated-route\")\n",
"async def authenticated_route(user: User = Depends(current_active_user)):\n",
" return {\"message\": f\"Hello {user.email}!\"}\n",
"\n",
"@app.post(\"/v1/chat/completions\")\n",
"async def openai_api_chat_completions_passthrough(\n",
" request: Request,\n",
" user: User = Depends(fastapi_users.current_user()),\n",
"):\n",
" if not user:\n",
" raise HTTPException(status_code=401, detail=\"Unauthorized\")\n",
"\n",
" # Get the request data and headers\n",
" request_data = await request.json()\n",
" request_headers = request.headers\n",
" openai_api_key = os.getenv(\"OPENAI_API_KEY\")\n",
" \n",
" if(request_data['model']=='gpt-4' or request_data['model'] == 'gpt-4-32k'):\n",
" print(\"User requested gpt-4, falling back to gpt-3.5-turbo\")\n",
" request_data['model'] = 'gpt-3.5-turbo'\n",
"\n",
" # Forward the request to the OpenAI API\n",
" response = requests.post(\n",
" \"https://api.openai.com/v1/chat/completions\",\n",
" json=request_data,\n",
" headers={\n",
" \"Content-Type\": request_headers.get(\"Content-Type\"),\n",
" \"Authorization\": f\"Bearer {openai_api_key}\",\n",
" },\n",
" )\n",
" print(response)\n",
"\n",
" # Return the OpenAI API response\n",
" return response.json()\n",
"\n",
"@app.on_event(\"startup\")\n",
"async def on_startup():\n",
" # Not needed if you setup a migration system like Alembic\n",
" await create_db_and_tables()\n",
" \n",
"gradio_gui = get_chatbot_app()\n",
"gradio_gui.auth = api_login\n",
"gradio_gui.auth_message = \"Welcome, to the 3341 OpenAI Service\"\n",
"app = gr.mount_gradio_app(app, gradio_gui, path=\"/\")"
]
},
{
"cell_type": "code",
"execution_count": 16,
"id": "f089dfd7",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Overwriting main.py\n"
]
}
],
"source": [
"%%writefile main.py\n",
"import subprocess\n",
"\n",
"subprocess.run(\"uvicorn app.app:app --host 0.0.0.0 --port 7860\", shell=True)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "9039be08",
"metadata": {},
"outputs": [],
"source": [
"%%writefile requirements.txt\n",
"fastapi==0.95.1\n",
"fastapi-users-db-sqlalchemy<5.0.0\n",
"gradio==3.27.0\n",
"httpx==0.24.0\n",
"openai==0.27.4\n",
"python-dotenv==1.0.0\n",
"Requests==2.28.2\n",
"SQLAlchemy==1.4.47\n",
"uvicorn==0.21.1\n",
"asyncpg==0.27.0"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "a20f7f8c",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\u001b[32mINFO\u001b[0m: Started server process [\u001b[36m77691\u001b[0m]\n",
"\u001b[32mINFO\u001b[0m: Waiting for application startup.\n",
"\u001b[32mINFO\u001b[0m: Application startup complete.\n",
"\u001b[32mINFO\u001b[0m: Uvicorn running on \u001b[1mhttp://0.0.0.0:7860\u001b[0m (Press CTRL+C to quit)\n",
"\u001b[32mINFO\u001b[0m: 127.0.0.1:58808 - \"\u001b[1mGET / HTTP/1.1\u001b[0m\" \u001b[32m200 OK\u001b[0m\n",
"\u001b[32mINFO\u001b[0m: 127.0.0.1:58808 - \"\u001b[1mGET /theme.css HTTP/1.1\u001b[0m\" \u001b[32m200 OK\u001b[0m\n",
"\u001b[32mINFO\u001b[0m: 127.0.0.1:58810 - \"\u001b[1mPOST /auth/jwt/login HTTP/1.1\u001b[0m\" \u001b[32m200 OK\u001b[0m\n",
"\u001b[32mINFO\u001b[0m: 127.0.0.1:58809 - \"\u001b[1mPOST /login HTTP/1.1\u001b[0m\" \u001b[32m200 OK\u001b[0m\n",
"\u001b[32mINFO\u001b[0m: 127.0.0.1:58809 - \"\u001b[1mGET / HTTP/1.1\u001b[0m\" \u001b[32m200 OK\u001b[0m\n",
"\u001b[32mINFO\u001b[0m: 127.0.0.1:58809 - \"\u001b[1mGET /theme.css HTTP/1.1\u001b[0m\" \u001b[32m200 OK\u001b[0m\n"
]
}
],
"source": [
"!python main.py"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "65658ef7",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"User 30d58c0b-04c8-4e55-89e5-878b08472884 has registered.\n",
"User created <app.db.User object at 0x1061dec80>\n",
"User 2a622947-16bd-4963-abc8-30a3766338c4 has registered.\n",
"User created <app.db.User object at 0x1061de440>\n",
"User 23e72a35-10e0-469d-8fc6-7b6f1f8fc5a3 has registered.\n",
"User created <app.db.User object at 0x1061de470>\n",
"User 85bcf4f4-db65-404d-b2ef-e23283462bfa has registered.\n",
"User created <app.db.User object at 0x1064ca410>\n",
"User 7df12d26-1f30-4b74-9d8c-975d68e0df9f has registered.\n",
"User created <app.db.User object at 0x1064c9c60>\n",
"User 1cd64c6e-bcde-4009-af24-6bee05e7afd8 has registered.\n",
"User created <app.db.User object at 0x1064ca410>\n",
"User 88b0449c-e604-4d57-bd0c-797a930efa05 has registered.\n",
"User created <app.db.User object at 0x1064cad10>\n",
"User 68242f26-a22b-49e8-8b8c-c4475e01dcd4 has registered.\n",
"User created <app.db.User object at 0x1064c9b70>\n",
"User 61b685a4-3df5-4baf-bb61-b4f93150699f has registered.\n",
"User created <app.db.User object at 0x1064cba00>\n",
"User 8443d506-859e-4f89-b301-6c08e56d34e1 has registered.\n",
"User created <app.db.User object at 0x1064cad10>\n",
"User 1adee351-777e-46ff-83be-379db22cc2d7 has registered.\n",
"User created <app.db.User object at 0x1064c9b70>\n",
"User 5654743e-fd1e-477d-97e0-f4eb138d2935 has registered.\n",
"User created <app.db.User object at 0x1064c97b0>\n",
"User 57c96dd2-6291-447d-9070-ca9c335798ba has registered.\n",
"User created <app.db.User object at 0x1064cbc70>\n",
"User 6a105d49-e84f-4d95-98ed-577b4a970854 has registered.\n",
"User created <app.db.User object at 0x1064cbb80>\n",
"User 6a17151f-60ad-42ae-8fef-2890a77ee0f8 has registered.\n",
"User created <app.db.User object at 0x1064c81c0>\n",
"User badec4ec-fee6-4832-bb89-1bf1501167ff has registered.\n",
"User created <app.db.User object at 0x1064cba90>\n",
"User 6c1a749e-fa19-44bd-b937-e508e78866cd has registered.\n",
"User created <app.db.User object at 0x1064c9cc0>\n",
"User 7c9aa8fe-d3e4-4af3-919a-20294d68fc4b has registered.\n",
"User created <app.db.User object at 0x1064c92d0>\n",
"User a93183b3-5aa1-4e06-a78f-a47be0b2bba1 has registered.\n",
"User created <app.db.User object at 0x1064cab00>\n",
"User 3abc7ae3-0185-4742-bf1d-f3749cecb199 has registered.\n",
"User created <app.db.User object at 0x1064cb850>\n",
"User e6e9eda6-80e2-40bd-be8c-4d371deddb4e has registered.\n",
"User created <app.db.User object at 0x1064c9780>\n",
"User a3587907-b38f-4291-8153-34d480d8ebfe has registered.\n",
"User created <app.db.User object at 0x1064cab00>\n",
"User 4de62323-12ba-41cc-bd72-60a53117236e has registered.\n",
"User created <app.db.User object at 0x1064c9510>\n",
"User fa7ae58a-e5d4-4495-9aec-d10f1076b291 has registered.\n",
"User created <app.db.User object at 0x1064c9240>\n",
"User a3d49925-470c-485b-85c7-b881fc6103bd has registered.\n",
"User created <app.db.User object at 0x1064cad10>\n",
"User 1aded816-081c-4c16-b6fb-5a8514acecbd has registered.\n",
"User created <app.db.User object at 0x1064c9930>\n",
"User c05807bb-5e02-4e9d-a5dd-870b40beeab9 has registered.\n",
"User created <app.db.User object at 0x1061de830>\n",
"User e3840eef-2ccc-43e8-bb98-f67e1d78d595 has registered.\n",
"User created <app.db.User object at 0x1064ca860>\n",
"User 177862c8-f84a-4e9a-8a11-325c1af34476 has registered.\n",
"User created <app.db.User object at 0x106222cb0>\n",
"User 833a7089-f258-4261-86a9-6aa874ccc7b2 has registered.\n",
"User created <app.db.User object at 0x106223040>\n",
"User c9f0147c-b880-4814-a272-3c91625ebfe2 has registered.\n",
"User created <app.db.User object at 0x106222cb0>\n",
"User 182b4c76-2cba-407c-965c-eea8ec17ef6f has registered.\n",
"User created <app.db.User object at 0x106223880>\n",
"User c79f3346-cf21-4e41-8393-c36aaeab67fe has registered.\n",
"User created <app.db.User object at 0x106223e50>\n",
"User 610705ed-b7ac-4296-b566-db6bdf642f5a has registered.\n",
"User created <app.db.User object at 0x106223ca0>\n",
"User 09817885-888b-4be9-9d20-fd03366f6791 has registered.\n",
"User created <app.db.User object at 0x106223880>\n",
"User 5c38dc47-7c00-4d68-ac7c-9ec2c7c4a6ea has registered.\n",
"User created <app.db.User object at 0x1064c88b0>\n",
"User 1009694f-b1e4-4751-a59c-a8ed757f76f1 has registered.\n",
"User created <app.db.User object at 0x1064c9ae0>\n",
"User b5fb3dbc-a8c0-4221-897f-9eb87ff29ced has registered.\n",
"User created <app.db.User object at 0x1064cba30>\n",
"User 3269239e-e87b-4f6f-9539-4d7fffc1d9a1 has registered.\n",
"User created <app.db.User object at 0x1064c9f00>\n",
"User 59bb7f37-d029-47a1-8bbd-37adae350fed has registered.\n",
"User created <app.db.User object at 0x1064c9ae0>\n"
]
}
],
"source": [
"import contextlib\n",
"\n",
"from app.db import get_async_session, get_user_db\n",
"from app.schemas import UserCreate\n",
"from app.users import get_user_manager\n",
"from fastapi_users.exceptions import UserAlreadyExists\n",
"import csv\n",
"\n",
"get_async_session_context = contextlib.asynccontextmanager(get_async_session)\n",
"get_user_db_context = contextlib.asynccontextmanager(get_user_db)\n",
"get_user_manager_context = contextlib.asynccontextmanager(get_user_manager)\n",
"\n",
"\n",
"async def create_user(email: str, password: str, is_superuser: bool = False):\n",
" try:\n",
" async with get_async_session_context() as session:\n",
" async with get_user_db_context(session) as user_db:\n",
" async with get_user_manager_context(user_db) as user_manager:\n",
" user = await user_manager.create(\n",
" UserCreate(\n",
" email=email, password=password, is_superuser=is_superuser\n",
" )\n",
" )\n",
" print(f\"User created {user}\")\n",
" except UserAlreadyExists:\n",
" print(f\"User {email} already exists\")\n",
" \n",
"with open(\"seeds.csv\", mode=\"r\") as csv_file:\n",
" csv_reader = csv.reader(csv_file)\n",
"\n",
" for row in csv_reader:\n",
" email = row[0]\n",
" password = row[1]\n",
"\n",
" await create_user(email=email, password=password)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "406b1bd5",
"metadata": {},
"outputs": [],
"source": [
"!git add app"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "4849ce67",
"metadata": {},
"outputs": [],
"source": [
"!git add requirements.txt"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "54c436ed",
"metadata": {},
"outputs": [],
"source": [
"!git add main.py"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "9553c6e6",
"metadata": {},
"outputs": [],
"source": [
"!git commit -m \"adding chatbot\""
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "bda07f88",
"metadata": {},
"outputs": [],
"source": [
"!pip -q install --upgrade huggingface_hub"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "39516b2a",
"metadata": {},
"outputs": [],
"source": [
"from huggingface_hub import notebook_login\n",
"notebook_login()"
]
},
{
"cell_type": "code",
"execution_count": 42,
"id": "83bdbe1d",
"metadata": {},
"outputs": [],
"source": [
"!git remote add huggingface https://huggingface.co/spaces/ericmichael/openai-playground-utrgv"
]
},
{
"cell_type": "code",
"execution_count": 43,
"id": "db9d1e70",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Enumerating objects: 19, done.\n",
"Counting objects: 100% (19/19), done.\n",
"Delta compression using up to 8 threads\n",
"Compressing objects: 100% (18/18), done.\n",
"Writing objects: 100% (19/19), 13.39 KiB | 6.70 MiB/s, done.\n",
"Total 19 (delta 3), reused 0 (delta 0), pack-reused 0\n",
"error: RPC failed; curl 92 HTTP/2 stream 0 was not closed cleanly: INTERNAL_ERROR (err 2)\n",
"Everything up-to-date\n"
]
}
],
"source": [
"!git push --force huggingface main"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.8"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
|