File size: 8,184 Bytes
68adb43
 
 
 
 
 
 
 
 
 
 
 
7d468dd
25978d4
68adb43
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
import streamlit as st
from sentence_transformers import SentenceTransformer
import torch
import json
from streamlit_lottie import st_lottie
from notion_client import Client
from datetime import datetime

# Set page config at the very beginning
st.set_page_config(page_title="Prompt easz", layout="centered")

# Initialize Notion client
notion=Client(auth=st.secrets["NOTION_API_KEY"])
NOTION_DATABASE_ID = st.secrets["notiondb"]

# Custom CSS to increase text size, beautify the app, and highlight the final message
st.markdown("""
    <style>
    .big-font {
        font-size:60px !important;
        text-align: center;
    }
    .slider-label {
        font-size:25px !important;
        font-weight: bold;
    }
    .small-text {
        font-size:12px !important;
    }
    .medium-text {
        font-size:16px !important;
    }
    .center-text {
        text-align: center;
    }
    .highlight {
        font-family: 'Courier New', Courier, monospace;
        background-color: #f0f0f0;
        padding: 10px;
        border-radius: 5px;
    }
    .stTextInput > div > div > input, .stSelectbox > div > div > select, .stButton > button { font-size: 16px; }
    .stMarkdown { font-size: 14px; }
    </style>
    """, unsafe_allow_html=True)

@st.cache_resource
def load_model():
    return SentenceTransformer('all-MiniLM-L6-v2')

@st.cache_data
def load_prompts():
    try:
        with open('prompts.json', 'r') as file:
            return json.load(file)
    except json.JSONDecodeError as e:
        st.error(f"Error loading prompts.json: {e}")
        return {}

@st.cache_data
def load_categories():
    try:
        with open('categories.json', 'r') as file:
            return json.load(file)
    except json.JSONDecodeError as e:
        st.error(f"Error loading categories.json: {e}")
        return {}

def load_lottiefile(filepath: str):
    with open(filepath, "r") as f:
        return json.load(f)

def find_prompt_types(user_input, num_types=3):
    model = load_model()
    prompt_types = load_prompts()
    user_embedding = model.encode(user_input, convert_to_tensor=True)
    similarities = {}
    for pt, data in prompt_types.items():
        all_keywords = " ".join([" ".join(variation["keywords"]) for variation in data])
        pt_embedding = model.encode(all_keywords, convert_to_tensor=True)
        similarity = torch.cosine_similarity(user_embedding, pt_embedding, dim=0).item()
        similarities[pt] = similarity
    return sorted(similarities, key=similarities.get, reverse=True)[:num_types]

def generate_prompt(prompt_type, topic, category, complexity, topic2=None, constraint=None):
    model = load_model()
    prompt_types = load_prompts()
    categories_info = load_categories()
    template = prompt_types[prompt_type][0]["template"]
    complexity_instructions = {
        "low": "Use simple language and basic concepts. Avoid technical jargon and provide elementary explanations suitable for beginners.",
        "medium": "Include more detailed explanations and introduce some field-specific terminology. Provide a balance between depth and accessibility.",
        "high": "Delve into advanced concepts and use specialized terminology. Assume a high level of prior knowledge and provide in-depth analysis."
    }
    category_info = categories_info.get(category, {})
    analogy = category_info.get("analogy", "analogous")
    expert_role = category_info.get("expert_role", "an expert")
    related_topics = ", ".join(category_info.get("related_topics", []))
    return f"""
    # {prompt_type} Prompt: {topic} in {category}

    {template.format(topic=topic, category=category, topic2=topic2, constraint=constraint)}

    **Complexity: {complexity.capitalize()}**
    {complexity_instructions[complexity]}

    **Category Details:**
    - **Analogy:** {analogy}
    - **Expert Role:** {expert_role}
    - **Related Topics:** {related_topics}

    **Additional Instructions:**
    - Ensure your response is well-structured and easy to follow.
    - Use relevant examples to illustrate key points.
    - Tailor your language to the specified complexity level.
    """.strip()

def save_feedback_to_notion(user_prompt, improvement_suggestion, timestamp):
    try:
        notion.pages.create(
            parent={"database_id": NOTION_DATABASE_ID},
            properties={
                "User Prompt": {"title": [{"text": {"content": user_prompt}}]},
                "Improvement Suggestion": {"rich_text": [{"text": {"content": improvement_suggestion}}]}
            }
        )
        return True
    except Exception as e:
        # Log the error to the console instead of displaying it in the Streamlit app
        print(f"Error saving to Notion: {str(e)}")
        return False

def main():
    # Display the title and animation
    st.markdown('<h1 class="big-font">Prompt easz</h1>', unsafe_allow_html=True)
    st.markdown('<h2 class="center-text">AI Prompt Generator</h2>', unsafe_allow_html=True)
    
    # Load and display Lottie animation
    lottie_animation = load_lottiefile("animation.json")  # Replace with your Lottie file path
    col1, col2, col3 = st.columns([1,2,1])
    with col2:
        st_lottie(lottie_animation, speed=1, height=400, key="initial")

    # Add About link with icon below the Lottie animation
    col1, col2, col3 = st.columns([1,2,1])
    with col2:
        st.markdown(
            '<div style="text-align: center;">'
            '<a href="/About" target="_blank" style="text-decoration: none;">'
            '<span style="font-size: 24px;">ℹ️</span> '
            '<span style="vertical-align: middle;">About</span>'
            '</a>'
            '</div>',
            unsafe_allow_html=True
        )

    user_input = st.text_input("What would you like a prompt for?")

    if user_input:
        suggested_types = find_prompt_types(user_input)
        prompt_types = load_prompts()
        categories_info = load_categories()

        unique_types = list(set(list(prompt_types.keys()) + suggested_types))
        
        topic = st.text_input("πŸ“Œ Main Topic:", value=user_input)
        category = st.selectbox("🏷️ Category or Field:", options=list(categories_info.keys()), index=0)
        complexity = st.select_slider("🧠 Complexity Level:", options=["low", "medium", "high"], value="medium")
        
        st.write("Choose Your Prompt")
        
        selected_tab = st.selectbox("Select Prompt Type:", unique_types)

        if selected_tab in prompt_types:
            topic2 = st.text_input(f"πŸ“Œ Second Topic for {selected_tab}:", key=f"{selected_tab}_topic2") if selected_tab == "Comparative Analysis" else None
            constraint = st.number_input(f"πŸ”’ Word Limit for {selected_tab}:", min_value=10, max_value=500, value=50, key=f"{selected_tab}_constraint") if selected_tab == "Constraint Addition" else None
            
            prompt = generate_prompt(selected_tab, topic, category, complexity, topic2, constraint)
            st.markdown(prompt)

            # Add feedback collection section
            st.subheader("Provide Feedback")
            improvement_suggestion = st.text_area("What can be improved in this prompt?", height=100)
            
            if st.button("Submit Feedback"):
                if improvement_suggestion:
                    timestamp = datetime.now().isoformat()
                    if save_feedback_to_notion(prompt, improvement_suggestion, timestamp):
                        st.success("Feedback saved to Notion successfully!")
                    else:
                        st.error("Failed to save feedback to Notion.")
                else:
                    st.warning("Please provide feedback before submitting.")

    st.markdown("---")
    st.markdown("""
    ### 🌟 How to Use AI Prompt Wizard Ultimate
    1. Enter your desired topic or question.
    2. Adjust the main topic, category, and complexity if needed.
    3. Select the prompt type from the dropdown.
    4. View the generated prompt.
    5. Provide feedback on what can be improved in the prompt.
    6. Submit your feedback to help us enhance our prompt generation.
    """)

if __name__ == "__main__":
    main()