Skip to content

Commit

Permalink
working extension, ai generation, storage, web app
Browse files Browse the repository at this point in the history
  • Loading branch information
hegstadjosh committed Oct 6, 2024
1 parent 3a345fa commit d627997
Show file tree
Hide file tree
Showing 6 changed files with 201 additions and 22 deletions.
11 changes: 6 additions & 5 deletions src/extension2/manifest.json
Original file line number Diff line number Diff line change
@@ -1,16 +1,17 @@
{
"manifest_version": 3,
"name": "AI Notetaking Extension with SQL Storage",
"version": "1.4",
"description": "Take notes, categorize them, and get AI-generated prompts. Now with SQL storage!",
"name": "AI Notetaking Extension with SQL Storage and Python AI",
"version": "1.5",
"description": "Take notes, categorize them, and get AI-generated prompts using Python backend.",
"action": {
"default_popup": "popup.html"
},
"permissions": [
"storage"
],
"host_permissions": [
"http://localhost:3000/*"
"http://localhost:3000/*",
"http://localhost:5000/*"
],
"content_security_policy": {
"extension_pages": "script-src 'self'; object-src 'self'"
Expand All @@ -19,4 +20,4 @@
"resources": ["journals.html"],
"matches": ["<all_urls>"]
}]
}
}
2 changes: 1 addition & 1 deletion src/extension2/popup.html
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ <h1>Notetaking</h1>
<!-- Buttons -->
<div class="buttons">
<button id="saveNote">Save Note</button>
<button id="getPrompt">Get AI Prompt</button>
<button id="getResponse">AI Response</button>
</div>

<!-- New Buttons -->
Expand Down
41 changes: 37 additions & 4 deletions src/extension2/popup.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
document.getElementById('saveNote').addEventListener('click', saveNote);
document.getElementById('getPrompt').addEventListener('click', getAIPrompt);
document.getElementById('getResponse').addEventListener('click', getAIResponse);
document.getElementById('viewJournals').addEventListener('click', viewJournals);

function saveNote() {
Expand Down Expand Up @@ -30,8 +30,41 @@ function saveNote() {
});
}

function getAIPrompt() {
// This function remains unchanged
// function getAIPrompt() {
// fetch('http://localhost:5000/get-prompt')
// .then(response => response.json())
// .then(data => {
// document.getElementById('noteArea').value = data.prompt;
// })
// .catch(error => {
// console.error('Error fetching AI prompt:', error);
// alert('Failed to get AI prompt.');
// });
// }

function getAIResponse() {
const noteContent = document.getElementById('noteArea').value;

if (!noteContent.trim()) {
alert('Please enter some content before requesting an AI response.');
return;
}

fetch('http://localhost:5000/get-response', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ note: noteContent }),
})
.then(response => response.json())
.then(data => {
document.getElementById('noteArea').value += '\n\nAI Response:\n' + data.response;
})
.catch(error => {
console.error('Error fetching AI response:', error);
alert('Failed to get AI response.');
});
}

function viewJournals() {
Expand All @@ -41,4 +74,4 @@ function viewJournals() {
width: 400,
height: 600,
});
}
}
56 changes: 44 additions & 12 deletions src/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,17 @@
from typing import Dict, List, Any
from dotenv import load_dotenv
from openai import OpenAI
from flask import Flask, jsonify, request
from flask_cors import CORS

app = Flask(__name__)
CORS(app)

# Load environment variables from .env file
load_dotenv()

# Initialize OpenAI client
client = OpenAI(api_key="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")
client = OpenAI(api_key="")

# Example knowledge base json structure
knowledge_base_example = {
Expand Down Expand Up @@ -56,6 +61,17 @@ def set_openai_api_key(api_key):
def create_agent_prompt(role, goal, backstory):
return f"You are a {role}. Your goal is to {goal}. Backstory: {backstory}"

def get_response(prompt):
response = client.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "system", "content": "generate info from users' notes:"},
{"role": "user", "content": prompt}
]
)

return response.choices[0].message.content

def execute_task(agent_prompt, task_description, context=""):
response = client.chat.completions.create(
model="gpt-4o",
Expand Down Expand Up @@ -194,19 +210,35 @@ def process_new_information(new_info, knowledge_base):
"new_content": new_content
}

#flask server
@app.route('/get-response', methods=['POST'])
def api_get_response():
data = request.json
note_content = data.get('note', '')
print(note_content)
response = get_response(note_content)
return jsonify({'response': response})
# def api_get_prompt():
# prompt = "Provide an engaging prompt to inspire note-taking:"
# response = get_response(prompt)
# return jsonify({'prompt': response})

if __name__ == '__main__':
app.run(port=5000)

# Example usage
if __name__ == "__main__":
# if __name__ == "__main__":

new_info = ("Recent advancements in quantum computing and their potential impact on cryptography.")
# new_info = ("Recent advancements in quantum computing and their potential impact on cryptography.")

knowledge_base = {
"title": ("Technology Trends"),
"pages": [
{"title": ("Quantum Computing Basics"), "content": "..."},
{"title": ("Modern Cryptography"), "content": "..."}
]
}
# knowledge_base = {
# "title": ("Technology Trends"),
# "pages": [
# {"title": ("Quantum Computing Basics"), "content": "..."},
# {"title": ("Modern Cryptography"), "content": "..."}
# ]
# }

updated_content = process_new_information(new_info, knowledge_base)
print("New content generated:", updated_content)
# updated_content = process_new_information(new_info, knowledge_base)
# print("New content generated:", updated_content)

62 changes: 62 additions & 0 deletions src/templates/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Notes Manager</title>
<style>
body { font-family: Arial, sans-serif; max-width: 800px; margin: 0 auto; padding: 20px; }
.note { border: 1px solid #ddd; padding: 10px; margin-bottom: 10px; }
form { margin-bottom: 20px; }
input, textarea { width: 100%; padding: 5px; margin-bottom: 10px; }
button { padding: 5px 10px; }
</style>
</head>
<body>
<h1>Notes Manager</h1>

<form action="{{ url_for('add_note') }}" method="post">
<input type="text" name="title" placeholder="Title" required>
<textarea name="content" placeholder="Note content" required></textarea>
<input type="text" name="category" placeholder="Category">
<button type="submit">Add Note</button>
</form>

<h2>Your Notes</h2>
{% for note in notes %}
<div class="note" data-note-id="{{ note['id'] }}">
<h3>{{ note['title'] }}</h3>
<p>{{ note['content'] }}</p>
<p><strong>Category:</strong> {{ note['category'] }}</p>
<p><strong>Date:</strong> {{ note['date'] }}</p>
<form action="{{ url_for('delete_note', id=note['id']) }}" method="post" style="display:inline;">
<button type="submit">Delete</button>
</form>
<button class="edit-button">Edit</button>
</div>
{% endfor %}

<script>
document.addEventListener('DOMContentLoaded', function() {
const editButtons = document.querySelectorAll('.edit-button');
editButtons.forEach(button => {
button.addEventListener('click', function() {
const noteId = this.closest('.note').dataset.noteId;
editNote(noteId);
});
});
});

function editNote(id) {
fetch(`/get_note/${id}`)
.then(response => response.json())
.then(note => {
document.querySelector('input[name="title"]').value = note.title;
document.querySelector('textarea[name="content"]').value = note.content;
document.querySelector('input[name="category"]').value = note.category;
// You might want to add a hidden input for the note id and change the form action for editing
});
}
</script>
</body>
</html>
51 changes: 51 additions & 0 deletions src/webapp.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
from flask import Flask, render_template, request, redirect, url_for, jsonify
from flask_cors import CORS
import sqlite3
from datetime import datetime

app = Flask(__name__)
CORS(app)

def get_db_connection():
conn = sqlite3.connect('notes.db')
conn.row_factory = sqlite3.Row
return conn

@app.route('/')
def index():
conn = get_db_connection()
notes = conn.execute('SELECT * FROM notes ORDER BY date DESC').fetchall()
conn.close()
return render_template('index.html', notes=notes)

@app.route('/add_note', methods=['POST'])
def add_note():
title = request.form['title']
content = request.form['content']
category = request.form['category']
date = datetime.now().isoformat()

conn = get_db_connection()
conn.execute('INSERT INTO notes (title, content, category, date) VALUES (?, ?, ?, ?)',
(title, content, category, date))
conn.commit()
conn.close()
return redirect(url_for('index'))

@app.route('/delete_note/<int:id>', methods=['POST'])
def delete_note(id):
conn = get_db_connection()
conn.execute('DELETE FROM notes WHERE id = ?', (id,))
conn.commit()
conn.close()
return redirect(url_for('index'))

@app.route('/get_note/<int:id>')
def get_note(id):
conn = get_db_connection()
note = conn.execute('SELECT * FROM notes WHERE id = ?', (id,)).fetchone()
conn.close()
return jsonify(dict(note))

if __name__ == '__main__':
app.run(debug=True, port=5001)

0 comments on commit d627997

Please sign in to comment.