File size: 7,711 Bytes
34a5595
4af552f
950275b
 
 
 
7b93499
4af552f
950275b
 
 
600d2ee
950275b
 
 
 
 
 
 
 
 
 
 
dc9f850
950275b
 
 
dc9f850
950275b
 
4af552f
950275b
 
4af552f
 
950275b
 
 
 
 
4c8d986
950275b
 
 
 
4c8d986
 
950275b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4c8d986
950275b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4c8d986
af43245
950275b
 
 
 
 
 
 
7b93499
950275b
7b93499
950275b
 
 
 
 
4c8d986
950275b
 
 
 
 
af43245
 
950275b
 
 
 
 
7b93499
af43245
 
950275b
 
 
 
 
 
 
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
import os
import json
from pathlib import Path

import requests
from flask import Flask, request, jsonify, send_from_directory, Response
from openai import OpenAI

BASE_DIR = Path(__file__).resolve().parent
app = Flask(__name__, static_folder=str(BASE_DIR))

AIHUBMIX_API_KEY = os.environ.get("AIHUBMIX_API_KEY", "sk-I1toL3Pvlk42DKd36d1824Cd683b44Ec834730C17cC39679")

AIHUBMIX_BASE_URL = "https://aihubmix.com/v1"

# النماذج التي اخترناها للمشروع
MODELS = {
    "flash_lite": {
        "name": "Genisi 4 Flash Lite",
        "id": "gpt-4.1-nano-free",
    },
    "flash": {
        "name": "Genisi 4 Flash",
        "id": "gemma-4-26b-a4b-it-free",
    },
    "pro": {
        "name": "Genisi 4 Pro",
        "id": "mimo-v2-flash-free",
    },
}

# API توليد الصور
IMAGE_API_URL = "https://prexzyapis.com/ai/aiappgen"


def get_client():
    if not AIHUBMIX_API_KEY:
        raise RuntimeError(
            "لم يتم العثور على AIHUBMIX_API_KEY في Environment Variables."
        )

    return OpenAI(
        api_key=AIHUBMIX_API_KEY,
        base_url=AIHUBMIX_BASE_URL,
    )


@app.get("/")
def index():
    return send_from_directory(BASE_DIR, "index.html")


@app.get("/api/models")
def models():
    return jsonify({
        "success": True,
        "models": MODELS
    })


@app.post("/api/chat")
def chat():
    try:
        data = request.get_json(silent=True) or {}

        messages = data.get("messages", [])
        model_key = data.get("model", "flash")
        thinking = bool(data.get("thinking", False))

        if not isinstance(messages, list) or not messages:
            return jsonify({
                "success": False,
                "error": "messages يجب أن تكون قائمة غير فارغة."
            }), 400

        if model_key not in MODELS:
            return jsonify({
                "success": False,
                "error": "النموذج غير موجود."
            }), 400

        model_id = MODELS[model_key]["id"]

        # زر التفكير اختياري.
        # لا نرسل parameter خاص بالتفكير للنماذج التي قد لا تدعمه.
        # بدلاً من ذلك نضيف توجيهاً بسيطاً عند تفعيله.
        final_messages = list(messages)

        if thinking:
            final_messages.insert(0, {
                "role": "system",
                "content": (
                    "عند تفعيل وضع التفكير، حلّل المشكلة داخلياً بعناية "
                    "وتحقق من خطواتك قبل إعطاء الإجابة النهائية. "
                    "لا تعرض سلسلة التفكير الداخلية التفصيلية."
                )
            })

        client = get_client()

        response = client.chat.completions.create(
            model=model_id,
            messages=final_messages,
            max_tokens=16384,
            stream=False,
        )

        text = ""

        if response.choices:
            message = response.choices[0].message
            text = message.content or ""

        return jsonify({
            "success": True,
            "model": model_id,
            "text": text
        })

    except Exception as e:
        return jsonify({
            "success": False,
            "error": str(e)
        }), 500


@app.post("/api/chat/stream")
def chat_stream():
    try:
        data = request.get_json(silent=True) or {}

        messages = data.get("messages", [])
        model_key = data.get("model", "flash")
        thinking = bool(data.get("thinking", False))

        if model_key not in MODELS:
            return jsonify({
                "success": False,
                "error": "النموذج غير موجود."
            }), 400

        if not isinstance(messages, list) or not messages:
            return jsonify({
                "success": False,
                "error": "messages غير صالحة."
            }), 400

        final_messages = list(messages)

        if thinking:
            final_messages.insert(0, {
                "role": "system",
                "content": (
                    "فكر بعناية داخلياً قبل الإجابة، خصوصاً في الرياضيات "
                    "والبرمجة والمشاريع المعقدة. لا تعرض سلسلة التفكير الداخلية."
                )
            })

        client = get_client()

        def generate():
            try:
                stream = client.chat.completions.create(
                    model=MODELS[model_key]["id"],
                    messages=final_messages,
                    max_tokens=16384,
                    stream=True,
                )

                for chunk in stream:
                    if not chunk.choices:
                        continue

                    delta = chunk.choices[0].delta

                    if delta and delta.content:
                        payload = {
                            "type": "text",
                            "text": delta.content
                        }

                        yield (
                            "data: "
                            + json.dumps(payload, ensure_ascii=False)
                            + "\n\n"
                        )

                yield 'data: {"type":"done"}\n\n'

            except Exception as e:
                payload = {
                    "type": "error",
                    "error": str(e)
                }

                yield (
                    "data: "
                    + json.dumps(payload, ensure_ascii=False)
                    + "\n\n"
                )

        return Response(
            generate(),
            mimetype="text/event-stream",
            headers={
                "Cache-Control": "no-cache",
                "X-Accel-Buffering": "no",
                "Connection": "keep-alive",
            },
        )

    except Exception as e:
        return jsonify({
            "success": False,
            "error": str(e)
        }), 500


@app.get("/api/image")
def image_generation():
    """
    مثال:
    /api/image?prompt=a%20beautiful%20city&style=realistic
    """

    try:
        prompt = request.args.get("prompt", "").strip()
        image = request.args.get("image", "")
        style = request.args.get("style", "")

        if not prompt:
            return jsonify({
                "success": False,
                "error": "أدخل وصف الصورة."
            }), 400

        params = {
            "prompt": prompt,
            "image": image,
            "style": style,
        }

        response = requests.get(
            IMAGE_API_URL,
            params=params,
            timeout=120,
        )

        try:
            result = response.json()
        except Exception:
            return jsonify({
                "success": False,
                "error": "الخادم أعاد استجابة غير JSON.",
                "raw": response.text
            }), response.status_code

        return jsonify(result), response.status_code

    except requests.RequestException as e:
        return jsonify({
            "success": False,
            "error": f"Image API error: {str(e)}"
        }), 502

    except Exception as e:
        return jsonify({
            "success": False,
            "error": str(e)
        }), 500


@app.get("/health")
def health():
    return jsonify({
        "status": "ok"
    })


if __name__ == "__main__":
    port = int(os.environ.get("PORT", "7860"))

    app.run(
        host="0.0.0.0",
        port=port,
        debug=False,
    )