sohiebwedyan commited on
Commit
e57e114
·
verified ·
1 Parent(s): 7d1ffa9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +123 -74
app.py CHANGED
@@ -5,24 +5,32 @@ import gradio as gr
5
  import asyncio
6
  import ipaddress
7
  from typing import Tuple
 
8
 
9
- # تعيين المتغيرات البيئية لتهيئة PyTorch لاستخدام الـ GPU إذا كان متاحًا
10
  os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "expandable_segments:True"
11
 
12
- # الحصول على التوكن من البيئة
13
- token = os.getenv("HF_TOKEN")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
 
15
- # إعداد الأنابيب للموديلات المختلفة باستخدام PyTorch
16
- device = 0 if torch.cuda.is_available() else -1
17
- Najeb_pipeline = pipeline("text-generation", model="sohiebwedyan/NAJEB_BOT", token=token, device=device)
18
- #gpt2_pipeline = pipeline("text-generation", model="Qwen/Qwen-1_8B-Chat", device=device, trust_remote_code=True)
19
- gpt2_pipeline = pipeline("text-generation", model="Harikrishnan46624/finetuned_llama2-1.1b-chat", device=device)
20
- summarization_pipeline = pipeline("summarization", model="Falconsai/text_summarization", device=device)
21
 
22
  previous_questions = []
23
 
24
 
25
- # توليد الردود باستخدام GPT-2
26
  async def generate_gpt2(question, max_length, num_beams, temperature):
27
  return gpt2_pipeline(
28
  question,
@@ -30,12 +38,11 @@ async def generate_gpt2(question, max_length, num_beams, temperature):
30
  num_return_sequences=1,
31
  num_beams=num_beams,
32
  do_sample=True,
33
- top_k=50,
34
- top_p=0.95,
35
  temperature=temperature
36
  )[0]['generated_text']
37
 
38
- # توليد الردود باستخدام Najeb
39
  async def generate_Najeb(question, max_length, num_beams, temperature):
40
  return Najeb_pipeline(
41
  question,
@@ -47,9 +54,7 @@ async def generate_Najeb(question, max_length, num_beams, temperature):
47
  top_p=0.85,
48
  temperature=temperature
49
  )[0]['generated_text']
50
-
51
- '''
52
- # توليد الردود باستخدام LLaMA 2
53
  async def generate_llama2(question, max_length, num_beams, temperature):
54
  return llama2_pipeline(
55
  question,
@@ -57,51 +62,44 @@ async def generate_llama2(question, max_length, num_beams, temperature):
57
  num_return_sequences=1,
58
  num_beams=num_beams,
59
  do_sample=True,
60
- top_k=50,
61
- top_p=0.95,
62
  temperature=temperature
63
- )[0]['generated_text']'''
 
64
 
65
- # التعامل مع الردود بشكل غير متزامن
66
  async def generate_responses_async(question, max_length=128, num_beams=2, temperature=0.5):
 
 
 
67
  previous_questions.append(question)
68
 
69
- # إنشاء المهام بشكل غير متزامن لتوليد الردود من الموديلات المختلفة
70
  gpt2_task = asyncio.create_task(generate_gpt2(question, max_length, num_beams, temperature))
71
  Najeb_task = asyncio.create_task(generate_Najeb(question, max_length, num_beams, temperature))
72
- #llama2_task = asyncio.create_task(generate_llama2(question, max_length, num_beams, temperature))
 
 
 
 
 
 
 
 
 
73
 
74
- # تجميع الردود من جميع الموديلات
75
- gpt2_response, Najeb_response = await asyncio.gather(gpt2_task, Najeb_task, llama2_task)
76
 
77
- # دمج الردود و تلخيصها
78
- combined_responses = f"GPT-2: {gpt2_response}\nNajeb: {Najeb_response}"
79
  summarized_response = summarization_pipeline(combined_responses, max_length=150, min_length=50, do_sample=False)[0]['summary_text']
80
 
81
  return {
82
- "GPT-2 Answer": gpt2_response,
83
- "Najeb Answer": Najeb_response,
84
- #"LLaMA 2 Answer": llama2_response,
85
- "Summarized Answer": summarized_response,
 
86
  "Previous Questions": "\n".join(previous_questions[-5:])
87
  }
88
 
89
- # تحديد طريقة الحساب بناءً على المدخل
90
- def handle_mode_selection(mode, input_text, max_length, num_beams, temperature):
91
- if mode == "AI Question Answering":
92
- result = asyncio.run(generate_responses_async(input_text, max_length, num_beams, temperature))
93
- return (
94
- f"**GPT-2 Model Response:**\n{result['GPT-2 Answer']}",
95
- f"**Najeb Model Response:**\n{result['Najeb Answer']}",
96
- #f"**LLaMA 2 Model Response:**\n{result['LLaMA 2 Answer']}",
97
- f"**Summarized Response:**\n{result['Summarized Answer']}",
98
- f"**Previous Questions:**\n{result['Previous Questions']}"
99
- )
100
- else:
101
- subnet_result = calculate_subnet(input_text)
102
- return subnet_result, "", "", "", ""
103
 
104
- # الحصول على الشبكة وعنوان الـ IP
105
  def get_network(ip_input: str) -> Tuple[ipaddress.IPv4Network, str]:
106
  try:
107
  if ip_input.count("/") == 0:
@@ -112,18 +110,19 @@ def get_network(ip_input: str) -> Tuple[ipaddress.IPv4Network, str]:
112
  except ValueError:
113
  return None, None
114
 
115
- # حساب الشبكة الفرعية
116
  def calculate_subnet(ip_input: str) -> str:
117
  network, ip = get_network(ip_input)
118
  if network is None or ip is None:
119
  return "Invalid IP Address or Subnet!"
120
 
 
121
  network_address = network.network_address
122
  broadcast_address = network.broadcast_address
123
  usable_hosts = list(network.hosts())
124
  num_usable_hosts = len(usable_hosts)
125
  usable_hosts_range = f"{usable_hosts[0]} - {usable_hosts[-1]}" if usable_hosts else "NA"
126
 
 
127
  octets = str(ip).split('.')
128
  binary_octets = [bin(int(octet))[2:].zfill(8) for octet in octets]
129
  bin_ip = '.'.join(binary_octets)
@@ -134,6 +133,7 @@ def calculate_subnet(ip_input: str) -> str:
134
  bin_mask = str(bin(int(network.netmask))[2:].zfill(32))
135
  bin_mask = '.'.join([bin_mask[i:i+8] for i in range(0, len(bin_mask), 8)])
136
 
 
137
  result = f"""
138
  IP Address: {ip}
139
  Address (bin): {bin_ip}
@@ -151,7 +151,17 @@ Private IP: {network.is_private}
151
  """
152
  return result.strip()
153
 
154
- # تحديد التصميم المخصص
 
 
 
 
 
 
 
 
 
 
155
  custom_css = """
156
  body {
157
  background-color: #f0f8ff;
@@ -211,46 +221,85 @@ p {
211
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
212
  }
213
 
 
214
  #image-container {
215
  text-align: center;
216
  position: relative;
217
  }
218
 
219
  #image-container img {
220
- width: 100%;
221
- max-width: 500px;
222
- margin-bottom: 10px;
223
  }
224
 
225
  #image-container button {
226
  position: absolute;
227
- top: 10px;
228
- left: 10px;
229
- background-color: rgba(0, 0, 0, 0.5);
 
230
  color: white;
231
  border: none;
232
- padding: 5px 10px;
 
233
  cursor: pointer;
 
 
 
 
 
 
234
  }
235
  """
236
 
237
- # إعداد واجهة Gradio
238
- gr.Interface(
239
- fn=handle_mode_selection,
240
- inputs=[
241
- gr.Dropdown(choices=["AI Question Answering", "Subnet Calculation"], label="Select Mode"),
242
- gr.Textbox(label="Input", placeholder="Ask your question or enter an IP address/subnet..."),
243
- gr.Slider(minimum=50, maximum=1024, step=1, value=128, label="Max Length"),
244
- gr.Slider(minimum=1, maximum=10, step=1, value=2, label="Num Beams"),
245
- gr.Slider(minimum=0.0, maximum=1.0, step=0.1, value=0.5, label="Temperature")
246
- ],
247
- outputs=[
248
- gr.Markdown(label="GPT-2 Answer"),
249
- gr.Markdown(label="Najeb Answer"),
250
- #gr.Markdown(label="LLaMA 2 Answer"),
251
- gr.Markdown(label="Summarized Answer"),
252
- gr.Markdown(label="Previous Questions")
253
- ],
254
- css=custom_css,
255
- live=True
256
- ).launch(debug=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
  import asyncio
6
  import ipaddress
7
  from typing import Tuple
8
+ from accelerate import Accelerator
9
 
 
10
  os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "expandable_segments:True"
11
 
12
+ accelerator = Accelerator()
13
+
14
+ gpt2_pipeline = accelerator.prepare(
15
+ pipeline("text-generation", model="Qwen/Qwen-1_8B-Chat", device=accelerator.device)
16
+ )
17
+ Najeb_pipeline = accelerator.prepare(
18
+ pipeline("text-generation", model="najeebjust/Najeeb", device=accelerator.device)
19
+ )
20
+ llama2_pipeline = accelerator.prepare(
21
+ pipeline("text-generation", model="Harikrishnan46624/finetuned_llama2-1.1b-chat", device=accelerator.device)
22
+ )
23
+ '''
24
+ gpt2_pipeline = pipeline("text-generation", model="Qwen/Qwen-1_8B-Chat", device=0 if torch.cuda.is_available() else -1, trust_remote_code=True)
25
+ Najeb_pipeline = pipeline("text-generation", model="najeebjust/Najeeb", device=0 if torch.cuda.is_available() else -1)
26
+ llama2_pipeline = pipeline("text-generation", model="Harikrishnan46624/finetuned_llama2-1.1b-chat", device=0 if torch.cuda.is_available() else -1)
27
+ '''
28
+ summarization_pipeline = pipeline("summarization", model="Falconsai/text_summarization", device=0 if torch.cuda.is_available() else -1)
29
 
 
 
 
 
 
 
30
 
31
  previous_questions = []
32
 
33
 
 
34
  async def generate_gpt2(question, max_length, num_beams, temperature):
35
  return gpt2_pipeline(
36
  question,
 
38
  num_return_sequences=1,
39
  num_beams=num_beams,
40
  do_sample=True,
41
+ top_k=30,
42
+ top_p=0.9,
43
  temperature=temperature
44
  )[0]['generated_text']
45
 
 
46
  async def generate_Najeb(question, max_length, num_beams, temperature):
47
  return Najeb_pipeline(
48
  question,
 
54
  top_p=0.85,
55
  temperature=temperature
56
  )[0]['generated_text']
57
+
 
 
58
  async def generate_llama2(question, max_length, num_beams, temperature):
59
  return llama2_pipeline(
60
  question,
 
62
  num_return_sequences=1,
63
  num_beams=num_beams,
64
  do_sample=True,
65
+ top_k=30,
66
+ top_p=0.9,
67
  temperature=temperature
68
+ )[0]['generated_text']
69
+
70
 
 
71
  async def generate_responses_async(question, max_length=128, num_beams=2, temperature=0.5):
72
+ responses = {}
73
+
74
+
75
  previous_questions.append(question)
76
 
 
77
  gpt2_task = asyncio.create_task(generate_gpt2(question, max_length, num_beams, temperature))
78
  Najeb_task = asyncio.create_task(generate_Najeb(question, max_length, num_beams, temperature))
79
+ llama2_task = asyncio.create_task(generate_llama2(question, max_length, num_beams, temperature))
80
+
81
+ gpt2_response, Najeb_response, llama2_response = await asyncio.gather(gpt2_task, Najeb_task, llama2_task)
82
+
83
+ responses['GPT-2'] = gpt2_response
84
+ responses['Najeb '] = Najeb_response
85
+ responses['LLaMA 2'] = llama2_response
86
+
87
+
88
+ combined_responses = f"GPT-2: {gpt2_response}\nNajeb: {Najeb_response}\nLLaMA 2: {llama2_response}"
89
 
 
 
90
 
 
 
91
  summarized_response = summarization_pipeline(combined_responses, max_length=150, min_length=50, do_sample=False)[0]['summary_text']
92
 
93
  return {
94
+
95
+ "Najeb Answering Response": Najeb_response,
96
+ "GPT-2 Answering Response": gpt2_response,
97
+ "LLaMA 2 Answering Response": llama2_response,
98
+ "Summarized Answering Response": summarized_response,
99
  "Previous Questions": "\n".join(previous_questions[-5:])
100
  }
101
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
102
 
 
103
  def get_network(ip_input: str) -> Tuple[ipaddress.IPv4Network, str]:
104
  try:
105
  if ip_input.count("/") == 0:
 
110
  except ValueError:
111
  return None, None
112
 
 
113
  def calculate_subnet(ip_input: str) -> str:
114
  network, ip = get_network(ip_input)
115
  if network is None or ip is None:
116
  return "Invalid IP Address or Subnet!"
117
 
118
+
119
  network_address = network.network_address
120
  broadcast_address = network.broadcast_address
121
  usable_hosts = list(network.hosts())
122
  num_usable_hosts = len(usable_hosts)
123
  usable_hosts_range = f"{usable_hosts[0]} - {usable_hosts[-1]}" if usable_hosts else "NA"
124
 
125
+
126
  octets = str(ip).split('.')
127
  binary_octets = [bin(int(octet))[2:].zfill(8) for octet in octets]
128
  bin_ip = '.'.join(binary_octets)
 
133
  bin_mask = str(bin(int(network.netmask))[2:].zfill(32))
134
  bin_mask = '.'.join([bin_mask[i:i+8] for i in range(0, len(bin_mask), 8)])
135
 
136
+
137
  result = f"""
138
  IP Address: {ip}
139
  Address (bin): {bin_ip}
 
151
  """
152
  return result.strip()
153
 
154
+
155
+
156
+ def handle_mode_selection(mode, input_text, max_length, num_beams, temperature):
157
+ if mode == "AI Question Answering":
158
+ result = asyncio.run(generate_responses_async(input_text, max_length, num_beams, temperature))
159
+ return result, ""
160
+ else:
161
+ subnet_result = calculate_subnet(input_text)
162
+ return {"Subnet Calculation Result": subnet_result}, ""
163
+
164
+
165
  custom_css = """
166
  body {
167
  background-color: #f0f8ff;
 
221
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
222
  }
223
 
224
+
225
  #image-container {
226
  text-align: center;
227
  position: relative;
228
  }
229
 
230
  #image-container img {
231
+ width: 1400px;
232
+ border-radius: 10px;
233
+ box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
234
  }
235
 
236
  #image-container button {
237
  position: absolute;
238
+ top: 50%;
239
+ left: 50%;
240
+ transform: translate(-50%, -50%);
241
+ background-color: rgba(0, 102, 204, 0.8);
242
  color: white;
243
  border: none;
244
+ padding: 10px 20px;
245
+ border-radius: 5px;
246
  cursor: pointer;
247
+ font-size: 16px;
248
+ transition: background-color 0.3s ease;
249
+ }
250
+
251
+ #image-container button:hover {
252
+ background-color: rgba(0, 76, 153, 0.8);
253
  }
254
  """
255
 
256
+
257
+ scroll_js = """
258
+ <script>
259
+ function scrollToTop() {
260
+ document.getElementById('target-section').scrollIntoView({behavior: 'smooth'});
261
+ }
262
+ </script>
263
+ """
264
+
265
+
266
+ iface = gr.Blocks(css=custom_css)
267
+
268
+ with iface:
269
+ gr.Markdown(f"<h1>Welcome to Najeb</h1><p>AI Question & Subnet Calculator, Enter your question or IP address to generate answers or calculate subnets.</p>")
270
+
271
+
272
+ gr.HTML(f"""
273
+ <div id="image-container">
274
+ <img src="https://news.cornell.edu/sites/default/files/styles/story_thumbnail_xlarge/public/2024-07/robot-1280x720_0.jpg?itok=AF6MakCq" alt="AI Image">
275
+ <button onclick="scrollToTop()">Go to Top</button>
276
+ </div>
277
+ {scroll_js} <!-- Adding the JS to handle scrolling -->
278
+ """)
279
+
280
+
281
+ gr.Markdown("<div id='target-section'></div>")
282
+
283
+ with gr.Row():
284
+ mode_selector = gr.Radio(["AI Question Answering", "Subnet Calculation"], label="Select Mode", value="AI Question Answering")
285
+
286
+ with gr.Row():
287
+ with gr.Column():
288
+ input_text = gr.Textbox(label="Enter your question or IP", placeholder="Type here...", lines=2)
289
+ max_length_slider = gr.Slider(minimum=50, maximum=1024, value=128, label="Max Length")
290
+ num_beams_slider = gr.Slider(minimum=1, maximum=10, value=2, label="Number of Beams", step=1)
291
+ temperature_slider = gr.Slider(minimum=0.1, maximum=1.0, value=0.5, label="Temperature", step=0.1)
292
+ submit_button = gr.Button("Submit")
293
+
294
+ with gr.Column():
295
+ output_box = gr.JSON(label="Response Output")
296
+ previous_questions_box = gr.Markdown("### Previous Questions\n")
297
+
298
+ submit_button.click(
299
+ handle_mode_selection,
300
+ inputs=[mode_selector, input_text, max_length_slider, num_beams_slider, temperature_slider],
301
+ outputs=[output_box, previous_questions_box]
302
+ )
303
+
304
+
305
+ iface.launch(share=True)