Coder Social home page Coder Social logo

devasy23 / streamlit-chatgpt-limits Goto Github PK

View Code? Open in Web Editor NEW
0.0 2.0 0.0 9.01 MB

Designing a Streamlit app for managing ChatGPT-4 query limits with the features you've described is a great way to ensure efficient usage among your group. This setup provides a basic but functional application structure and codebase to get started with your pr

License: MIT License

Python 100.00%

streamlit-chatgpt-limits's Introduction

ChatGPT-4 Query Manager

Overview

ChatGPT-4 Query Manager is a Streamlit-based application designed to help users manage their queries and appointments. It features a simple and intuitive interface, allowing users to log in, sign up, and book slots for their queries.

Features

  • User authentication (Login/Sign up)
  • Google OAuth 2.0 integration for easy sign-in
  • Calendar interface for booking query slots
  • MongoDB integration for data storage

Getting Started

Prerequisites

  • Python 3.7 or higher
  • MongoDB account

Installation

  1. Clone the repository:

    git clone https://github.com/yourusername/chatgpt-4-query-manager.git
  2. Install the required dependencies:

    pip install -r requirements.txt
  3. Set up your MongoDB connection in app.py or through environment variables.

  4. Run the application:

    streamlit run app.py

Usage

  1. Open the application in your web browser.
  2. Sign up or log in to access the booking calendar.
  3. Select a slot and book your query session.

Contributing

Please see CONTRIBUTING.md for details on how to contribute to this project.

License

This project is licensed under the MIT License.

Acknowledgments

  • Streamlit for the amazing framework
  • Authlib for simplifying OAuth integration
  • MongoDB for the flexible database solution

For more information, check out the project wiki.

Demo Screenshot

Tutoria Video

streamlit-chatgpt-limits's People

Contributors

devasy23 avatar

Watchers

Kostas Georgiou avatar  avatar

streamlit-chatgpt-limits's Issues

Feature Enhancement

To enhance the modularity of your Streamlit app and to accommodate additional operations like editing and deleting bookings, as well as enforcing booking slot constraints (e.g., bookings must be in multiples of 3 hours), you can further refine your codebase. Here's how you might approach these enhancements:

Modular Design Considerations

  1. Split Functionality into More Specific Modules: Break down db.py into more specific modules, such as user_management.py for handling user-related database operations and booking_management.py for booking-related operations. This separation makes the codebase easier to navigate and scale.

  2. Service Layer: Introduce a service layer that sits between the Streamlit frontend (app.py) and the database operations (e.g., user_management.py, booking_management.py). This layer can handle business logic, such as the validation of booking times.

  3. Utilize Classes: For both users and bookings, consider using classes to represent these entities. This approach can make handling data and related operations more intuitive.

Proposed Structure with Enhancements

Here's an outline of how the updated project structure might look:

streamlit-chatgpt-limits/
├── app.py
├── requirements.txt
├── db/
│   ├── __init__.py
│   ├── connection.py
│   ├── user_management.py
│   └── booking_management.py
├── services/
│   ├── __init__.py
│   ├── booking_service.py
│   └── user_service.py
└── utils/
    ├── __init__.py
    └── helpers.py
  • connection.py: Manages the MongoDB client connection.
  • user_management.py and booking_management.py: Contain functions for user and booking CRUD operations, respectively.
  • booking_service.py and user_service.py: Implement business logic, such as booking slot validation and user authentication.
  • helpers.py: Includes utility functions like formatting messages or data for the UI.

Implementing New Features

  1. Booking Slot Validation: In booking_service.py, implement a function to check if a booking request meets the 3-hour multiple requirement.

    def is_valid_booking(start, end):
        duration = end - start
        return duration.total_seconds() % (3 * 3600) == 0
  2. Edit and Delete Bookings: In booking_management.py, add functions to update and remove bookings. These operations can then be called from the service layer or directly from app.py, depending on your design.

    def update_booking(booking_id, new_start, new_end):
        # Implement booking update logic
    
    def delete_booking(booking_id):
        # Implement booking deletion logic
  3. UI for Additional Operations: Extend app.py to include UI elements and logic for editing and deleting bookings, as well as displaying warnings when booking attempts violate the 3-hour rule.

Additional Suggestions

  • Use Environment Variables: For MongoDB connection strings and other sensitive information, use environment variables to enhance security.
  • Error Handling: Implement robust error handling throughout the application to manage database errors, input validation failures, etc.
  • Testing: Develop unit tests for the service layer to ensure business logic is correctly implemented, especially for critical functions like is_valid_booking.

By adopting these modular design principles and implementing the suggested features, your Streamlit app will be well-positioned for further development and maintenance.

Change directory structure and enhance modularity

To enhance the modularity of your Streamlit app and to accommodate additional operations like editing and deleting bookings, as well as enforcing booking slot constraints (e.g., bookings must be in multiples of 3 hours), you can further refine your codebase. Here's how you might approach these enhancements:

Modular Design Considerations

  1. Split Functionality into More Specific Modules: Break down db.py into more specific modules, such as user_management.py for handling user-related database operations and booking_management.py for booking-related operations. This separation makes the codebase easier to navigate and scale.

  2. Service Layer: Introduce a service layer that sits between the Streamlit frontend (app.py) and the database operations (e.g., user_management.py, booking_management.py). This layer can handle business logic, such as the validation of booking times.

  3. Utilize Classes: For both users and bookings, consider using classes to represent these entities. This approach can make handling data and related operations more intuitive.

Proposed Structure with Enhancements

Here's an outline of how the updated project structure might look:

streamlit-chatgpt-limits/
├── app.py
├── requirements.txt
├── db/
│   ├── __init__.py
│   ├── connection.py
│   ├── user_management.py
│   └── booking_management.py
├── services/
│   ├── __init__.py
│   ├── booking_service.py
│   └── user_service.py
└── utils/
    ├── __init__.py
    └── helpers.py
  • connection.py: Manages the MongoDB client connection.
  • user_management.py and booking_management.py: Contain functions for user and booking CRUD operations, respectively.
  • booking_service.py and user_service.py: Implement business logic, such as booking slot validation and user authentication.
  • helpers.py: Includes utility functions like formatting messages or data for the UI.

Implementing New Features

  1. Booking Slot Validation: In booking_service.py, implement a function to check if a booking request meets the 3-hour multiple requirement.

    def is_valid_booking(start, end):
        duration = end - start
        return duration.total_seconds() % (3 * 3600) == 0
  2. Edit and Delete Bookings: In booking_management.py, add functions to update and remove bookings. These operations can then be called from the service layer or directly from app.py, depending on your design.

    def update_booking(booking_id, new_start, new_end):
        # Implement booking update logic
    
    def delete_booking(booking_id):
        # Implement booking deletion logic
  3. UI for Additional Operations: Extend app.py to include UI elements and logic for editing and deleting bookings, as well as displaying warnings when booking attempts violate the 3-hour rule.

Additional Suggestions

  • Use Environment Variables: For MongoDB connection strings and other sensitive information, use environment variables to enhance security.
  • Error Handling: Implement robust error handling throughout the application to manage database errors, input validation failures, etc.
  • Testing: Develop unit tests for the service layer to ensure business logic is correctly implemented, especially for critical functions like is_valid_booking.

By adopting these modular design principles and implementing the suggested features, your Streamlit app will be well-positioned for further development and maintenance.

Feature Request: Add google authentication

To add the "Sign in with Google" feature to your Streamlit app, you can use the OAuth 2.0 protocol with the help of the authlib library. Here's a step-by-step guide:

Step 1: Set up a Google Cloud Project

  1. Go to the Google Cloud Console.
  2. Create a new project or select an existing one.
  3. Navigate to the "APIs & Services" > "Credentials" section.
  4. Click on "Create Credentials" and choose "OAuth client ID".
  5. Configure the consent screen as required.
  6. Set the application type to "Web application".
  7. Add authorized redirect URIs. For a local Streamlit app, you can use http://localhost:8501/oauth2callback.
  8. Note down the Client ID and Client Secret.

Step 2: Install Required Libraries

Install authlib if you haven't already:

pip install authlib

Step 3: Modify Your App

Add the following imports and global variables to your app.py:

from authlib.integrations.requests_client import OAuth2Session
import streamlit as st

# Google OAuth2 config
GOOGLE_CLIENT_ID = "your-client-id"
GOOGLE_CLIENT_SECRET = "your-client-secret"
GOOGLE_DISCOVERY_URL = (
    "https://accounts.google.com/.well-known/openid-configuration"
)

Replace "your-client-id" and "your-client-secret" with the credentials you obtained from the Google Cloud Console.

Step 4: Implement the OAuth Flow

Add the following functions to handle the OAuth flow:

def get_google_oauth_session(redirect_uri="http://localhost:8501/oauth2callback"):
    """Create an OAuth session for Google."""
    client = OAuth2Session(
        GOOGLE_CLIENT_ID,
        GOOGLE_CLIENT_SECRET,
        scope=["openid", "email", "profile"],
        redirect_uri=redirect_uri,
    )
    return client

def authenticate_user():
    """Authenticate the user with Google OAuth."""
    oauth = get_google_oauth_session()
    authorization_url, state = oauth.create_authorization_url(GOOGLE_DISCOVERY_URL)
    st.session_state["oauth_state"] = state
    return authorization_url

def get_user_info(code):
    """Get user information from the OAuth provider."""
    oauth = get_google_oauth_session()
    token = oauth.fetch_token(
        GOOGLE_DISCOVERY_URL,
        authorization_response=f"http://localhost:8501/oauth2callback?code={code}",
        state=st.session_state["oauth_state"],
    )
    user_info = oauth.get("https://openidconnect.googleapis.com/v1/userinfo").json()
    return user_info

Step 5: Update the Main App Logic

Modify the main() function to include the Google sign-in option:

def main():
    st.sidebar.title("ChatGPT-4 Query Manager")
    mode = st.sidebar.selectbox("Mode", ["Login", "Sign Up", "Sign in with Google"])

    if mode == "Sign in with Google":
        if "code" not in st.experimental_get_query_params():
            # Redirect to Google for authentication
            auth_url = authenticate_user()
            st.sidebar.markdown(f'[Sign in with Google]({auth_url})', unsafe_allow_html=True)
        else:
            # Handle the callback from Google
            code = st.experimental_get_query_params()["code"][0]
            user_info = get_user_info(code)
            st.session_state["authenticated"] = True
            st.session_state["user"] = user_info["email"]
            st.experimental_set_query_params()  # Clear the query params
            st.sidebar.success("Logged in successfully!")
            st.sidebar.write(f"Welcome, {user_info['email']}")

    # Handle other modes (Login and Sign Up) and display booking calendar
    # ...

Step 6: Run Your App

Start your Streamlit app and test the "Sign in with Google" feature.

streamlit run app.py

Make sure to replace http://localhost:8501 with your actual app's URL if you're deploying it online. Also, update the authorized redirect URIs in the Google Cloud Console accordingly.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.