File size: 8,624 Bytes
1c05cb6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import json
import base64
import os, io
import mimetypes
from PIL import Image
import gradio as gr

def import_history(history, file):
    if os.path.getsize(file.name) > 100e6:
        raise ValueError("History larger than 100 MB")

    with open(file.name, mode="rb") as f:
        content = f.read().decode('utf-8', 'replace')

    import_data = json.loads(content)
    
    # Handle different import formats
    if 'messages' in import_data:
        # New OpenAI-style format
        messages = import_data['messages']
        system_prompt_value = ''
        chat_history = []
        
        msg_num = 1
        for msg in messages:
            if msg['role'] == 'system':
                system_prompt_value = msg['content']
                continue
                
            if msg['role'] == 'user':
                content = msg['content']
                if isinstance(content, list):
                    for item in content:
                        if item.get('type', '') == 'image_url':
                            # Create gr.Image from data URI
                            image_data = base64.b64decode(item['image_url']['url'].split(',')[1])
                            img = Image.open(io.BytesIO(image_data))
                            chat_history.append({
                                "role": msg['role'],
                                "content": gr.Image(value=img)
                            })
                        elif item.get('type', '') == 'file':
                            # Handle file content with gr.File
                            fname = os.path.basename(item['file'].get('name', f'download{msg_num}'))
                            dir_path = os.path.dirname(file.name)
                            temp_path = os.path.join(dir_path, fname)
                            file_data = base64.b64decode(item['file']['url'].split(',')[1])
                            if (len(file_data) > 15e6):
                                raise ValueError(f"file content `{fname}` larger than 15 MB")
                            
                            with open(temp_path, "wb") as tempf:
                                tempf.write(file_data)
                            chat_history.append({
                                "role": msg['role'],
                                "content": gr.File(value=temp_path, 
                                                 label=fname)
                            })
                        else:
                            chat_history.append(msg)
                else:
                    chat_history.append(msg)
                    
            elif msg['role'] == 'assistant':
                chat_history.append(msg)

            msg_num = msg_num + 1
            
    else:
        # Legacy format handling
        if 'history' in import_data:
            legacy_history = import_data['history']
            system_prompt_value = import_data.get('system_prompt', '')
        else:
            legacy_history = import_data
            system_prompt_value = ''
        
        chat_history = []
        # Convert tuple/pair format to messages format
        for pair in legacy_history:
            if pair[0]:  # User message
                if isinstance(pair[0], dict) and 'file' in pair[0]:
                    if 'data' in pair[0]['file']:
                        # Legacy format with embedded data
                        file_data = pair[0]['file']['data']
                        mime_type = file_data.split(';')[0].split(':')[1]
                        
                        if mime_type.startswith('image/'):
                            image_data = base64.b64decode(file_data.split(',')[1])
                            img = Image.open(io.BytesIO(image_data))
                            chat_history.append({
                                "role": "user",
                                "content": gr.Image(value=img)
                            })
                        else:
                            fname = pair[0]['file'].get('name', 'download')
                            dir_path = os.path.dirname(file.name)
                            temp_path = os.path.join(dir_path, fname)
                            file_data = base64.b64decode(file_data.split(',')[1])
                            
                            with open(temp_path, "wb") as tempf:
                                tempf.write(file_data)
                            chat_history.append({
                                "role": "user",
                                "content": gr.File(value=temp_path, 
                                                 label=fname)
                            })
                    else:
                        # Keep as-is but convert to message format
                        chat_history.append({
                            "role": "user",
                            "content": pair[0]
                        })
                else:
                    chat_history.append({
                        "role": "user",
                        "content": pair[0]
                    })
            
            if pair[1]:  # Assistant message
                chat_history.append({
                    "role": "assistant",
                    "content": pair[1]
                })

    return chat_history, system_prompt_value

def get_export_js():
    return """
    async (chat_history, system_prompt) => {
        let messages = [];
        
        if (system_prompt) {
            messages.push({
                "role": "system",
                "content": system_prompt
            });
        }

        async function processFile(file_url) {
            const response = await fetch(file_url);
            const blob = await response.blob();
            return new Promise((resolve) => {
                const reader = new FileReader();
                reader.onloadend = () => resolve({
                    data: reader.result,
                    type: blob.type
                });
                reader.onerror = (error) => resolve(null);
                reader.readAsDataURL(blob);
            });
        }

        for (let message of chat_history) {
            if (!message.role || !message.content) continue;

            if (message.content && typeof message.content === 'object') {
                if (message.content.file) {
                    try {
                        const file_data = await processFile(message.content.file.url);
                        if (!file_data) continue;

                        if (file_data.type.startsWith('image/')) {
                            messages.push({
                                "role": message.role,
                                "content": [{
                                    "type": "image_url",
                                    "image_url": {
                                        "url": file_data.data
                                    }
                                }]
                            });
                        } else {
                            const fileLink = document.querySelector(`a[data-testid="chatbot-file"][download][href*="${message.content.file.url.split('/').pop()}"]`);
                            const fileName = fileLink ? fileLink.getAttribute('download') : (message.content.file.name || "download");
                            
                            messages.push({
                                "role": message.role,
                                "content": [{
                                    "type": "file",
                                    "file": {
                                        "url": file_data.data,
                                        "name": fileName,
                                        "mime_type": file_data.type
                                    }
                                }]
                            });
                        }
                    } catch (error) {}
                }
            } else {
                messages.push({
                    "role": message.role,
                    "content": message.content
                });
            }
        }

        const export_data = { messages };
        const blob = new Blob([JSON.stringify(export_data)], {type: 'application/json'});
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = 'chat_history.json';
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
    }
    """