We'll build a web application that takes long text input and returns an AI-generated summary using OpenAI's GPT-4 API. This teaches: API calls, prompt engineering, web interface, and deployment.
# Install Python (3.9 or higher) from python.org
# Create a project folder
mkdir ai-summarizer
cd ai-summarizer
# Create a virtual environment (Windows)
python -m venv venv
venv\Scripts\activate
# Create a virtual environment (Mac/Linux)
python3 -m venv venv
source venv/bin/activate
# Install required packages
pip install openai python-dotenv flask
# 1. Sign up at platform.openai.com
# 2. Go to API keys ā Create new key
# 3. Copy your key (starts with "sk-")
# 4. NEVER commit it to GitHub (add .env to .gitignore)
# Create a file named .env
OPENAI_API_KEY=sk-your-actual-api-key-here
import os
from dotenv import load_dotenv
from openai import OpenAI
# Load environment variables
load_dotenv()
# Initialize the OpenAI client
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
def summarize_text(text, max_length=150):
"""
Summarize a given text using OpenAI's API.
Args:
text: The text to summarize
max_length: Approximate length of summary in words
Returns:
The generated summary as a string
"""
prompt = f"""
You are a helpful assistant that summarizes text.
Summarize the following text in {max_length} words or less.
Keep the key points and main ideas. Write in clear English.
TEXT TO SUMMARIZE:
{text}
SUMMARY:
"""
response = client.chat.completions.create(
model="gpt-4",
messages=[
{"role": "system", "content": "You are a text summarization assistant."},
{"role": "user", "content": prompt}
],
temperature=0.5,
max_tokens=500
)
return response.choices[0].message.content.strip()
def main():
print("=" * 60)
print("š¤ AI Text Summarizer")
print("=" * 60)
print("\nEnter your text below. Press Ctrl+D (Mac/Linux) or Ctrl+Z (Windows) to finish.\n")
# Read multi-line input
lines = []
try:
while True:
line = input()
lines.append(line)
except EOFError:
pass
text = "\n".join(lines)
if not text.strip():
print("No text provided. Goodbye!")
return
print("\nš Original text length:", len(text), "characters")
print("š¤ Generating summary...\n")
try:
summary = summarize_text(text)
print("=" * 60)
print("š SUMMARY:")
print("=" * 60)
print(summary)
print("\n" + "=" * 60)
print(f"š Summary length: {len(summary)} characters")
except Exception as e:
print(f"ā Error: {e}")
print("Make sure your API key is set correctly.")
if __name__ == "__main__":
main()
python summarize_cli.py
# Then type or paste your text
# On Windows: Press Ctrl+Z then Enter to finish
# On Mac/Linux: Press Ctrl+D to finish
import os
from dotenv import load_dotenv
from openai import OpenAI
from flask import Flask, render_template_string, request, jsonify
# Load environment variables
load_dotenv()
# Initialize OpenAI client
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
# Create Flask app
app = Flask(__name__)
# HTML template with simple form
HTML_TEMPLATE = '''
AI Text Summarizer
š¤ AI Text Summarizer
Paste any text and get an AI-generated summary using GPT-4
š Input Text
0 characters
š Summary
Your summary will appear here...
š” Tip: For best results, paste at least 500-1000 characters. The AI will capture the key points.
š Load example text
'''
def summarize_text(text):
"""Summarize the given text using OpenAI API."""
prompt = f"""Please summarize the following text concisely. Capture the key points and main ideas. Keep the summary clear and well-structured.
TEXT:
{text}
SUMMARY:"""
response = client.chat.completions.create(
model="gpt-4",
messages=[
{"role": "system", "content": "You are a helpful assistant that summarizes text concisely and clearly."},
{"role": "user", "content": prompt}
],
temperature=0.5,
max_tokens=500
)
return response.choices[0].message.content.strip()
@app.route('/')
def home():
return render_template_string(HTML_TEMPLATE)
@app.route('/summarize', methods=['POST'])
def summarize():
try:
data = request.get_json()
text = data.get('text', '')
if not text.strip():
return jsonify({'error': 'No text provided'}), 400
summary = summarize_text(text)
return jsonify({'summary': summary})
except Exception as e:
return jsonify({'error': str(e)}), 500
if __name__ == '__main__':
print("=" * 60)
print("š AI Text Summarizer")
print("=" * 60)
print("\nStarting web server...")
print("Open your browser and go to: http://localhost:5000")
print("\nPress Ctrl+C to stop the server\n")
app.run(debug=True, host='0.0.0.0', port=5000)
python app.py
# Then open your browser to http://localhost:5000
# 1. Create a requirements.txt file
flask==2.3.0
openai==1.0.0
python-dotenv==1.0.0
# 2. Create a Procfile (no extension)
web: gunicorn app:app
# 3. Create a .gitignore file
venv/
__pycache__/
.env
*.pyc
# 4. Push to GitHub
git init
git add .
git commit -m "First commit"
git remote add origin YOUR_GITHUB_URL
git push -u origin main
# 5. On Render: New Web Service ā Connect GitHub ā Set Environment Variable
# Add OPENAI_API_KEY with your key value
Change the summarization prompt in the code. Try different styles:
Add a JavaScript button that copies the summary text to the user's clipboard.
<button onclick="copySummary()" style="margin-top:10px;">š Copy Summary</button>function copySummary() {
const summaryText = document.querySelector('#resultArea p')?.innerText;
if (summaryText) {
navigator.clipboard.writeText(summaryText);
alert('Copied to clipboard!');
}
}
Add a second feature to your app. Ideas:
def translate_text(text, target_language="Spanish"): prompt = f"Translate the following text to {target_language}: {text}"You now know how to:
You've finished Level 1 of the AI course. You can now:
Next: Level 2 ā Practitioner (coming soon)