Spaces:
Sleeping
Sleeping
| import sqlite3 | |
| # Step 1: Connect to the database (or create it if it doesn't exist) | |
| conn = sqlite3.connect('huggingface_app.db') | |
| cursor = conn.cursor() | |
| # Step 2: Create tables | |
| def create_tables(): | |
| cursor.execute(''' | |
| CREATE TABLE IF NOT EXISTS users ( | |
| id INTEGER PRIMARY KEY AUTOINCREMENT, | |
| username TEXT NOT NULL, | |
| email TEXT UNIQUE | |
| ) | |
| ''') | |
| cursor.execute(''' | |
| CREATE TABLE IF NOT EXISTS model_interactions ( | |
| id INTEGER PRIMARY KEY AUTOINCREMENT, | |
| user_id INTEGER, | |
| query TEXT NOT NULL, | |
| response TEXT NOT NULL, | |
| model_name TEXT NOT NULL, | |
| timestamp DATETIME DEFAULT CURRENT_TIMESTAMP, | |
| FOREIGN KEY (user_id) REFERENCES users(id) | |
| ) | |
| ''') | |
| print("Tables created successfully!") | |
| # Step 3: Insert Data | |
| def insert_user(username, email): | |
| cursor.execute(''' | |
| INSERT INTO users (username, email) | |
| VALUES (?, ?) | |
| ''', (username, email)) | |
| conn.commit() | |
| print(f"User {username} added.") | |
| def log_interaction(user_id, query, response, model_name): | |
| cursor.execute(''' | |
| INSERT INTO model_interactions (user_id, query, response, model_name) | |
| VALUES (?, ?, ?, ?) | |
| ''', (user_id, query, response, model_name)) | |
| conn.commit() | |
| print("Interaction logged.") | |
| # Step 4: Query Data | |
| def get_user_interactions(user_id): | |
| cursor.execute(''' | |
| SELECT * FROM model_interactions WHERE user_id = ? | |
| ''', (user_id,)) | |
| return cursor.fetchall() | |
| # Step 5: Close connection | |
| def close_connection(): | |
| conn.close() | |
| print("Database connection closed.") | |
| # Initialize the database | |
| if __name__ == "__main__": | |
| create_tables() | |
| # Example usage | |
| insert_user("test_user", "test@example.com") | |
| log_interaction(1, "What is AI?", "AI stands for Artificial Intelligence.", "gpt-4") | |
| # Fetch user interactions | |
| interactions = get_user_interactions(1) | |
| for interaction in interactions: | |
| print(interaction) | |
| close_connection() | |