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

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

# Model list
models = [
    ("Google Gemini Pro 2.0", "google/gemini-2.0-pro-exp-02-05:free"),
    ("Google Gemini 2.5 Pro", "google/gemini-2.5-pro-exp-03-25:free"),
    ("Meta Llama 3.2 Vision", "meta-llama/llama-3.2-11b-vision-instruct:free"),
    ("Qwen 2.5 VL", "qwen/qwen2.5-vl-72b-instruct:free"),
    ("DeepSeek R1", "deepseek/deepseek-r1:free"),
    ("Mistral 3.1", "mistralai/mistral-small-3.1-24b-instruct:free")
]

def get_ai_response(message, history, model_name, image=None, file=None):
    """Get response from AI"""
    # Find model ID
    model_id = next((mid for name, mid in models if name == model_name), models[0][1])
    
    # Prepare messages
    messages = []
    for human, ai in history:
        messages.append({"role": "user", "content": human})
        if ai:
            messages.append({"role": "assistant", "content": ai})
    
    # Handle file
    if file is not None:
        try:
            with open(file.name, 'r', encoding='utf-8') as f:
                file_content = f.read()
                message = f"{message}\n\nFile content:\n```\n{file_content}\n```"
        except Exception as e:
            message = f"{message}\n\nError reading file: {str(e)}"
    
    # Handle image
    if image is not None:
        try:
            buffered = BytesIO()
            image.save(buffered, format="JPEG")
            base64_image = base64.b64encode(buffered.getvalue()).decode("utf-8")
            
            content = [
                {"type": "text", "text": message},
                {
                    "type": "image_url",
                    "image_url": {
                        "url": f"data:image/jpeg;base64,{base64_image}"
                    }
                }
            ]
            messages.append({"role": "user", "content": content})
        except Exception as e:
            messages.append({"role": "user", "content": message})
            return f"Error processing image: {str(e)}"
    else:
        messages.append({"role": "user", "content": message})
    
    # API call
    try:
        response = requests.post(
            "https://openrouter.ai/api/v1/chat/completions",
            headers={
                "Content-Type": "application/json",
                "Authorization": f"Bearer {OPENROUTER_API_KEY}",
                "HTTP-Referer": "https://huggingface.co/spaces",
            },
            json={
                "model": model_id,
                "messages": messages,
                "temperature": 0.7,
                "max_tokens": 1000
            },
            timeout=60
        )
        response.raise_for_status()
        
        result = response.json()
        return result.get("choices", [{}])[0].get("message", {}).get("content", "No response")
    except Exception as e:
        return f"Error: {str(e)}"

def clear_inputs():
    """Clear input fields"""
    return "", None, None

with gr.Blocks() as demo:
    gr.Markdown("# 🔆 CrispChat")
    
    chatbot = gr.Chatbot(
        height=450,
        type="messages"  # Use the new format as suggested in the warning
    )
    
    model_selector = gr.Dropdown(
        choices=[name for name, _ in models],
        value=models[0][0],
        label="Model"
    )
    
    msg_input = gr.Textbox(
        placeholder="Type your message here...",
        lines=3,
        label="Message"
    )
    
    img_input = gr.Image(
        type="pil", 
        label="Image (optional)"
    )
    
    file_input = gr.File(
        label="Text File (optional)"
    )
    
    with gr.Row():
        submit_btn = gr.Button("Send")
        clear_btn = gr.Button("Clear Chat")
    
    # Define clear function
    def clear_chat():
        return []
    
    # Submit function
    def submit_message(message, chat_history, model, image, file):
        if not message and not image and not file:
            return chat_history, "", None, None
        
        response = get_ai_response(message, chat_history, model, image, file)
        chat_history.append((message, response))
        return chat_history, "", None, None
    
    # Set up events
    submit_btn.click(
        fn=submit_message,
        inputs=[msg_input, chatbot, model_selector, img_input, file_input],
        outputs=[chatbot, msg_input, img_input, file_input]
    )
    
    msg_input.submit(
        fn=submit_message,
        inputs=[msg_input, chatbot, model_selector, img_input, file_input],
        outputs=[chatbot, msg_input, img_input, file_input]
    )
    
    clear_btn.click(
        fn=clear_chat,
        outputs=[chatbot]
    )

# FastAPI endpoint
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 text generation"""
    try:
        model_id = request.model or models[0][1]
        
        # Prepare messages
        messages = []
        
        # Handle image
        if request.image_data:
            try:
                # Decode base64 image
                image_bytes = base64.b64decode(request.image_data)
                image = Image.open(BytesIO(image_bytes))
                
                # Re-encode
                buffered = BytesIO()
                image.save(buffered, format="JPEG")
                base64_image = base64.b64encode(buffered.getvalue()).decode("utf-8")
                
                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})
        
        # API call
        response = requests.post(
            "https://openrouter.ai/api/v1/chat/completions",
            headers={
                "Content-Type": "application/json",
                "Authorization": f"Bearer {OPENROUTER_API_KEY}",
                "HTTP-Referer": "https://huggingface.co/spaces",
            },
            json={
                "model": model_id,
                "messages": messages,
                "temperature": 0.7
            },
            timeout=60
        )
        response.raise_for_status()
        
        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
if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=7860)