Can you take the following code of mine that is for a ai chatbot user interface in a browser localhost. Can you now dive into making the design much better and making it look professional calm and like an award winning website design. You can use bootstrap or tailwind or whatever will get us closer to making something truly beautiful and easy to use that people like because of the way it runs and looks. Dive deep into the design elements and feel free to create something that you would be proud of saying you created.




import os
import openai
from flask import Flask, render_template, request, jsonify
from pinecone import Pinecone, ServerlessSpec
import random
from dotenv import load_dotenv

# Load environment variables from .env file
load_dotenv()

# Initialize Flask app
app = Flask(__name__)

# Initialize OpenAI API
openai.api_key = os.getenv("OPENAI_API_KEY")

# Initialize Pinecone client
pc = Pinecone(api_key=os.getenv("PINECONE_API_KEY"))

# Define Pinecone index details
INDEX_NAME = "academicphil"
HOST = "https://academicphil-v9aromm.svc.aped-4627-b74a.pinecone.io"
ENVIRONMENT = "us-east-1"

# Create or connect to Pinecone index
if INDEX_NAME not in [index.name for index in pc.list_indexes().indexes]:
    pc.create_index(
        name=INDEX_NAME,
        dimension=1536,
        metric="cosine",
        spec=ServerlessSpec(
            cloud="aws",
            region=ENVIRONMENT
        )
    )
index = pc.Index(INDEX_NAME)

def embed_text(text: str) -> list:
    response = openai.Embedding.create(
        input=[text],
        model="text-embedding-3-small"  # Updated to a commonly used embedding model
    )
    return response['data'][0]['embedding']

def get_relevant_context(query: str, top_k: int = 10, random_subset_size: int = 3) -> str:
    query_embedding = embed_text(query)
    context = ""
    retrieved_texts = []
    seen_texts = set()
    unique_matches = 0
    query_offset = 0

    while unique_matches < top_k:
        try:
            results = index.query(
                vector=query_embedding,
                top_k=top_k + query_offset,
                include_metadata=True
            )
        except Exception as e:
            print(f"Error querying Pinecone: {e}")
            return ""

        for match in results['matches']:
            text = match['metadata']['text']
            if text not in seen_texts:
                retrieved_texts.append(text)
                seen_texts.add(text)
                unique_matches += 1
                if unique_matches >= top_k:
                    break
        query_offset += top_k

        if len(results['matches']) < top_k:
            break  # No more results available

    # Select a random subset of the top-scoring matches
    random_subset = random.sample(retrieved_texts, min(random_subset_size, len(retrieved_texts)))

    # Create the context string
    for text in random_subset:
        context += text + "\n"

    return context

def generate_summary(context: str) -> str:
    messages = [
        {"role": "system", "content": "You are an expert in summarization and are known for your ability to take complex information and distill it down to detailed but easy to understand text that is clear and precise and academic. You will be given text from multiple different sources that roughly deal with the same topics. Use the provided context to generate a summary of the texts as well as putting special emphasis on highlighting any information you think is especially intriguing, fascinating and interesting. Be very detailed and thorough and if warranted quote direct passages from the texts you found especially enlightening and interesting."},
        {"role": "user", "content": context},
    ]

    try:
        response = openai.ChatCompletion.create(
            model="gpt-4o-mini",
            messages=messages,
            max_tokens=3500,
            temperature=0.7,
            top_p=1.0,
            frequency_penalty=0.0,
            presence_penalty=0.0
        )
        return response['choices'][0]['message']['content']
    except Exception as e:
        print(f"Error generating summary: {e}")
        return "An error occurred while generating the summary."

@app.route('/')
def home():
    return render_template('index.html')

@app.route('/generate_summary', methods=['POST'])
def handle_generate_summary():
    data = request.get_json()
    user_input = data.get('user_input', '')
    if not user_input:
        return jsonify({"error": "No input provided."}), 400

    context = get_relevant_context(user_input)
    if not context:
        return jsonify({"error": "Failed to retrieve context."}), 500

    summary = generate_summary(context)
    return jsonify({"summary": summary})

if __name__ == "__main__":
    app.run(debug=True)