Skip to content

Instantly share code, notes, and snippets.

@seqis
Last active October 4, 2024 17:17
Show Gist options
  • Select an option

  • Save seqis/c4ca9671d5d876746f88cb942959d82e to your computer and use it in GitHub Desktop.

Select an option

Save seqis/c4ca9671d5d876746f88cb942959d82e to your computer and use it in GitHub Desktop.
This script sends any text in your clipboard to the OpenAI API for summary and puts that summary right back into the clipboard. You can modify your model name and API key variables below.
#!/usr/bin/env python3
import pyperclip
from openai import OpenAI
# Function to summarize the text using a valid OpenAI model
def summarize_text(text, client):
# Define the instructions for the summarizer
instructions = """
IDENTITY and PURPOSE
Summarize the text given into a Markdown formatted summary.
First, output a summary paragraph explaining the entire text. This paragraph should be as long as necessary to explain all the key points.
Then, create a 10 bullet-point MARKDOWN list called "Key Points": and place the most important key takeaway points there.
Finally, add a section for "Memorable Quote" and put the most memorable quote in that section.
"""
# Combine the instructions with the input text
content = instructions + "\n\n" + text
try:
# Send the request to OpenAI's API using a valid model
response = client.chat.completions.create(
model="gpt-4o-mini", # Use "gpt-3.5-turbo" if preferred
messages=[
{"role": "system", "content": "You are a helpful assistant that summarizes text."},
{"role": "user", "content": content},
],
max_tokens=1000 # Adjust as needed
)
# Extract the summary from the response
summary = response.choices[0].message.content.strip()
return summary
except Exception as e:
print(f"An error occurred: {e}")
return ""
# Main function
def main():
# Get the content from the clipboard
text = pyperclip.paste().strip()
# Your ChatGPT API key
# IMPORTANT: Keep your API key secure. Do not share this script publicly.
api_key = "PLACE YOUR OpenAI API KEY HERE"
# Validate the API key format
if api_key.startswith("sk-") and len(api_key) > 10:
# Initialize OpenAI client
client = OpenAI(api_key=api_key)
# Get the summary of the text
summary = summarize_text(text, client)
if summary:
# Copy the summary to the clipboard
pyperclip.copy(summary)
print("The summary has been copied to your clipboard.")
else:
print("Failed to generate a summary.")
else:
print("Error: Invalid API key format.")
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment