File size: 6,958 Bytes
a13c2bb
 
c96734b
1ca78b8
 
5e307e7
a13c2bb
c96734b
a13c2bb
 
1ca78b8
cef7f39
 
 
 
 
 
 
 
a13c2bb
1ca78b8
cef7f39
 
 
 
a13c2bb
cef7f39
9144903
cef7f39
 
 
 
9144903
b142a4a
cef7f39
 
 
 
 
 
 
9144903
cef7f39
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9144903
cef7f39
 
 
 
b142a4a
 
 
cef7f39
b142a4a
 
 
 
 
 
 
 
 
cef7f39
 
b142a4a
9144903
1ca78b8
cef7f39
 
 
 
 
 
 
 
 
 
 
 
1ca78b8
cef7f39
b142a4a
cef7f39
 
b142a4a
a13c2bb
cef7f39
 
1ca78b8
b142a4a
cef7f39
 
 
 
a13c2bb
9144903
b142a4a
cef7f39
 
 
 
b142a4a
a13c2bb
cef7f39
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9144903
b142a4a
cef7f39
 
3e6631d
 
cef7f39
 
 
9144903
b142a4a
cef7f39
 
a13c2bb
 
cef7f39
1ca78b8
cef7f39
9144903
3e6631d
 
 
 
 
 
 
 
 
 
 
cef7f39
 
 
 
 
 
 
 
 
 
 
b142a4a
cef7f39
 
 
 
 
 
 
 
 
 
 
b142a4a
cef7f39
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9144903
 
b142a4a
9144903
5e307e7
b142a4a
a13c2bb
9144903
3e6631d
 
 
82deaf2
9144903
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
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", "")

# Simplified 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_response(message, history, model_name, image=None, file=None):
    """Simple function to get response from API"""
    # Find model ID from name
    model_id = next((mid for name, mid in models if name == model_name), models[0][1])
    
    # Format messages from history
    messages = []
    for human, ai in history:
        messages.append({"role": "user", "content": human})
        if ai:  # Only add if there's a response
            messages.append({"role": "assistant", "content": ai})
    
    # Process file if provided
    if file:
        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)}"
    
    # Process image if provided
    if image is not None:
        try:
            # Convert image to base64
            buffered = BytesIO()
            image.save(buffered, format="JPEG")
            base64_image = base64.b64encode(buffered.getvalue()).decode("utf-8")
            
            # Create multimodal content
            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": f"{message}\n\nError processing image: {str(e)}"})
    else:
        messages.append({"role": "user", "content": message})
    
    # Make API call (non-streaming for reliability)
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {OPENROUTER_API_KEY}",
        "HTTP-Referer": "https://huggingface.co/spaces",
    }
    
    data = {
        "model": model_id,
        "messages": messages,
        "temperature": 0.7,
        "max_tokens": 1000
    }
    
    try:
        response = requests.post(
            "https://openrouter.ai/api/v1/chat/completions",
            headers=headers,
            json=data,
            timeout=60
        )
        response.raise_for_status()
        
        result = response.json()
        reply = result.get("choices", [{}])[0].get("message", {}).get("content", "No response")
        
        return reply
    except Exception as e:
        return f"Error: {str(e)}"

# Create ultra simple interface
with gr.Blocks() as demo:
    gr.Markdown("# 🔆 CrispChat")
    
    chatbot = gr.Chatbot(height=450)
    
    with gr.Row():
        with gr.Column(scale=3):
            msg = gr.Textbox(
                placeholder="Type your message here...",
                lines=3,
                label="Message"
            )
        
        with gr.Column(scale=1):
            model = gr.Dropdown(
                choices=[name for name, _ in models],
                value=models[0][0],
                label="Model"
            )
    
    with gr.Row():
        with gr.Column(scale=1):
            img = gr.Image(type="pil", label="Image (optional)")
        
        with gr.Column(scale=1):
            file = gr.File(label="Text File (optional)")
    
    with gr.Row():
        submit = gr.Button("Send")
        clear = gr.Button("Clear")
    
    # Events
    submit.click(
        fn=get_response,
        inputs=[msg, chatbot, model, img, file],
        outputs=chatbot
    ).then(
        lambda: "", None, None,
        outputs=[msg, img, file]
    )
    
    msg.submit(
        fn=get_response,
        inputs=[msg, chatbot, model, img, file],
        outputs=chatbot
    ).then(
        lambda: "", None, None,
        outputs=[msg, img, file]
    )
    
    clear.click(lambda: [], outputs=chatbot)

# Define 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):
    """Simple API endpoint"""
    model_id = request.model or models[0][1]
    
    messages = []
    
    # Process image if provided
    if request.image_data:
        try:
            # Decode base64 image
            image_bytes = base64.b64decode(request.image_data)
            image = Image.open(BytesIO(image_bytes))
            
            # Re-encode to ensure proper format
            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})
    
    # Make API call
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {OPENROUTER_API_KEY}",
        "HTTP-Referer": "https://huggingface.co/spaces",
    }
    
    data = {
        "model": model_id,
        "messages": messages,
        "temperature": 0.7
    }
    
    try:
        response = requests.post(
            "https://openrouter.ai/api/v1/chat/completions",
            headers=headers,
            json=data,
            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 the app
if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=7860)