Spaces:
Runtime error

File size: 6,582 Bytes
105e363
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f52a1ee
 
105e363
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f52a1ee
 
105e363
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import gradio as gr
from openai import OpenAI
import requests
import random

# ============================================
# NEXUS AI - GRADIO 6 COMPATIBLE
# ============================================

api_key = os.getenv("OPENROUTER_API_KEY")

client = OpenAI(
    base_url="https://openrouter.ai/api/v1",
    api_key=api_key
)

SYSTEM_CHAT = """You are Nexus AI, a brilliant friendly personal AI assistant.
Help with anything — questions, planning, analysis, writing, advice.
Be helpful, concise and smart."""

SYSTEM_CODE = """You are Nexus AI Code — an elite software engineer.
Write complete, production-ready, well-commented code.
Always use markdown code blocks with language specified.
Support all languages and frameworks."""

# ============================================
# FUNCTIONS
# ============================================

def generate_response(message, history, system_prompt):
    try:
        if not api_key:
            return "❌ OPENROUTER_API_KEY not found in Hugging Face Secrets."

        history.append({"role": "user", "content": message})
history.append({"role": "assistant", "content": response})

        for item in history:
            messages.append({"role": "user", "content": item[0]})
            messages.append({"role": "assistant", "content": item[1]})

        messages.append({"role": "user", "content": message})

        completion = client.chat.completions.create(
            model="deepseek/deepseek-chat-v3-0324:free",
            messages=messages,
            temperature=0.7,
            max_tokens=2000
        )

        return completion.choices[0].message.content

    except Exception as e:
        return f"❌ Error: {str(e)}"


def chat(message, history):
    if history is None:
        history = []
    if not message.strip():
        return "", history
    response = generate_response(message, history, SYSTEM_CHAT)
    history.append((message, response))
    return "", history


def code_chat(message, history):
    if history is None:
        history = []
    if not message.strip():
        return "", history
    response = generate_response(message, history, SYSTEM_CODE)
    history.append({"role": "user", "content": message})
history.append({"role": "assistant", "content": response})
    return "", history


def generate_image(prompt, style):
    if not prompt.strip():
        return None, "❌ Please describe your image first!"

    style_map = {
        "Default": "",
        "Photo": "photorealistic, DSLR, 8k",
        "Anime": "anime style, studio ghibli",
        "Painting": "oil painting, impressionist",
        "Digital Art": "cinematic digital art, concept art",
        "3D Render": "3d render, octane render, unreal engine",
        "Pixel Art": "pixel art, 16-bit",
        "Cyberpunk": "neon glow, cyberpunk, futuristic"
    }

    style_text = style_map.get(style, "")
    full_prompt = f"{prompt}, {style_text}, high quality, ultra detailed" if style_text else f"{prompt}, high quality, ultra detailed"

    seed = random.randint(0, 9999999)
    url = f"https://image.pollinations.ai/prompt/{requests.utils.quote(full_prompt)}?width=512&height=512&seed={seed}&nologo=true&enhance=true"

    try:
        response = requests.get(url, timeout=30)
        if response.status_code == 200:
            from PIL import Image
            from io import BytesIO
            img = Image.open(BytesIO(response.content))
            return img, "✅ Image generated!"
        else:
            return None, "❌ Failed. Try again!"
    except Exception as e:
        return None, f"❌ Error: {str(e)}"


# ============================================
# CSS
# ============================================

css = """
.gradio-container {
    max-width: 900px !important;
    margin: auto !important;
}
#title {
    text-align: center;
    font-size: 36px;
    font-weight: 800;
    color: #7c3aed;
    margin-bottom: 4px;
}
#subtitle {
    text-align: center;
    color: #94a3b8;
    font-size: 14px;
    margin-bottom: 16px;
}
footer { display: none !important; }
"""

# ============================================
# UI - GRADIO 6 COMPATIBLE
# ============================================

with gr.Blocks() as demo:

    gr.HTML("""
        <div id="title">🤖 Nexus AI</div>
        <div id="subtitle">Your Ultimate AI — Assistant · Coder · Image Generator</div>
    """)

    with gr.Tabs():

        with gr.Tab("💬 Assistant"):
            chat_bot = gr.Chatbot(height=500)
            with gr.Row():
                chat_input = gr.Textbox(
                    placeholder="Ask me anything…",
                    lines=1, scale=8, container=False
                )
                chat_send = gr.Button("➤", scale=1, variant="primary")
            chat_send.click(chat, inputs=[chat_input, chat_bot], outputs=[chat_input, chat_bot])
            chat_input.submit(chat, inputs=[chat_input, chat_bot], outputs=[chat_input, chat_bot])

        with gr.Tab("💻 Coding"):
            code_bot = gr.Chatbot(height=500)
            with gr.Row():
                code_input = gr.Textbox(
                    placeholder="Ask for code in any language…",
                    lines=1, scale=8, container=False
                )
                code_send = gr.Button("➤", scale=1, variant="primary")
            code_send.click(code_chat, inputs=[code_input, code_bot], outputs=[code_input, code_bot])
            code_input.submit(code_chat, inputs=[code_input, code_bot], outputs=[code_input, code_bot])

        with gr.Tab("🎨 Images"):
            with gr.Row():
                img_prompt = gr.Textbox(
                    placeholder="Describe your image…",
                    lines=3, label="Image Description", scale=3
                )
                img_style = gr.Dropdown(
                    choices=["Default", "Photo", "Anime", "Painting", "Digital Art", "3D Render", "Pixel Art", "Cyberpunk"],
                    value="Default", label="Style", scale=1
                )
            img_btn = gr.Button("✨ Generate Image — Free!", variant="primary")
            with gr.Row():
                img_output = gr.Image(label="Generated Image", scale=2)
                img_status = gr.Textbox(label="Status", scale=1, interactive=False)
            img_btn.click(generate_image, inputs=[img_prompt, img_style], outputs=[img_output, img_status])

# ============================================
# LAUNCH - css and theme go here in Gradio 6
# ============================================

demo.launch(
    css=css,
    theme=gr.themes.Soft()
)