Sada8888 commited on
Commit
1fa5e24
·
verified ·
1 Parent(s): dd31ab2

Update yml/chat-gemma.py

Browse files
Files changed (1) hide show
  1. yml/chat-gemma.py +23 -102
yml/chat-gemma.py CHANGED
@@ -1,117 +1,38 @@
1
- import os, sys, requests, time, base64
2
- import httpx
3
- from gradio_client import Client
4
-
5
- # =========================================================
6
- # پچ جلوگیری از قطعی ارتباط (Time Out) برای پردازش‌های طولانی
7
- # زمان انتظار روی ۵ دقیقه تنظیم شده است
8
- original_client_init = httpx.Client.__init__
9
- def patched_client_init(self, *args, **kwargs):
10
- kwargs['timeout'] = httpx.Timeout(300.0)
11
- original_client_init(self, *args, **kwargs)
12
- httpx.Client.__init__ = patched_client_init
13
-
14
- original_async_init = httpx.AsyncClient.__init__
15
- def patched_async_init(self, *args, **kwargs):
16
- kwargs['timeout'] = httpx.Timeout(300.0)
17
- original_async_init(self, *args, **kwargs)
18
- httpx.AsyncClient.__init__ = patched_async_init
19
- # =========================================================
20
 
21
  prompt = os.environ.get('PROMPT', '')
22
  file_url = os.environ.get('FILE_URL', '')
23
  run_id = os.environ.get('RUN_ID')
24
- space_url = os.environ.get('SPACE_URL')
25
- gh_run_id = os.environ.get('GITHUB_RUN_ID')
26
-
27
- files_to_send = []
28
 
29
- # ۱. دانلود تصویر و تبدیل قطعی آن به Base64 Data URI (دقیقاً مشابه روش Qwen)
30
- if file_url and file_url.strip():
31
- print(f'Downloading attachment for Base64 conversion: {file_url}')
32
- try:
33
- req = requests.get(file_url, timeout=30)
34
- ext = file_url.split('.')[-1] if '.' in file_url else 'bin'
35
- local_filename = f'attachment.{ext}'
36
-
37
- with open(local_filename, 'wb') as f:
38
- f.write(req.content)
39
-
40
- # تبدیل فایل به رشته Base64
41
- with open(local_filename, "rb") as img_file:
42
- encoded_string = base64.b64encode(img_file.read()).decode('utf-8')
43
-
44
- # تشخیص حدودی نوع فایل برای هدر
45
- mime_type = "application/octet-stream"
46
- if ext.lower() in ['png', 'jpg', 'jpeg', 'webp']:
47
- mime_type = f"image/{ext.lower()}"
48
- elif ext.lower() in ['mp4', 'mov', 'avi', 'webm']:
49
- mime_type = f"video/{ext.lower()}"
50
- elif ext.lower() in ['wav', 'mp3', 'ogg', 'flac']:
51
- mime_type = f"audio/{ext.lower()}"
52
-
53
- base64_data_uri = f"data:{mime_type};base64,{encoded_string}"
54
-
55
- # ارسال مستقیم رشته متنی بیس۶۴ به عنوان فایل (بدون استفاده از آبجکت دیکشنری)
56
- files_to_send.append(base64_data_uri)
57
- print(' -> Base64 payload generated successfully.')
58
- except Exception as e:
59
- print(f'Failed to process file: {e}')
60
 
61
- print('Connecting to Gemma-4 Space...')
62
- bot_reply = ''
 
 
 
63
 
64
  try:
65
- # ۲. اتصال به اسپیس هدف شما
66
- client = Client('opera8/gemma-4-e4b-it')
 
67
 
68
- # ۳. اجرای متد Predict (ارسال پیام به همراه آرایه متنی تصاویر)
69
- result = client.predict(
70
- message={'text': prompt, 'files': files_to_send},
71
- thinking=False,
72
- max_new_tokens=2000,
73
- max_soft_tokens=280,
74
- system_prompt='شما یک دستیار هوش مصنوعی بسیار باهوش و مودب به زبان فارسی هستید.',
75
- api_name='/generate'
76
- )
77
 
78
- # ۴. استخراج پاسخ متنی
79
- bot_reply = result[0] if isinstance(result, (list, tuple)) else result
80
- if isinstance(bot_reply, dict):
81
- bot_reply = bot_reply.get('text', str(bot_reply))
82
-
83
- except Exception as e:
84
- err_str = str(e)
85
- print(f'Generation Error: {err_str}')
86
- if 'quota' in err_str.lower() or '429' in err_str:
87
- bot_reply = '⚠️ ظرفیت پردازش موقتاً پر شده است. لطفاً کمی بعد امتحان کنید.'
88
- else:
89
- bot_reply = f'⚠️ خطای سرور پردازش: {err_str}'
90
-
91
- # بررسی نهایی برای جلوگیری از کرش سیستم در صورت خالی بودن پاسخ
92
- if not bot_reply or str(bot_reply).strip() == '':
93
- bot_reply = "⚠️ پاسخی از سمت سرور دریافت نشد."
94
- else:
95
- bot_reply = str(bot_reply)
96
-
97
- print('Uploading response back to Docker Space...')
98
- try:
99
  with open('response.txt', 'w', encoding='utf-8') as f:
100
  f.write(bot_reply)
101
-
102
- with open('response.txt', 'rb') as f:
103
- res = requests.post(
104
- f'{space_url}/api/webhook/upload',
105
- data={'run_id': run_id, 'github_run_id': gh_run_id, 'ext': 'txt'},
106
- files={'file': f}
107
- )
108
 
109
- if res.status_code == 200:
110
- print('SUCCESS!')
111
- else:
112
- print(f"Upload failed with status {res.status_code}: {res.text}")
113
- sys.exit(1)
114
-
115
  except Exception as e:
116
- print(f"Upload Exception: {e}")
117
  sys.exit(1)
 
1
+ import os, sys, requests, base64
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
 
3
  prompt = os.environ.get('PROMPT', '')
4
  file_url = os.environ.get('FILE_URL', '')
5
  run_id = os.environ.get('RUN_ID')
6
+ space_url = "https://opera8-gemma-4-e4b-it.hf.space" # آدرس مستقیم اسپیس شما
 
 
 
7
 
8
+ image_data = None
9
+ if file_url:
10
+ # دانلود و تبدیل به base64
11
+ img_resp = requests.get(file_url)
12
+ image_data = base64.b64encode(img_resp.content).decode('utf-8')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
 
14
+ payload = {
15
+ "prompt": prompt,
16
+ "image_base64": image_data,
17
+ "system_prompt": "شما یک دستیار هوشمند هستید."
18
+ }
19
 
20
  try:
21
+ # ارسال به FastAPI
22
+ response = requests.post(f"{space_url}/chat", json=payload, timeout=120)
23
+ result = response.json()
24
 
25
+ bot_reply = result.get("response", "⚠️ خطایی رخ داد.")
 
 
 
 
 
 
 
 
26
 
27
+ # آپلود پاسخ به سرور خودتان (Docker Space)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
  with open('response.txt', 'w', encoding='utf-8') as f:
29
  f.write(bot_reply)
 
 
 
 
 
 
 
30
 
31
+ requests.post(
32
+ f"{os.environ.get('SPACE_URL')}/api/webhook/upload",
33
+ data={'run_id': run_id, 'github_run_id': os.environ.get('GITHUB_RUN_ID'), 'ext': 'txt'},
34
+ files={'file': open('response.txt', 'rb')}
35
+ )
 
36
  except Exception as e:
37
+ print(f"Error: {e}")
38
  sys.exit(1)