File size: 11,139 Bytes
a13c2bb
 
c96734b
1ca78b8
 
5e307e7
a13c2bb
5e307e7
c96734b
a13c2bb
 
1ca78b8
b142a4a
a13c2bb
b142a4a
 
 
 
 
 
 
 
a13c2bb
1ca78b8
9144903
a13c2bb
 
 
5e307e7
a13c2bb
 
3e6631d
 
 
 
 
 
 
 
b142a4a
 
 
 
 
a13c2bb
b142a4a
9144903
b142a4a
 
 
9144903
 
 
b142a4a
9144903
 
b142a4a
9144903
b142a4a
9144903
b142a4a
9144903
b142a4a
 
9144903
 
 
 
 
 
 
 
b142a4a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9144903
 
b142a4a
9144903
1ca78b8
b142a4a
 
 
 
 
 
 
 
 
 
 
5e307e7
b142a4a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e6631d
b142a4a
 
3e6631d
 
9144903
 
b142a4a
3e6631d
b142a4a
1ca78b8
5e307e7
b142a4a
3e6631d
1ca78b8
b142a4a
 
 
 
 
 
 
 
 
 
 
a13c2bb
1ca78b8
b142a4a
a13c2bb
9144903
b142a4a
a13c2bb
 
b142a4a
a13c2bb
 
b142a4a
9144903
 
b142a4a
 
9144903
 
b142a4a
9144903
 
b142a4a
9144903
 
b142a4a
9144903
b142a4a
9144903
3e6631d
b142a4a
 
9144903
b142a4a
9144903
b142a4a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a13c2bb
b142a4a
 
 
9144903
 
 
 
 
 
 
 
 
 
 
b142a4a
 
 
3e6631d
 
b142a4a
 
9144903
 
 
 
 
 
 
 
 
 
 
b142a4a
 
 
a13c2bb
 
b142a4a
 
 
 
1ca78b8
 
b142a4a
9144903
3e6631d
 
 
 
 
 
 
 
 
 
 
a13c2bb
 
b142a4a
 
 
 
 
 
 
9144903
3e6631d
9144903
3e6631d
 
b142a4a
 
 
 
 
 
3e6631d
b142a4a
 
 
9144903
 
b142a4a
 
 
 
 
 
 
 
 
 
 
9144903
b142a4a
 
 
 
 
9144903
 
b142a4a
9144903
 
b142a4a
 
9144903
5e307e7
b142a4a
 
a13c2bb
9144903
3e6631d
 
 
82deaf2
9144903
c96734b
9144903
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
import os
import base64
import gradio as gr
import requests
import json
from io import BytesIO
from PIL import Image
import time

# Get API key from environment variable for security
OPENROUTER_API_KEY = os.environ.get("OPENROUTER_API_KEY", "")

# Simplified model information with only name and ID
free_models = [
    ("Google: Gemini Pro 2.0 Experimental", "google/gemini-2.0-pro-exp-02-05:free"),
    ("Google: Gemini 2.0 Flash", "google/gemini-2.0-flash-exp:free"),
    ("Google: Gemini Pro 2.5 Experimental", "google/gemini-2.5-pro-exp-03-25:free"),
    ("Meta: Llama 3.2 11B Vision", "meta-llama/llama-3.2-11b-vision-instruct:free"),
    ("Qwen: Qwen2.5 VL 72B", "qwen/qwen2.5-vl-72b-instruct:free"),
    ("DeepSeek: DeepSeek R1", "deepseek/deepseek-r1:free"),
    ("Meta: Llama 3.1 8B", "meta-llama/llama-3.1-8b-instruct:free"),
    ("Mistral: Mistral Small 3.1 24B", "mistralai/mistral-small-3.1-24b-instruct:free")
]

# Helper functions
def encode_image(image):
    """Convert PIL Image to base64 string"""
    buffered = BytesIO()
    image.save(buffered, format="JPEG")
    return base64.b64encode(buffered.getvalue()).decode("utf-8")

def encode_file(file_path):
    """Convert text file to string"""
    try:
        with open(file_path, 'r', encoding='utf-8') as file:
            return file.read()
    except Exception as e:
        return f"Error reading file: {str(e)}"

def generate_response(message, chat_history, model_name, uploaded_image=None, uploaded_file=None, 
                      temp=0.7, max_tok=1000, use_stream=True):
    """Process message and get response from API"""
    # Find model ID
    model_id = next((model_id for name, model_id in free_models if name == model_name), free_models[0][1])
    
    # Get context from history
    messages = []
    for turn in chat_history:
        if isinstance(turn, tuple):
            user_msg, ai_msg = turn
            messages.append({"role": "user", "content": user_msg})
            messages.append({"role": "assistant", "content": ai_msg})
    
    # Process file if provided
    if uploaded_file:
        file_content = encode_file(uploaded_file)
        message = f"{message}\n\nFile content:\n```\n{file_content}\n```"
    
    # Create new message
    if uploaded_image:
        # Process image for vision models
        base64_image = encode_image(uploaded_image)
        content = [
            {"type": "text", "text": message},
            {
                "type": "image_url",
                "image_url": {
                    "url": f"data:image/jpeg;base64,{base64_image}"
                }
            }
        ]
        messages.append({"role": "user", "content": content})
    else:
        messages.append({"role": "user", "content": message})
    
    # Setup headers and URL
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {OPENROUTER_API_KEY}",
        "HTTP-Referer": "https://huggingface.co/spaces",
    }
    
    url = "https://openrouter.ai/api/v1/chat/completions"
    
    # Build request data
    data = {
        "model": model_id,
        "messages": messages,
        "stream": use_stream,
        "temperature": temp,
        "max_tokens": max_tok
    }
    
    # Add message to chat history
    chat_history.append((message, ""))
    
    try:
        if use_stream:
            # Streaming response
            with requests.post(url, headers=headers, json=data, stream=True) as response:
                response.raise_for_status()
                
                full_response = ""
                buffer = ""
                
                for chunk in response.iter_content(chunk_size=1024, decode_unicode=False):
                    if chunk:
                        buffer += chunk.decode('utf-8')
                        
                        # Process line by line
                        while '\n' in buffer:
                            line, buffer = buffer.split('\n', 1)
                            line = line.strip()
                            
                            if line.startswith('data: '):
                                data = line[6:]
                                if data == '[DONE]':
                                    break
                                    
                                try:
                                    data_obj = json.loads(data)
                                    delta_content = data_obj["choices"][0]["delta"].get("content", "")
                                    if delta_content:
                                        full_response += delta_content
                                        chat_history[-1] = (message, full_response)
                                        yield chat_history
                                except Exception:
                                    pass
                
                # Final yield to ensure complete message
                if full_response:
                    chat_history[-1] = (message, full_response)
                    yield chat_history
                
        else:
            # Non-streaming response
            response = requests.post(url, headers=headers, json=data)
            response.raise_for_status()
            result = response.json()
            
            reply = result.get("choices", [{}])[0].get("message", {}).get("content", "No response")
            chat_history[-1] = (message, reply)
            yield chat_history
                
    except Exception as e:
        error_msg = f"Error: {str(e)}"
        chat_history[-1] = (message, error_msg)
        yield chat_history

def clear_chat():
    """Clear the chat history"""
    return []

def clear_input():
    """Clear the input field"""
    return "", None, None

# Create a very simple UI
with gr.Blocks(theme=gr.themes.Default()) as demo:
    gr.Markdown("# 🔆 CrispChat")
    
    with gr.Row():
        with gr.Column(scale=3):
            chatbot = gr.Chatbot(
                height=500,
                layout="bubble",
                show_copy_button=True,
                show_share_button=False,
                avatar_images=("👤", "🤖")
            )
            
            with gr.Group():
                user_message = gr.Textbox(
                    placeholder="Type your message here...",
                    lines=3,
                    show_label=False
                )
                
                with gr.Row():
                    image_upload = gr.Image(
                        type="pil", 
                        label="Image (optional)",
                        show_label=True
                    )
                    
                    file_upload = gr.File(
                        label="Text File (optional)",
                        file_types=[".txt", ".md", ".py", ".js", ".html", ".css", ".json"]
                    )
                    
                with gr.Row():
                    submit_btn = gr.Button("Send", variant="primary")
                    clear_chat_btn = gr.Button("Clear Chat")
        
        with gr.Column(scale=1):
            model_selector = gr.Dropdown(
                choices=[name for name, _ in free_models],
                value=free_models[0][0],
                label="Select Model"
            )
            
            temperature = gr.Slider(
                minimum=0.1, 
                maximum=2.0, 
                value=0.7, 
                step=0.1, 
                label="Temperature"
            )
            
            max_tokens = gr.Slider(
                minimum=100, 
                maximum=4000, 
                value=1000, 
                step=100, 
                label="Max Tokens"
            )
            
            streaming = gr.Checkbox(
                label="Streaming", 
                value=True
            )
    
    # Set up submit events
    submit_btn.click(
        fn=generate_response,
        inputs=[
            user_message, 
            chatbot, 
            model_selector, 
            image_upload, 
            file_upload,
            temperature,
            max_tokens,
            streaming
        ],
        outputs=chatbot
    ).then(
        fn=clear_input,
        outputs=[user_message, image_upload, file_upload]
    )
    
    user_message.submit(
        fn=generate_response,
        inputs=[
            user_message, 
            chatbot, 
            model_selector, 
            image_upload, 
            file_upload,
            temperature,
            max_tokens,
            streaming
        ],
        outputs=chatbot
    ).then(
        fn=clear_input,
        outputs=[user_message, image_upload, file_upload]
    )
    
    # Clear chat button
    clear_chat_btn.click(
        fn=clear_chat,
        outputs=chatbot
    )

# API for external access
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class GenerateRequest(BaseModel):
    message: str
    model: str = None
    image_data: str = None

@app.post("/api/generate")
async def api_generate(request: GenerateRequest):
    """API endpoint for generating responses"""
    try:
        # Get model ID
        model_id = request.model
        if not model_id:
            model_id = free_models[0][1]
            
        # Process image if provided
        messages = []
        if request.image_data:
            try:
                image_bytes = base64.b64decode(request.image_data)
                image = Image.open(BytesIO(image_bytes))
                base64_image = encode_image(image)
                content = [
                    {"type": "text", "text": request.message},
                    {
                        "type": "image_url",
                        "image_url": {
                            "url": f"data:image/jpeg;base64,{base64_image}"
                        }
                    }
                ]
                messages.append({"role": "user", "content": content})
            except Exception as e:
                return {"error": f"Image processing error: {str(e)}"}
        else:
            messages.append({"role": "user", "content": request.message})
        
        # Setup API call
        headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {OPENROUTER_API_KEY}",
            "HTTP-Referer": "https://huggingface.co/spaces",
        }
        
        url = "https://openrouter.ai/api/v1/chat/completions"
        
        data = {
            "model": model_id,
            "messages": messages,
            "temperature": 0.7
        }
        
        # Make API call
        response = requests.post(url, headers=headers, json=data)
        response.raise_for_status()
        
        # Parse response
        result = response.json()
        reply = result.get("choices", [{}])[0].get("message", {}).get("content", "No response")
        
        return {"response": reply}
    
    except Exception as e:
        return {"error": f"Error: {str(e)}"}

# Mount Gradio app
app = gr.mount_gradio_app(app, demo, path="/")

# Launch the app
if __name__ == "__main__":
    demo.launch()