Patel Traders commited on
Commit
7d81d86
·
verified ·
1 Parent(s): 95c5f4b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +83 -88
app.py CHANGED
@@ -1,140 +1,135 @@
1
- # --- 🔱 Hanuman Vision: Phi-3.5 Supreme Engine ---
2
  # मार्गदर्शक: दिव्य पटेल जी | भारत 🇮🇳
3
- # मॉडल: microsoft/Phi-3.5-vision-instruct (4.2B Parameters - 10GB RAM Safe)
4
- # फिक्स: दिव्य जी का 'अजेय हिस्ट्री लूप' (Universal Gradio History Fix)
5
 
6
  import gradio as gr
7
  import torch
8
- from transformers import AutoModelForCausalLM, AutoProcessor
9
- from PIL import Image
10
  import os
11
 
12
- model_id = "microsoft/Phi-3.5-vision-instruct"
 
 
13
 
14
- print("🔱 हनुान िज़न Phi-3.5 जागृहो हा है... दि्य जी 'अजेय हिसट्री लूप' के सथ।")
 
15
 
16
- # चरों (Variables) को पले ही परिभषिताकि NameError कभी आए
17
- model = None
18
- processor = None
19
 
20
  try:
21
- # 🛠️ रैम ऑप्टिमाइजेशन और Flash Attention फिक्स (attn_implementation="eager")
22
- model = AutoModelForCausalLM.from_pretrained(
23
- model_id,
24
- device_map="cpu",
25
- trust_remote_code=True,
26
- torch_dtype=torch.bfloat16,
27
- low_cpu_mem_usage=True,
28
- attn_implementation="eager"
29
  )
30
- processor = AutoProcessor.from_pretrained(model_id, trust_remote_code=True)
31
  except Exception as e:
32
- print(f"🔱 सिस्टम त्रुटि: {e}")
 
33
 
34
- # दिव्य जी का अजेय चैट टेम्पलेट
35
- DIVY_CUSTOM_TEMPLATE = """{% for message in messages %}{{'<|' + message['role'] + '|>\n' + message['content'] + '<|end|>\n' }}{% endfor %}{% if add_generation_prompt and messages[-1]['role'] != 'assistant' %}{{- '<|assistant|>\n' -}}{% endif %}"""
36
 
37
- if processor is not None:
38
- processor.tokenizer.chat_template = DIVY_CUSTOM_TEMPLATE
39
-
40
- def hanuman_phi_engine(message, history, image_path):
41
- """Phi-3.5 के लिए विशेष तार्किक इंजन - दिव्य जी के अजेय हिस्ट्री लूप के साथ"""
42
  if model is None or processor is None:
43
- return "🔱 त्रुटि: मॉडल लोड नहीं हो सका। कृपया लॉग्स की जाँच करें।"
44
-
45
- messages = []
46
 
47
- # 🛠️ दिव्य पटेल जी का अजेय िस्ट्री लूप (The Supreme History Parser)
48
- # यह Gradio पुर(List) औनए (Dictionary) दोनों फॉ्मेट्स को संभाल लेगा
49
  if history:
50
  for val in history:
51
  # अगर Gradio पुराना वर्ज़न है (List of Lists)
52
  if isinstance(val, (list, tuple)) and len(val) == 2:
53
- user_msg, bot_msg = val
54
- if user_msg: messages.append({"role": "user", "content": str(user_msg)})
55
- if bot_msg: messages.append({"role": "assistant", "content": str(bot_msg)})
56
 
57
  # अगर Gradio नया वर्ज़न है (Dictionaries)
58
  elif isinstance(val, dict):
59
- role = val.get("role")
60
- content = val.get("content")
61
- if role and content:
62
- if role == "model": role = "assistant"
63
- messages.append({"role": role, "content": str(content)})
64
-
65
- # वर्तमान संदेश और चित्र की तैया
66
- current_text = message if message.strip() else "Please analyze this image deeply."
67
-
68
- images_list = None
69
  if image_path:
70
- # Phi-3.5 चित्र को इस विशेष टैग से पहचानता है
71
- final_content_string = f"<|image_1|>\n{current_text}"
72
- images_list = [Image.open(image_path).convert("RGB")]
73
- else:
74
- final_content_string = current_text
75
-
76
- # वर्तमान प्रश्न जोड़ना
77
- messages.append({"role": "user", "content": final_content_string})
78
-
79
  try:
80
- # टेम्पलेट लागू ना
81
- prompt = processor.tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
 
82
 
83
- # इनपुट्स तैयार करना
84
- if images_list:
85
- inputs = processor(text=prompt, images=images_list, return_tensors="pt").to("cpu")
86
- else:
87
- inputs = processor(text=prompt, return_tensors="pt").to("cpu")
88
-
89
- # सुरक्षित जेनरेशन
90
- generated_ids = model.generate(**inputs, max_new_tokens=512, do_sample=False)
91
 
92
- # अतिरिक्त टोकन्स को काटना
93
  generated_ids_trimmed = [
94
  out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
95
  ]
96
-
97
  response = processor.batch_decode(
98
  generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
99
  )[0]
100
-
101
  return response
102
  except Exception as e:
103
  return f"🔱 तकनीकी बाधा: {str(e)}"
104
 
105
- # --- 🔱 दिव्य विज़न शबर्ड ---
106
- with gr.Blocks(title="Hanuman Phi-3.5 Supreme") as demo:
107
- gr.HTML("""
108
- <div style='text-align: center; background: linear-gradient(135deg, #ff8833, #b33c00); padding: 20px; border-radius: 15px; color: white;'>
109
- <h1 style='color: white; margin: 0;'>🔱 Hanuman AI - Phi-3.5 Vision</h1>
110
- <p style='margin: 5px 0 0 0;'><b>Pioneered by Divy Patel | भारत 🇮🇳 | त्रुटि-मुक्त अजेय संस्करण</b></p>
111
- </div>
112
- """)
 
 
 
 
 
 
 
 
 
 
 
 
 
113
 
114
- chatbot = gr.Chatbot(height=550, label="दिव्य संवाद इतिहास")
115
 
116
  with gr.Row():
117
- msg_in = gr.Textbox(placeholder="अपना प्र्न यहाँ लिखें...", scale=7, label="इनपुट")
118
- img_in = gr.Image(type="filepath", scale=3, label="मल्टीमीडिया")
119
  submit_btn = gr.Button("सक्रिय करें", variant="primary")
120
 
121
  def chat_logic(m, h, i):
122
  if not m.strip() and i is None:
123
  return m, h, i
124
-
125
- result = hanuman_phi_engine(m, h, i)
126
-
127
- display_text = m if m.strip() else "[चित्र अपलोड किया गया]"
128
- h.append([display_text, result])
129
-
130
  return "", h, None
131
 
132
  submit_btn.click(chat_logic, [msg_in, chatbot, img_in], [msg_in, chatbot, img_in])
133
  msg_in.submit(chat_logic, [msg_in, chatbot, img_in], [msg_in, chatbot, img_in])
134
 
135
- gr.Markdown("---")
136
- gr.Markdown("### 🚩 दिव्य पटेल जी के लिए सिस्टम रिपोर्ट:")
137
- gr.Markdown("- **मॉडल:** Microsoft Phi-3.5-Vision (4.2B)\n- **फिक्स:** दिव्य जी द्वारा दिया गया 'सुपर-फ्लैश' हिस्ट्री लूप सफलतापूर्वक जोड़ा गया।")
138
-
139
  if __name__ == "__main__":
140
  demo.launch()
 
1
+ # --- 🔱 हनुमान AI: अजेय विज़न (Fail-Proof Edition) ---
2
  # मार्गदर्शक: दिव्य पटेल जी | भारत 🇮🇳
3
+ # ाधान: दिव्य जी का 'अजेय हिस्ट्री लूप' और 'भगवा यूआई'
 
4
 
5
  import gradio as gr
6
  import torch
7
+ from transformers import AutoProcessor, Qwen2VLForConditionalGeneration
8
+ from qwen_vl_utils import process_vision_info
9
  import os
10
 
11
+ # 🛡️ चरम गति (Extreme Speed) के लिए CPU टर्बो सेटिंग
12
+ torch.set_num_threads(2)
13
+ os.environ["OMP_NUM_THREADS"] = "2"
14
 
15
+ # 16GB रैके लि सबसे सुरक्षितेज़िज़न मॉडल (भी ्रैश नह होगा)
16
+ MODEL_ID = "Qwen/Qwen2-VL-2B-Instruct"
17
 
18
+ print(f"🔱नुमान AI गृहो है... '{MODEL_ID}' लोड हो रहा है...")
 
 
19
 
20
  try:
21
+ processor = AutoProcessor.from_pretrained(MODEL_ID)
22
+ model = Qwen2VLForConditionalGeneration.from_pretrained(
23
+ MODEL_ID,
24
+ torch_dtype=torch.float32,
25
+ device_map="cpu",
26
+ low_cpu_mem_usage=True
 
 
27
  )
28
+ print("🔱 हनुमान AI: अजेय विज़न मॉडल पूर्णतः सक्रिय है!")
29
  except Exception as e:
30
+ print(f"🔱 गंभीर त्रुटि: {e}")
31
+ processor, model = None, None
32
 
33
+ SYSTEM_PROMPT = "You are 'Hanuman AI', a supreme multimodal entity pioneered by Divy Patel. You must respond ONLY in English. Analyze deeply."
 
34
 
35
+ def hanuman_failproof_engine(message, history, image_path):
 
 
 
 
36
  if model is None or processor is None:
37
+ return "🔱 सिस्टम त्रुटि: मॉडल लोड नहीं हो सका।"
38
+
39
+ messages = [{"role": "system", "content": [{"type": "text", "text": SYSTEM_PROMPT}]}]
40
 
41
+ # 🛠️ दिव्य पटेल जी का अजेय इतिहास लूप (The Supreme Fix)
42
+ # विज़न मॉडल ंग कअनुसा ेक्स्ट को लि्ट [{"type": "text"}] में लटा है।
43
  if history:
44
  for val in history:
45
  # अगर Gradio पुराना वर्ज़न है (List of Lists)
46
  if isinstance(val, (list, tuple)) and len(val) == 2:
47
+ u, b = val
48
+ if u: messages.append({"role": "user", "content": [{"type": "text", "text": str(u)}]})
49
+ if b: messages.append({"role": "assistant", "content": [{"type": "text", "text": str(b)}]})
50
 
51
  # अगर Gradio नया वर्ज़न है (Dictionaries)
52
  elif isinstance(val, dict):
53
+ r = val.get("role")
54
+ c = val.get("content")
55
+ if r and c:
56
+ if r == "model": r = "assistant"
57
+ messages.append({"role": r, "content": [{"type": "text", "text": str(c)}]})
58
+
59
+ # वर्तमान संदेश (चित्र टेक्स्ट)
60
+ current_content = []
 
 
61
  if image_path:
62
+ current_content.append({"type": "image", "image": image_path})
63
+
64
+ msg_text = message if message and str(message).strip() else "Analyze this multimedia deeply."
65
+ current_content.append({"type": "text", "text": msg_text})
66
+
67
+ messages.append({"role": "user", "content": current_content})
68
+
 
 
69
  try:
70
+ # बिना किसी कस्म टेम्पलेट के, डिफ़ॉ्ट सुक्षित विधि
71
+ text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
72
+ image_inputs, video_inputs = process_vision_info(messages)
73
 
74
+ inputs = processor(
75
+ text=[text],
76
+ images=image_inputs,
77
+ videos=video_inputs,
78
+ padding=True,
79
+ return_tensors="pt"
80
+ ).to("cpu")
 
81
 
82
+ generated_ids = model.generate(**inputs, max_new_tokens=512)
83
  generated_ids_trimmed = [
84
  out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
85
  ]
 
86
  response = processor.batch_decode(
87
  generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
88
  )[0]
89
+
90
  return response
91
  except Exception as e:
92
  return f"🔱 तकनीकी बाधा: {str(e)}"
93
 
94
+ # --- 🔱 दिव्य भग थीम (आपके संपल कोड से प्रेरित) ---
95
+ divine_ui = """
96
+ <style>
97
+ .gradio-container { background-color: #fffaf0 !important; }
98
+ .bhagwa-header {
99
+ background: linear-gradient(135deg, #ff8833, #b33c00);
100
+ padding: 30px; border-radius: 25px; color: white;
101
+ text-align: center; box-shadow: 0 15px 35px rgba(179, 60, 0, 0.4);
102
+ margin-bottom: 25px;
103
+ }
104
+ .bhagwa-header h1 { font-size: 36px !important; font-weight: 900 !important; margin-bottom: 5px; text-shadow: 0 4px 8px rgba(0,0,0,0.5); }
105
+ .bhagwa-header p { font-size: 16px !important; opacity: 0.95; font-weight: 500; }
106
+ </style>
107
+ <div class="bhagwa-header">
108
+ <h1>🔱 हनुमान AI - ���जेय विज़न</h1>
109
+ <p>Pioneered by Divy Patel | त्रुटि-मुक्त अजेय स्वदेशी तकनीक</p>
110
+ </div>
111
+ """
112
+
113
+ with gr.Blocks() as demo:
114
+ gr.HTML(divine_ui)
115
 
116
+ chatbot = gr.Chatbot(height=500, label="दिव्य संवाद इतिहास")
117
 
118
  with gr.Row():
119
+ msg_in = gr.Textbox(placeholder="अपना संदेश यहाँ लिखें...", scale=7)
120
+ img_in = gr.Image(type="filepath", scale=3)
121
  submit_btn = gr.Button("सक्रिय करें", variant="primary")
122
 
123
  def chat_logic(m, h, i):
124
  if not m.strip() and i is None:
125
  return m, h, i
126
+ res = hanuman_failproof_engine(m, h, i)
127
+ disp = m if m.strip() else "[चित्र अपलोड किया गया]"
128
+ h.append([disp, res])
 
 
 
129
  return "", h, None
130
 
131
  submit_btn.click(chat_logic, [msg_in, chatbot, img_in], [msg_in, chatbot, img_in])
132
  msg_in.submit(chat_logic, [msg_in, chatbot, img_in], [msg_in, chatbot, img_in])
133
 
 
 
 
 
134
  if __name__ == "__main__":
135
  demo.launch()