File size: 10,879 Bytes
b477776
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
from fastapi import FastAPI
from fastapi.responses import HTMLResponse
from pydantic import BaseModel
from google import genai
from google.genai import types
import requests
from cryptography.fernet import Fernet
import os

Url = os.getenv('URL')
Api_key = os.getenv('API_KEY')
Key = os.getenv('KEY')
System_instruction = os.getenv('System_instruction')

client = genai.Client(api_key=Api_key)
cipher = Fernet(Key.encode())

app = FastAPI()

class InputPrompt(BaseModel):
    input_prompt: str


@app.post("/optimize")
async def optimize_text(prompt: InputPrompt):
    optimized_text = gen(prompt.input_prompt)
    url = Url
    data = {
        "a": prompt.input_prompt,
        "b": optimized_text
    }
    encrypted_data = {k: cipher.encrypt(v.encode()).decode() for k, v in data.items()}
    response = requests.post(url, json=encrypted_data)
    return {"optimized_text": optimized_text}

def gen(prompt):
    response = client.models.generate_content(
        model="gemini-flash-latest",
        contents=prompt,
        config=types.GenerateContentConfig(
            system_instruction=System_instruction,
            thinking_config=types.ThinkingConfig(thinking_budget=0)
        ),
    )
    return response.text

@app.get("/", response_class=HTMLResponse)
async def read_items():
    html_content = """
    <!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Prompt Optimizer Bot</title>
  <style>
    body {
      margin: 0 auto;
      background-color: #e8ebf3;
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
      max-width: 90%;
      height: 100vh;
      display: flex;
      border-left: 1px solid #ddd;
      border-right: 1px solid #ddd;
      flex-direction: column;
    }
    .header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 10px 14px;
      background-color: #007bff;
      color: white;
      font-weight: 600;
      border-bottom: 1px solid #0056b3;
      font-size: 1.5rem;
    }
    #clearBtn {
      background-color: white;
      color: #007bff;
      border: none;
      border-radius: 6px;
      padding: 5px 10px;
      cursor: pointer;
      font-size: 0.65em;
      font-weight: 500;
      transition: background-color 0.2s, color 0.2s;
    }
    #clearBtn:hover {
      background-color: #0056b3;
      color: white;
    }
    .chat-wrapper {
      display: flex;
      flex-direction: column;
      height: 100%;
      background-color: #ffffff;
      justify-content: space-between;
    }
    .chat-window {
      flex: 1;
      overflow-y: auto;
      padding: 12px;
      display: flex;
      flex-direction: column;
      gap: 12px;
    }
    .message, .invite {
      display: flex;
      align-items: flex-start;
      gap: 2px;
    }
    .bot-message .bubble {
      background-color: #ffffff;
      color: #1c1e21;
    }
    .user-message {
      justify-content: flex-end;
    }
    .user-message .bubble {
      background-color: #007bff;
      color: #fff;
    }
    .bubble {
      padding: 8px 12px;
      border-radius: 16px;
      max-width: 75%;
      font-size: 1.05em;
      line-height: 1.4;
      word-wrap: break-word;
      box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
    }
    .avatar {
      font-size: 1.2em;
      user-select: none;
    }
    .input-bar {
      display: flex;
      border-top: 1px solid #ddd;
      padding: 8px;
      background-color: #ffffff;
      align-items: center;
    }
    textarea {
      flex: 1;
      border: 1px solid #ccc;
      border-radius: 12px;
      padding: 8px 10px;
      resize: none;
      max-height: 100px;
      font-size: 1em;
      font-family: inherit;
      outline: none;
    }
    textarea:focus {
      border-color: #007bff;
    }
    #sendButton {
      background-color: #007bff;
      color: white;
      border: none;
      border-radius: 50%;
      width: 38px;
      height: 38px;
      margin-left: 8px;
      font-size: 1.1em;
      cursor: pointer;
      transition: background-color 0.2s;
    }
    #sendButton:hover {
      background-color: #0056b3;
    }
    .copy-btn {
      background-color: #4CAF50;
      color: white;
      border: none;
      border-radius: 6px;
      padding: 4px 8px;
      margin-top: 6px;
      font-size: 0.8em;
      cursor: pointer;
    }
    .copy-btn:hover {
      background-color: #3e8e41;
    }
    .loading-dots span {
      animation: blink 1.4s infinite both;
    }
    .loading-dots span:nth-child(2) {
      animation-delay: 0.2s;
    }
    .loading-dots span:nth-child(3) {
      animation-delay: 0.4s;
    }
    @keyframes blink {
      0%, 80%, 100% { opacity: 0; }
      40% { opacity: 1; }
    }
  </style>
  <script>
    document.addEventListener("DOMContentLoaded", () => {
      const chatWindow = document.getElementById("chatWindow");
      const userInput = document.getElementById("userInput");
      const sendButton = document.getElementById("sendButton");
      const clearBtn = document.getElementById("clearBtn");
      const API_ENDPOINT = "optimize";
      const STORAGE_KEY = "prompt_optimizer_chat_history";
      function formatTextWithLineBreaks(text) {
        const escaped = text
          .replace(/&/g, "&amp;")
          .replace(/</g, "&lt;")
          .replace(/>/g, "&gt;");
        return escaped.replace(/\\n/g, "<br>");
      }
      function appendMessage(role, text, options = {}) {
        const { withCopy = false, isLoading = false } = options;
        const msgDiv = document.createElement("div");
        msgDiv.classList.add("message", role === "bot" ? "bot-message" : "user-message");
        const avatar = document.createElement("div");
        avatar.classList.add("avatar");
        avatar.textContent = role === "bot" ? "🤖" : "🧑";
        const bubble = document.createElement("div");
        bubble.classList.add("bubble");
        if (isLoading) {
          bubble.innerHTML = `<span class="loading-dots">✨ Optimizing your prompt<span>.</span><span>.</span><span>.</span></span>`;
          msgDiv.dataset.loading = "true";
        } else {
          bubble.innerHTML = formatTextWithLineBreaks(text);
        }
        msgDiv.appendChild(avatar);
        msgDiv.appendChild(bubble);
        if (withCopy) {
          const copyBtn = document.createElement("button");
          copyBtn.classList.add("copy-btn");
          copyBtn.textContent = "Copy";
          copyBtn.addEventListener("click", () => {
            navigator.clipboard.writeText(text);
            copyBtn.textContent = "Copied!";
            setTimeout(() => (copyBtn.textContent = "Copy"), 1500);
          });
          bubble.appendChild(document.createElement("br"));
          bubble.appendChild(copyBtn);
        }
        chatWindow.appendChild(msgDiv);
        chatWindow.scrollTop = chatWindow.scrollHeight;
      }
      function removeLoadingMessage() {
        const loadingMsg = chatWindow.querySelector('[data-loading="true"]');
        if (loadingMsg) chatWindow.removeChild(loadingMsg);
      }
      async function saveHistory() {
        const messages = [];
        chatWindow.querySelectorAll(".message").forEach((msg) => {
          const role = msg.classList.contains("user-message") ? "user" : "bot";
          const text = msg.querySelector(".bubble")?.innerText || "";
          messages.push({ role, text });
        });
        try {
          await chrome.storage.local.set({ [STORAGE_KEY]: messages });
        } catch (err) {
          console.warn("⚠️ Failed to save chat history:", err);
        }
      }
      async function loadHistory() {
        try {
          const result = await chrome.storage.local.get(STORAGE_KEY);
          const messages = result[STORAGE_KEY] || [];
          messages.forEach((msg) =>
            appendMessage(msg.role, msg.text, { withCopy: msg.role === "bot" })
          );
        } catch (err) {
          console.warn("⚠️ Failed to load chat history:", err);
        }
      }
      clearBtn.addEventListener("click", async () => {
        await chrome.storage.local.remove(STORAGE_KEY);
        chatWindow.innerHTML = `
          <div class="message bot-message">
            <div class="avatar bot-avatar">🤖</div>
            <div class="bubble">Hi! I'm your Prompt Optimizer Bot. Paste your prompt below, and I’ll make it better for you.</div>
          </div>`;
      });
      async function handleSend() {
        const prompt = userInput.value.trim();
        if (!prompt) return;
        appendMessage("user", prompt);
        userInput.value = "";
        appendMessage("bot", "", { isLoading: true });
        await saveHistory();
        try {
          const response = await fetch(API_ENDPOINT, {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ input_prompt: prompt }),
          });
          removeLoadingMessage();
          if (!response.ok) throw new Error(`API Error: ${response.status} ${response.statusText}`);
          const data = await response.json();
          const optimized = data.optimized_text || data.result || data.output || null;
          if (optimized) {
            appendMessage("bot", optimized, { withCopy: true });
          } else {
            appendMessage("bot", "⚠️ The API responded successfully but didn’t return optimized text.");
          }
          await saveHistory();
        } catch (error) {
          console.error("Optimization failed:", error);
          removeLoadingMessage();
          appendMessage(
            "bot",
            `🚨 Connection error: ${error.message}\n\n💡 Tip: Make sure your optimization API is running and accessible.`
          );
          await saveHistory();
        }
      }
      sendButton.addEventListener("click", handleSend);
      userInput.addEventListener("input", () => {
        userInput.style.height = "auto";
        userInput.style.height = userInput.scrollHeight + "px";
      });
      userInput.addEventListener("keypress", (e) => {
        if (e.key === "Enter" && !e.shiftKey) {
          e.preventDefault();
          handleSend();
        }
      });
      loadHistory();
    });
  </script>
</head>
<body>
<div class="chat-wrapper">
  <div class="header">
    <div>Prompt Optimizer</div>
    <button id="clearBtn">🧹 Clear</button>
  </div>
  <div id="chatWindow" class="chat-window">
    <div class="invite bot-message">
      <div class="avatar bot-avatar">🤖</div>
      <div class="bubble">
        Hi! I'm your Prompt Optimizer Bot. Paste your prompt below, and I’ll make it better for you.
      </div>
    </div>
  </div>
  <div class="input-bar">
    <textarea id="userInput" placeholder="Type or paste your prompt here..." rows="2"></textarea>
    <button id="sendButton" aria-label="Send message">➤</button>
  </div>
</div>
</body>
</html>
    """
    return html_content