AnesKAM commited on
Commit
98abdb3
·
verified ·
1 Parent(s): 5651a69

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +73 -78
app.py CHANGED
@@ -5,7 +5,7 @@ import json, time, re, io, base64, html, logging
5
  import requests
6
  from urllib.parse import quote_plus
7
 
8
- from g4f.client import Client
9
  from docx import Document
10
  from pptx import Presentation
11
  from openpyxl import Workbook
@@ -23,32 +23,6 @@ except:
23
  logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
24
  logger = logging.getLogger("genisi")
25
 
26
- # ======================== HAR Auth ========================
27
- HAR_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "har_and_cookies")
28
- os.makedirs(HAR_DIR, exist_ok=True)
29
- DEEPSEEK_HAR = os.path.join(HAR_DIR, "deepseek.com.har")
30
-
31
- if not os.path.exists(DEEPSEEK_HAR):
32
- har_data = {
33
- "log": {
34
- "version": "1.2",
35
- "entries": [{
36
- "request": {
37
- "method": "GET",
38
- "url": "https://chat.deepseek.com/api/v0/chat_session",
39
- "headers": [
40
- {"name": "Authorization", "value": "Bearer sk-67e56e7d20bb481982f00421c0a9c2e8"},
41
- {"name": "Content-Type", "value": "application/json"},
42
- {"name": "User-Agent", "value": "Mozilla/5.0"}
43
- ]
44
- }
45
- }]
46
- }
47
- }
48
- with open(DEEPSEEK_HAR, 'w') as f:
49
- json.dump(har_data, f)
50
- logger.info("[auth] HAR file created")
51
-
52
  # ======================== Base ========================
53
  BASE_DIR = os.path.dirname(os.path.abspath(__file__))
54
  TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates')
@@ -59,14 +33,18 @@ CORS(app)
59
  if not os.path.isfile(os.path.join(TEMPLATE_DIR, 'index.html')):
60
  raise RuntimeError("index.html not found in templates/")
61
 
62
- # ======================== API Config ========================
63
- # ✨ DeepSeek Provider + deepseek-v3 Model
64
- GENISI_MODEL = "deepseek-v3"
65
 
66
- # ✨ g4f Client - مباشر بدون custom server
67
- GENISI_CLIENT = Client()
 
68
 
69
- MEDIA_CLIENT = Client()
 
 
 
 
70
  IMAGE_MODEL = "flux"
71
 
72
  CAPS = {
@@ -99,45 +77,68 @@ def health():
99
  'status': 'ok',
100
  'project': 'Genisi AI',
101
  'owner': 'Anes Kameche (أنس كامش)',
102
- 'provider': 'DeepSeek',
103
- 'model': 'deepseek-v3',
104
- 'models': {'flash': 'Genisi Flash 2 ⚡', 'pro': 'Genisi Pro 2 🧠'}
 
 
 
 
105
  })
106
 
107
  # ======================== System Prompts ========================
108
- FLASH_PROMPT = """You are Genisi Flash 2 ⚡ by AnesNT project, owned by Anes Kameche.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
109
 
110
- RULES:
111
- 1. NO THINKING - answer immediately
112
- 2. Same language as user
113
- 3. Short and direct
114
 
115
- TOOLS (one JSON when needed):
116
- - Search: {"tool":"search","query":"..."}
117
- - Image: {"tool":"image","prompt":"..."}
118
- - Document: {"tool":"document","format":"pdf|docx|pptx|xlsx","title":"...","content":{...}}
119
 
120
- END WITH: SUGGESTIONS: ["s1","s2","s3"]"""
121
 
122
- PRO_PROMPT = """You are Genisi Pro 2 🧠 by AnesNT project, owned by Anes Kameche.
123
 
124
- RULES:
125
- 1. Start with "Thinking..." then deep reasoning, blank line, then answer
126
- 2. Comprehensive, Accurate, Structured
127
- 3. NEVER fabricate facts
128
 
129
- TOOLS (one JSON when needed):
130
- - Search: {"tool":"search","query":"..."}
131
- - Image: {"tool":"image","prompt":"..."}
132
- - Document: {"tool":"document","format":"pdf|docx|pptx|xlsx","title":"...","content":{...}}
 
133
 
134
- END WITH: SUGGESTIONS: ["s1","s2","s3"]"""
 
 
135
 
136
  def build_prompt(user, interests, think):
137
- lines = [PRO_PROMPT if think else FLASH_PROMPT]
 
 
 
 
138
  user = user or {}
139
- if user.get('name'): lines.append(f"\nUser: {user['name']}")
140
- if interests: lines.append(f"Interests: {', '.join(interests[:10])}")
 
 
 
141
  return "\n".join(lines)
142
 
143
  # ======================== Helpers ========================
@@ -153,10 +154,6 @@ def normalize_messages(messages):
153
  for m in messages[-20:]:
154
  role = m.get('role')
155
  content = m.get('content', '') or ''
156
- atts = m.get('attachments') or []
157
- if atts:
158
- extra = "\n\n".join(f"[File: {a.get('name','')}]\n{(a.get('text') or '')[:8000]}" for a in atts if a.get('kind') != 'image')
159
- content = f"{content}\n\n{extra}" if extra else content
160
  out.append({"role": role, "content": content})
161
  return out
162
 
@@ -231,8 +228,7 @@ def build_pdf(cmd):
231
  buf = io.BytesIO()
232
  doc = SimpleDocTemplate(buf, pagesize=A4)
233
  styles = getSampleStyleSheet(); story = []
234
- story.append(Paragraph(cmd.get('title', 'Document'), styles['Title']))
235
- story.append(Spacer(1, 12))
236
  c = cmd.get('content', {}) or {}
237
  if c.get('heading'): story.append(Paragraph(c['heading'], styles['Heading1']))
238
  for p in c.get('paragraphs', []): story.append(Paragraph(as_text(p), styles['Normal']))
@@ -307,14 +303,9 @@ def chat():
307
  full = ""
308
  try:
309
  name = "Genisi Pro 2 🧠" if think else "Genisi Flash 2 ⚡"
310
- logger.info(f"[chat] {name} | DeepSeek/deepseek-v3")
311
 
312
- # ✨ استدعاء DeepSeek مباشر
313
- response = GENISI_CLIENT.chat.completions.create(
314
- model=GENISI_MODEL,
315
- messages=full_msgs,
316
- stream=True
317
- )
318
 
319
  for chunk in response:
320
  delta = getattr(chunk.choices[0].delta, 'content', None)
@@ -335,7 +326,7 @@ def chat():
335
 
336
  except Exception as e:
337
  logger.error(f"[chat] {e}")
338
- yield f"data: {json.dumps({'error': str(e)[:300]})}\n\n"
339
  yield f"data: {json.dumps({'done': True})}\n\n"
340
 
341
  return Response(stream_with_context(generate()), mimetype='text/event-stream')
@@ -348,11 +339,11 @@ def title():
348
  try:
349
  data = _safe_json()
350
  convo = "\n".join(f"{m.get('role')}: {(m.get('content') or '')[:300]}" for m in data.get('messages', [])[:4])
351
- resp = GENISI_CLIENT.chat.completions.create(model=GENISI_MODEL, messages=[{"role": "user", "content": f"Short title (max 5 words):\n{convo}"}], stream=False)
352
  txt = (resp.choices[0].message.content or "").strip().strip('"').split("\n")[0][:60]
353
  return jsonify({'title': txt or None})
354
  except Exception as e:
355
- return jsonify({'title': None, 'error': str(e)})
356
 
357
  @app.route('/api/upload', methods=['POST'])
358
  def upload():
@@ -424,9 +415,13 @@ def nf(e): return jsonify({'error': 'Not found'}), 404
424
 
425
  if __name__ == '__main__':
426
  port = int(os.environ.get('PORT', 7860))
427
- logger.info("=" * 50)
428
- logger.info(" 🤖 Genisi AI | DeepSeek/deepseek-v3")
429
  logger.info(" Owner: Anes Kameche (أنس كامش)")
 
 
 
 
430
  logger.info(f" Port: {port}")
431
- logger.info("=" * 50)
432
  app.run(host='0.0.0.0', port=port, threaded=True)
 
5
  import requests
6
  from urllib.parse import quote_plus
7
 
8
+ from g4f.client import ClientFactory
9
  from docx import Document
10
  from pptx import Presentation
11
  from openpyxl import Workbook
 
23
  logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
24
  logger = logging.getLogger("genisi")
25
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
  # ======================== Base ========================
27
  BASE_DIR = os.path.dirname(os.path.abspath(__file__))
28
  TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates')
 
33
  if not os.path.isfile(os.path.join(TEMPLATE_DIR, 'index.html')):
34
  raise RuntimeError("index.html not found in templates/")
35
 
36
+ # ======================== API Configuration ========================
37
+ G4F_API_KEY = "g4f_u_mr2i6a_d57da5201b897515fe32b881e8c579440a6dbe70df88f574_da069b53"
 
38
 
39
+ # ✨ Gemma Provider
40
+ GEMMA_PROVIDER = "custom:srv_mrgy0nmbc8a86c407f17"
41
+ GEMMA_MODEL = "models/gemma-4-31b-it"
42
 
43
+ # عميل Gemma
44
+ GEMMA_CLIENT = ClientFactory.create_client(GEMMA_PROVIDER, api_key=G4F_API_KEY)
45
+
46
+ # وسائط
47
+ MEDIA_CLIENT = ClientFactory.create_client("custom:srv_mp5miql908c8738d71be", api_key=G4F_API_KEY)
48
  IMAGE_MODEL = "flux"
49
 
50
  CAPS = {
 
77
  'status': 'ok',
78
  'project': 'Genisi AI',
79
  'owner': 'Anes Kameche (أنس كامش)',
80
+ 'developer': 'AnesNT Project',
81
+ 'provider': f'Gemma ({GEMMA_PROVIDER})',
82
+ 'model': GEMMA_MODEL,
83
+ 'models': {
84
+ 'flash': 'Genisi Flash 2 ⚡ - Gemma 4 31B',
85
+ 'pro': 'Genisi Pro 2 🧠 - Gemma 4 31B (Deep Thinking)'
86
+ }
87
  })
88
 
89
  # ======================== System Prompts ========================
90
+ FLASH_PROMPT = """You are Genisi Flash 2 ⚡, a fast and direct AI assistant powered by Gemma 4, developed by the AnesNT project, owned by Anes Kameche (أنس كامش).
91
+
92
+ CRITICAL RULES:
93
+ 1. NO THINKING - ANSWER IMMEDIATELY. Never start with "Thinking..." or any reasoning.
94
+ 2. Answer in the SAME language the user writes in.
95
+ 3. Keep responses SHORT and DIRECT.
96
+ 4. Use simple, clear language.
97
+
98
+ TOOLS (output ONE JSON object when user explicitly requests):
99
+ - Web search: {"tool":"search","query":"search terms"}
100
+ - Image search: {"tool":"image_search","query":"search terms"}
101
+ - Image generation: {"tool":"image","prompt":"detailed English description"}
102
+ - Document: {"tool":"document","format":"pdf|docx|pptx|xlsx","title":"Document title","content":{...}}
103
+
104
+ END EVERY RESPONSE WITH:
105
+ SUGGESTIONS: ["suggestion 1","suggestion 2","suggestion 3"]
106
+ (2-4 short follow-up prompts in the user's language)"""
107
+
108
+ PRO_PROMPT = """You are Genisi Pro 2 🧠, a highly analytical and precise AI assistant powered by Gemma 4 31B, developed by the AnesNT project, owned by Anes Kameche (أنس كامش).
109
 
110
+ CRITICAL RULES:
 
 
 
111
 
112
+ 1. MANDATORY DEEP THINKING: Start EVERY response with "Thinking..." then your complete internal reasoning. After reasoning, add a blank line, then your final answer.
 
 
 
113
 
114
+ 2. ANSWER MUST BE: Comprehensive, Accurate, Structured, Informative, Honest, Balanced, Actionable.
115
 
116
+ 3. NEVER fabricate facts. ALWAYS verify before stating. Use web search for real-time info.
117
 
118
+ 4. Use professional formatting: ## headings, **bold**, bullet points, tables.
 
 
 
119
 
120
+ 5. TOOLS (output ONE JSON object when needed):
121
+ - Web search: {"tool":"search","query":"search terms"}
122
+ - Image search: {"tool":"image_search","query":"search terms"}
123
+ - Image generation: {"tool":"image","prompt":"detailed English description"}
124
+ - Document: {"tool":"document","format":"pdf|docx|pptx|xlsx","title":"Document title","content":{...}}
125
 
126
+ END EVERY RESPONSE WITH:
127
+ SUGGESTIONS: ["suggestion 1","suggestion 2","suggestion 3"]
128
+ (2-4 insightful follow-up prompts in the user's language)"""
129
 
130
  def build_prompt(user, interests, think):
131
+ if think:
132
+ lines = [PRO_PROMPT]
133
+ else:
134
+ lines = [FLASH_PROMPT]
135
+
136
  user = user or {}
137
+ if user.get('name'):
138
+ lines.append(f"\nCurrent user: {user['name']}")
139
+ if interests:
140
+ lines.append(f"User interests: {', '.join(interests[:10])}")
141
+
142
  return "\n".join(lines)
143
 
144
  # ======================== Helpers ========================
 
154
  for m in messages[-20:]:
155
  role = m.get('role')
156
  content = m.get('content', '') or ''
 
 
 
 
157
  out.append({"role": role, "content": content})
158
  return out
159
 
 
228
  buf = io.BytesIO()
229
  doc = SimpleDocTemplate(buf, pagesize=A4)
230
  styles = getSampleStyleSheet(); story = []
231
+ story.append(Paragraph(cmd.get('title', 'Document'), styles['Title'])); story.append(Spacer(1, 12))
 
232
  c = cmd.get('content', {}) or {}
233
  if c.get('heading'): story.append(Paragraph(c['heading'], styles['Heading1']))
234
  for p in c.get('paragraphs', []): story.append(Paragraph(as_text(p), styles['Normal']))
 
303
  full = ""
304
  try:
305
  name = "Genisi Pro 2 🧠" if think else "Genisi Flash 2 ⚡"
306
+ logger.info(f"[chat] {name} | Gemma 4 31B")
307
 
308
+ response = GEMMA_CLIENT.chat.completions.create(model=GEMMA_MODEL, messages=full_msgs, stream=True)
 
 
 
 
 
309
 
310
  for chunk in response:
311
  delta = getattr(chunk.choices[0].delta, 'content', None)
 
326
 
327
  except Exception as e:
328
  logger.error(f"[chat] {e}")
329
+ yield f"data: {json.dumps({'error': f'Error: {str(e)[:200]}'})}\n\n"
330
  yield f"data: {json.dumps({'done': True})}\n\n"
331
 
332
  return Response(stream_with_context(generate()), mimetype='text/event-stream')
 
339
  try:
340
  data = _safe_json()
341
  convo = "\n".join(f"{m.get('role')}: {(m.get('content') or '')[:300]}" for m in data.get('messages', [])[:4])
342
+ resp = GEMMA_CLIENT.chat.completions.create(model=GEMMA_MODEL, messages=[{"role": "user", "content": f"Short title (max 5 words):\n{convo}"}], stream=False)
343
  txt = (resp.choices[0].message.content or "").strip().strip('"').split("\n")[0][:60]
344
  return jsonify({'title': txt or None})
345
  except Exception as e:
346
+ return jsonify({'title': None})
347
 
348
  @app.route('/api/upload', methods=['POST'])
349
  def upload():
 
415
 
416
  if __name__ == '__main__':
417
  port = int(os.environ.get('PORT', 7860))
418
+ logger.info("=" * 55)
419
+ logger.info(" 🤖 Genisi AI Server")
420
  logger.info(" Owner: Anes Kameche (أنس كامش)")
421
+ logger.info(" Developer: AnesNT Project")
422
+ logger.info(f" Provider: Gemma ({GEMMA_PROVIDER})")
423
+ logger.info(f" Model: {GEMMA_MODEL}")
424
+ logger.info(" Flash ⚡ | Pro 🧠 (Deep Thinking)")
425
  logger.info(f" Port: {port}")
426
+ logger.info("=" * 55)
427
  app.run(host='0.0.0.0', port=port, threaded=True)