File size: 14,479 Bytes
82aaf07
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>HF Space AI Workspace</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- JSZip for client side unzip and document parsing -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
</head>
<body class="bg-gray-900 text-gray-100 h-screen flex flex-col font-sans">

    <!-- Header Config -->
    <header class="bg-gray-800 border-b border-gray-700 p-4">
        <div class="max-w-6xl mx-auto flex flex-col sm:flex-row justify-between items-center gap-4">
            <h1 class="text-xl font-bold tracking-tight text-white flex items-center gap-2">
                <span></span> HF Space AI Gateway
            </h1>
            <div class="flex flex-wrap items-center gap-3 w-full sm:w-auto justify-end">
                <!-- Smart HF URL Container: Shows only if HTML is run locally -->
                <div id="hf-url-container" class="hidden w-full sm:w-auto">
                    <input type="text" id="hf-url-input" placeholder="Hugging Face Direct URL (e.g. https://your-space.hf.space)" 
                           class="bg-gray-700 border border-gray-600 rounded px-3 py-1.5 text-xs text-white w-full sm:w-72">
                </div>
                
                <div class="flex items-center gap-2">
                    <label for="model-select" class="text-xs text-gray-300 whitespace-nowrap">Model:</label>
                    <select id="model-select" class="bg-gray-700 border border-gray-600 rounded px-2.5 py-1.5 text-xs text-white focus:outline-none focus:ring-2 focus:ring-blue-500">
                        <option value="claude-opus-4-8">claude-opus-4-8</option>
                        <option value="claude-opus-4-7">claude-opus-4-7</option>
                        <option value="claude-opus-4-6">claude-opus-4-6</option>
                        <option value="glm-5.2">glm-5.2</option>
                        <option value="gpt-5.5">gpt-5.5</option>
                    </select>
                </div>
            </div>
        </div>
    </header>

    <!-- Chat Console -->
    <main id="chat-container" class="flex-1 overflow-y-auto p-4 space-y-4 max-w-4xl mx-auto w-full">
        <div class="bg-gray-800 rounded-lg p-4 border border-gray-700 text-gray-300 text-sm">
            <p class="font-semibold text-white mb-1">CORS & WAF Bypassed Workspace</p>
            <p class="text-xs">ZIP archives, python/js documents, aur images upload karein. ZIP files browser mein hi automatically extract ho kar readable XML codeblocks mein tabdeel ho jayengi taake AI poore code ko dekh sake.</p>
        </div>
        <div id="file-preview-area" class="flex flex-wrap gap-2"></div>
    </main>

    <!-- Controls Input -->
    <footer class="bg-gray-800 border-t border-gray-700 p-4">
        <div class="max-w-4xl mx-auto flex flex-col gap-3">
            <div class="flex items-center gap-4">
                <label class="cursor-pointer bg-gray-700 hover:bg-gray-600 text-xs text-gray-300 px-3 py-1.5 rounded border border-gray-600 flex items-center gap-1.5">
                    <span>📎</span> Attach Files / ZIPs / Images
                    <input type="file" id="file-input" multiple class="hidden">
                </label>
                <span id="attached-count" class="text-xs text-gray-400">No files attached</span>
            </div>
            
            <div class="flex gap-3">
                <input type="text" id="user-input" placeholder="Type a message..." 
                       class="flex-1 bg-gray-700 border border-gray-600 rounded px-4 py-3 text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500">
                <button id="send-btn" class="bg-blue-600 hover:bg-blue-700 text-white font-medium px-6 py-3 rounded transition">
                    Send
                </button>
            </div>
        </div>
    </footer>

    <script>
        const API_KEY = "sk-P7JoqWr5SriePQgq1ijtiGxkL5elV4C84xtqL2MoNQpi1uLs";
        
        const chatContainer = document.getElementById("chat-container");
        const userInput = document.getElementById("user-input");
        const sendBtn = document.getElementById("send-btn");
        const modelSelect = document.getElementById("model-select");
        const fileInput = document.getElementById("file-input");
        const filePreviewArea = document.getElementById("file-preview-area");
        const attachedCount = document.getElementById("attached-count");
        const hfUrlContainer = document.getElementById("hf-url-container");
        const hfUrlInput = document.getElementById("hf-url-input");

        let conversationHistory = [];
        let pendingFilesData = [];

        // Check if index.html is loaded as local file or hosted directly
        const isLocal = window.location.protocol === "file:" || window.location.hostname === "localhost" || window.location.hostname === "127.0.0.1";
        
        if (isLocal) {
            hfUrlContainer.classList.remove("hidden"); // Show URL field if run as offline file
        }

        const isTextFile = (name) => /\.(txt|py|js|jsx|ts|tsx|html|css|json|csv|md|yaml|yml|rs|go|java|c|cpp|h|sh|bat)$/i.test(name);
        const isImageFile = (name) => /\.(png|jpg|jpeg|webp|gif)$/i.test(name);

        const toBase64 = file => new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onload = () => resolve(reader.result);
            reader.onerror = error => reject(error);
        });

        // Smart file handler for ZIPs and documents
        fileInput.addEventListener("change", async (e) => {
            const files = e.target.files;
            for (let file of files) {
                try {
                    if (file.name.endsWith(".zip")) {
                        const zip = await JSZip.loadAsync(file);
                        let extractedText = "";
                        for (let relativePath in zip.files) {
                            const zipFile = zip.files[relativePath];
                            if (!zipFile.dir && isTextFile(relativePath)) {
                                const content = await zipFile.async("string");
                                // Wrap contents in XML style tags so models can process structures correctly
                                extractedText += `\n<file path="${relativePath}">\n${content}\n</file>\n`;
                            }
                        }
                        pendingFilesData.push({
                            type: "text_data",
                            name: file.name,
                            content: `User uploaded a ZIP file named "${file.name}" with the following file structures inside:\n${extractedText}`
                        });
                    } else if (isTextFile(file.name)) {
                        const text = await file.text();
                        pendingFilesData.push({
                            type: "text_data",
                            name: file.name,
                            content: `\n<file path="${file.name}">\n${text}\n</file>\n`
                        });
                    } else if (isImageFile(file.name)) {
                        const base64Str = await toBase64(file);
                        pendingFilesData.push({
                            type: "image_data",
                            name: file.name,
                            content: base64Str
                        });
                    } else {
                        // Fallback plain text read
                        const text = await file.text();
                        pendingFilesData.push({
                            type: "text_data",
                            name: file.name,
                            content: `\n<file path="${file.name}">\n${text}\n</file>\n`
                        });
                    }
                } catch (err) {
                    alert(`Could not process/read file: ${file.name}`);
                }
            }
            updatePreviewUI();
        });

        function updatePreviewUI() {
            filePreviewArea.innerHTML = "";
            attachedCount.textContent = `${pendingFilesData.length} files attached`;
            pendingFilesData.forEach((file, index) => {
                const badge = document.createElement("div");
                badge.className = "bg-gray-800 text-xs px-2.5 py-1 rounded border border-gray-700 flex items-center gap-1.5";
                badge.innerHTML = `
                    <span class="text-gray-400">${file.type === 'image_data' ? '🖼️' : '📄'} ${file.name}</span>
                    <button class="text-red-400 font-bold ml-1 hover:text-red-300" onclick="removeFile(${index})">×</button>
                `;
                filePreviewArea.appendChild(badge);
            });
        }

        window.removeFile = (index) => {
            pendingFilesData.splice(index, 1);
            updatePreviewUI();
        }

        function appendMessage(role, text) {
            const messageDiv = document.createElement("div");
            messageDiv.className = `flex ${role === 'user' ? 'justify-end' : 'justify-start'}`;
            const innerDiv = document.createElement("div");
            innerDiv.className = `max-w-[85%] rounded-lg px-4 py-3 ${
                role === 'user' 
                    ? 'bg-blue-600 text-white rounded-br-none' 
                    : 'bg-gray-800 text-gray-200 border border-gray-700 rounded-bl-none'
            }`;
            innerDiv.style.whiteSpace = 'pre-wrap';
            innerDiv.textContent = text;
            messageDiv.appendChild(innerDiv);
            chatContainer.appendChild(messageDiv);
            chatContainer.scrollTop = chatContainer.scrollHeight;
            return innerDiv;
        }

        async function handleSend() {
            let apiEndpointUrl = "/v1/chat/completions";

            if (isLocal) {
                const customHfUrl = hfUrlInput.value.trim().replace(/\/$/, "");
                if (!customHfUrl) {
                    alert("Pehle apna Hugging Face Space URL enter karein!");
                    return;
                }
                apiEndpointUrl = `${customHfUrl}/v1/chat/completions`;
            }

            const textInputVal = userInput.value.trim();
            if (!textInputVal && pendingFilesData.length === 0) return;

            let textPayload = textInputVal;
            let imagePayloads = [];

            pendingFilesData.forEach(file => {
                if (file.type === "text_data") {
                    textPayload += `\n\n${file.content}`;
                } else if (file.type === "image_data") {
                    imagePayloads.push(file.content);
                }
            });

            appendMessage("user", textInputVal || "Attached files context uploaded");
            userInput.value = "";
            pendingFilesData = [];
            updatePreviewUI();

            // Construct payload content shape
            let messageContent;
            if (imagePayloads.length > 0) {
                messageContent = [{ type: "text", text: textPayload }];
                imagePayloads.forEach(imgBase64 => {
                    messageContent.push({
                        type: "image_url",
                        image_url: { url: imgBase64 }
                    });
                });
            } else {
                messageContent = textPayload;
            }

            conversationHistory.push({ role: "user", content: messageContent });

            const assistantBubble = appendMessage("assistant", "Generating answer...");
            assistantBubble.textContent = "";

            try {
                const response = await fetch(apiEndpointUrl, {
                    method: "POST",
                    headers: {
                        "Content-Type": "application/json",
                        "Authorization": `Bearer ${API_KEY}`
                    },
                    body: JSON.stringify({
                        model: modelSelect.value,
                        messages: conversationHistory,
                        stream: true
                    })
                });

                if (!response.ok) {
                    throw new Error(`HTTP Error: ${response.status}`);
                }

                const reader = response.body.getReader();
                const decoder = new TextDecoder("utf-8");
                let buffer = "";
                let completeResponse = "";

                while (true) {
                    const { value, done } = await reader.read();
                    if (done) break;

                    buffer += decoder.decode(value, { stream: true });
                    const lines = buffer.split("\n");
                    buffer = lines.pop();

                    for (const line of lines) {
                        const cleanLine = line.trim();
                        if (cleanLine.startsWith("data: ")) {
                            const dataStr = cleanLine.slice(6);
                            if (dataStr === "[DONE]") break;
                            try {
                                const parsed = JSON.parse(dataStr);
                                const content = parsed.choices[0].delta.content;
                                if (content) {
                                    completeResponse += content;
                                    assistantBubble.textContent = completeResponse;
                                    chatContainer.scrollTop = chatContainer.scrollHeight;
                                }
                            } catch (e) {}
                        }
                    }
                }

                conversationHistory.push({ role: "assistant", content: completeResponse });

            } catch (error) {
                console.error(error);
                assistantBubble.textContent = `Error: ${error.message}. Connection lost or HF space is paused.`;
                assistantBubble.classList.add("text-red-400");
            }
        }

        sendBtn.addEventListener("click", handleSend);
        userInput.addEventListener("keydown", (e) => {
            if (e.key === "Enter") handleSend();
        });
    </script>
</body>
</html>