Datasets:
Upload 11 files
Browse filesFiles changed (11)
- runs/python/__pycache__/config.cpython-312.pycAdded
- runs/python/__pycache__/telegram.cpython-312.pycAdded
- runs/python/__pycache__/telegram_gemini.cpython-312.pycAdded
- runs/python/bot.pyAdded+27
- runs/python/config.pyAdded+3
- runs/python/gemini_telegram.pyAdded+36
- runs/python/radar.pyAdded+263
- runs/python/telegram_gemini.pyAdded+34
- runs/python/telegram_gemini2.pyAdded+56
- runs/python/telegram_gemini3.pyAdded+56
- runs/python/telegram_gemini4.pyAdded+55
123456789101112131415161718192021222324252627# bot.py
from telegram import Update
from telegram.ext import ApplicationBuilder, MessageHandler, filters, ContextTypes
import openai
from openai import OpenAI
import config
client = OpenAI(api_key=config.OPENAI_API_KEY)
async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
user_message = update.message.text
response = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[
{"role": "user", "content": user_message}
]
)
reply = response.choices[0].message.content
await update.message.reply_text(reply)
# راهاندازی ربات
app = ApplicationBuilder().token(config.TELEGRAM_BOT_TOKEN).build()
app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message))
app.run_polling()123# config.py
OPENAI_API_KEY = "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"
TELEGRAM_BOT_TOKEN = "7490823724:AAEcskSIKg9t63nBME3Igkxw_QE4dl2Ql_U"123456789101112131415161718192021222324252627282930313233343536import requests
from telegram_gemini import Update
from telegram.ext import ApplicationBuilder, MessageHandler, ContextTypes, filters
BOT_TOKEN = "7490823724:AAEcskSIKg9t63nBME3Igkxw_QE4dl2Ql_U"
LLAMA_API_URL = "http://127.0.0.1:8080/completion"
# تابع گرفتن پاسخ از سرور llama.cpp
def get_llama_response(prompt):
payload = {
"prompt": prompt,
"max_tokens": 256,
"temperature": 0.7,
"stop": ["</s>", "User:"]
}
response = requests.post(LLAMA_API_URL, json=payload)
if response.ok:
return response.json()["content"].strip()
else:
return "خطا در ارتباط با مدل زبان."
# تابع هندل پیام تلگرام
async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
user_input = update.message.text
reply = get_llama_response(user_input)
await update.message.reply_text(reply)
# راهاندازی ربات
app = ApplicationBuilder().token(BOT_TOKEN).build()
app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message))
app.run_polling()
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from mpl_toolkits.mplot3d import Axes3D, art3d
import random
# Parameters
WORLD_SIZE = 100000
AIRCRAFT_COUNT = 100
RADAR_RANGE = 70000
RADAR_ALTITUDE_LIMIT = 20000 # max altitude radar covers in meters
SCAN_SPEED = 2.0 # degrees per frame
BEAM_WIDTH = 5.0 # degrees width of radar beam
TRACK_LENGTH = 20 # length of tail/track for aircrafts
MAX_ACCELERATION = 5 # m/s^2 max change in velocity per frame
# Aircraft types with properties
AIRCRAFT_TYPES = {
'commercial': {'rcs_range': (10, 20), 'color': 'cyan', 'size': 30},
'military': {'rcs_range': (5, 12), 'color': 'red', 'size': 40},
'drone': {'rcs_range': (1, 4), 'color': 'yellow', 'size': 20},
'unknown': {'rcs_range': (0.5, 2), 'color': 'magenta', 'size': 25}
}
# Event Class with motion
class MovingEvent3D:
def __init__(self, evt_type, center, radius, altitude, velocity):
self.type = evt_type
self.center = np.array(center, dtype=float)
self.radius = radius
self.altitude = altitude
self.velocity = np.array(velocity, dtype=float)
self.active = True
def update(self):
self.center += self.velocity
# Bounce inside world bounds for x,y
for i in [0, 1]:
if self.center[i] < 0 or self.center[i] > WORLD_SIZE:
self.velocity[i] = -self.velocity[i]
self.center[i] = np.clip(self.center[i], 0, WORLD_SIZE)
# Bounce altitude inside radar altitude limit
if self.altitude < 0 or self.altitude > RADAR_ALTITUDE_LIMIT:
self.velocity[2] = -self.velocity[2]
self.altitude = np.clip(self.altitude, 0, RADAR_ALTITUDE_LIMIT)
# Random on/off toggle for event activity
if random.random() < 0.001:
self.active = not self.active
def generate_moving_events_3d():
events = []
for _ in range(4):
evt_type = random.choice(['storm', 'no-fly-zone', 'jamming', 'interference'])
center = np.random.uniform(0, WORLD_SIZE, 2)
altitude = np.random.uniform(0, RADAR_ALTITUDE_LIMIT)
radius = {'storm': 15000, 'no-fly-zone': 10000, 'jamming': 8000, 'interference':12000}[evt_type]
velocity = np.random.uniform(-50, 50, 3)
events.append(MovingEvent3D(evt_type, center, radius, altitude, velocity))
return events
world_events = generate_moving_events_3d()
# Generate aircrafts with altitude, track history, type and variable velocity
def generate_aircraft_3d():
aircrafts = []
for i in range(AIRCRAFT_COUNT):
ac_type = random.choices(list(AIRCRAFT_TYPES.keys()), weights=[0.5,0.3,0.15,0.05])[0]
rcs_min, rcs_max = AIRCRAFT_TYPES[ac_type]['rcs_range']
ac = {
'id': i,
'type': ac_type,
'position': np.array([*np.random.uniform(0, WORLD_SIZE, 2), np.random.uniform(0, RADAR_ALTITUDE_LIMIT)]),
'velocity': np.random.uniform(-50, 50, 3),
'rcs': random.uniform(rcs_min, rcs_max),
'callsign': f"{ac_type[:2].upper()}{i:03}",
'emergency': random.random() < 0.03,
'track': [],
'acceleration': np.zeros(3),
}
aircrafts.append(ac)
return aircrafts
aircrafts = generate_aircraft_3d()
radar_angle = [0]
radar_pos = np.array([WORLD_SIZE/2, WORLD_SIZE/2, 0])
paused = [False]
def is_event_active_3d(pos):
for evt in world_events:
if evt.active:
d_xy = np.linalg.norm(pos[:2] - evt.center)
dz = abs(pos[2] - evt.altitude)
if d_xy < evt.radius and dz < evt.radius / 2:
return evt.type
return None
def detect_3d(ac, radar_pos):
delta = ac['position'] - radar_pos
rng = np.linalg.norm(delta)
if rng > RADAR_RANGE or ac['position'][2] > RADAR_ALTITUDE_LIMIT:
return False
bearing = (np.degrees(np.arctan2(delta[1], delta[0])) + 360) % 360
diff = abs((bearing - radar_angle[0] + 180) % 360 - 180)
if diff > BEAM_WIDTH / 2:
return False
evt = is_event_active_3d(ac['position'])
snr_val = 20 - 20*np.log10(rng + 1) + ac['rcs']
if evt == 'jamming':
snr_val -= 50
elif evt == 'storm':
snr_val -= 15
elif evt == 'interference':
snr_val -= 25
prob = 1 / (1 + np.exp(-(snr_val - 10)))
# Introduce random detection noise
noise = np.random.normal(0, 0.1)
return np.random.rand() < (prob + noise)
# Setup plot
fig = plt.figure(figsize=(14, 10))
ax = fig.add_subplot(111, projection='3d')
ax.set_xlim(0, WORLD_SIZE)
ax.set_ylim(0, WORLD_SIZE)
ax.set_zlim(0, RADAR_ALTITUDE_LIMIT)
ax.set_facecolor('black')
# Scatter for different types of aircrafts (dynamic update)
all_scatter = ax.scatter([], [], [], c=[], s=[], label='Aircraft')
detected_scatter = ax.scatter([], [], [], c='lime', s=60, label='Detected')
emergency_scatter = ax.scatter([], [], [], c='orange', s=80, marker='^', label='Emergency')
radar_sweep_line, = ax.plot([], [], [], c='cyan', linewidth=3, label='Radar Sweep')
# Track lines for aircrafts
track_lines = [ax.plot([], [], [], c='white', alpha=0.3, linewidth=1)[0] for _ in range(AIRCRAFT_COUNT)]
event_spheres = []
event_colors = {'storm':'blue', 'no-fly-zone':'yellow', 'jamming':'magenta', 'interference':'purple'}
def plot_sphere(center, radius, color):
u = np.linspace(0, 2*np.pi, 20)
v = np.linspace(0, np.pi, 20)
x = center[0] + radius * np.outer(np.cos(u), np.sin(v))
y = center[1] + radius * np.outer(np.sin(u), np.sin(v))
z = center[2] + radius * np.outer(np.ones(np.size(u)), np.cos(v))
return ax.plot_surface(x, y, z, color=color, alpha=0.15)
for evt in world_events:
sphere = plot_sphere(np.array([*evt.center, evt.altitude]), evt.radius, event_colors[evt.type])
event_spheres.append(sphere)
# Radar range circle on ground
radar_circle = plt.Circle((radar_pos[0], radar_pos[1]), RADAR_RANGE, color='cyan', alpha=0.1)
ax.add_patch(radar_circle)
art3d.pathpatch_2d_to_3d(radar_circle, z=0, zdir="z")
def update(frame):
if paused[0]:
return
# بهروزرسانی زاویه رادار
radar_angle[0] = (radar_angle[0] + 1) % 360
all_pos = []
all_colors = []
all_sizes = []
detected_pos = []
emergency_pos = []
for ac in aircrafts:
# محدود کردن سرعت
v_mag = np.linalg.norm(ac['velocity'])
max_speed = 250 # m/s
if v_mag > max_speed:
ac['velocity'] = (ac['velocity'] / v_mag) * max_speed
# بهروزرسانی موقعیت
ac['position'] += ac['velocity']
# برخورد به دیوارههای جهان
for i in [0, 1]:
if ac['position'][i] < 0 or ac['position'][i] > WORLD_SIZE:
ac['velocity'][i] = -ac['velocity'][i]
ac['position'][i] = np.clip(ac['position'][i], 0, WORLD_SIZE)
if ac['position'][2] < 0 or ac['position'][2] > RADAR_ALTITUDE_LIMIT:
ac['velocity'][2] = -ac['velocity'][2]
ac['position'][2] = np.clip(ac['position'][2], 0, RADAR_ALTITUDE_LIMIT)
# ثبت رد حرکت
ac['track'].append(ac['position'].copy())
if len(ac['track']) > TRACK_LENGTH:
ac['track'].pop(0)
all_pos.append(ac['position'])
all_colors.append(AIRCRAFT_TYPES[ac['type']]['color'])
all_sizes.append(AIRCRAFT_TYPES[ac['type']]['size'])
if detect_3d(ac, radar_pos):
detected_pos.append(ac['position'])
if ac['emergency']:
emergency_pos.append(ac['position'])
# تبدیل به np.array
all_pos = np.array(all_pos)
detected_pos = np.array(detected_pos)
emergency_pos = np.array(emergency_pos)
# آپدیت scatter کل هواپیماها
if len(all_pos) > 0:
all_scatter._offsets3d = (all_pos[:,0], all_pos[:,1], all_pos[:,2])
all_scatter.set_color(all_colors)
all_scatter.set_sizes(all_sizes)
else:
all_scatter._offsets3d = ([], [], [])
all_scatter.set_color([])
all_scatter.set_sizes([])
# آپدیت scatter هواپیماهای تشخیص داده شده
if len(detected_pos) > 0:
detected_scatter._offsets3d = (detected_pos[:,0], detected_pos[:,1], detected_pos[:,2])
detected_scatter.set_sizes([60]*len(detected_pos))
else:
detected_scatter._offsets3d = ([], [], [])
detected_scatter.set_sizes([])
# آپدیت scatter هواپیماهای اضطراری
if len(emergency_pos) > 0:
emergency_scatter._offsets3d = (emergency_pos[:,0], emergency_pos[:,1], emergency_pos[:,2])
emergency_scatter.set_sizes([80]*len(emergency_pos))
else:
emergency_scatter._offsets3d = ([], [], [])
emergency_scatter.set_sizes([])
# بهروزرسانی خطوط رد حرکت
for i, ac in enumerate(aircrafts):
if len(ac['track']) >= 2:
track_arr = np.array(ac['track'])
track_lines[i].set_data(track_arr[:,0], track_arr[:,1])
track_lines[i].set_3d_properties(track_arr[:,2])
else:
track_lines[i].set_data([], [])
track_lines[i].set_3d_properties([])
# بهروزرسانی خط اسکن رادار
angle_rad = np.radians(radar_angle[0])
x = [radar_pos[0], radar_pos[0] + RADAR_RANGE * np.cos(angle_rad)]
y = [radar_pos[1], radar_pos[1] + RADAR_RANGE * np.sin(angle_rad)]
z = [0, 0]
radar_sweep_line.set_data(x, y)
radar_sweep_line.set_3d_properties(z)
ax.set_title(f"3D Radar Simulation - Scan Angle: {radar_angle[0]:.1f}°")
def on_key(event):
if event.key == ' ':
paused[0] = not paused[0]
fig.canvas.mpl_connect('key_press_event', on_key)
ani = FuncAnimation(fig, update, interval=50)
plt.legend(loc='upper right')
plt.show()12345678910111213141516171819202122232425262728293031323334import requests
from telegram import Update
from telegram.ext import ApplicationBuilder, MessageHandler, ContextTypes, filters
BOT_TOKEN = "7490823724:AAEcskSIKg9t63nBME3Igkxw_QE4dl2Ql_U"
LLAMA_API_URL = "http://127.0.0.1:8080/completion"
# گرفتن پاسخ از llama.cpp
def get_llama_response(prompt):
system_prompt = f"User: {prompt}\nAssistant:"
payload = {
"prompt": system_prompt,
"max_tokens": 64,
"temperature": 0.7,
"stop": ["</s>", "User:"]
}
response = requests.post(LLAMA_API_URL, json=payload)
if response.ok:
return response.json()["content"].strip()
else:
return "خطا در ارتباط با مدل زبان."
# هندل کردن پیامهایی که با / شروع میشن
async def handle_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
message = update.message
user_input = message.text.lstrip('/gemma') # حذف اسلش اول
reply = get_llama_response(user_input)
await message.reply_text(reply)
# راهاندازی ربات
app = ApplicationBuilder().token(BOT_TOKEN).build()
app.add_handler(MessageHandler(filters.COMMAND, handle_command))
app.run_polling()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556import asyncio
import aiohttp # برای درخواستهای async
from telegram import Update
from telegram.ext import ApplicationBuilder, MessageHandler, ContextTypes, filters
import logging
# تنظیمات
BOT_TOKEN = "7490823724:AAEcskSIKg9t63nBME3Igkxw_QE4dl2Ql_U"
LLAMA_API_URL = "http://127.0.0.1:8080/completion"
# لاگگیری
logging.basicConfig(
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
)
# گرفتن پاسخ از llama.cpp به صورت async
async def get_llama_response(prompt: str) -> str:
system_prompt = f"User: {prompt}\nAssistant:"
payload = {
"prompt": system_prompt,
"max_tokens": 64,
"temperature": 0.7,
"stop": ["</s>", "User:"]
}
try:
async with aiohttp.ClientSession() as session:
async with session.post(LLAMA_API_URL, json=payload, timeout=60) as resp:
if resp.status == 200:
data = await resp.json()
return data.get("content", "").strip()
else:
logging.error(f"LLaMA API Error: {resp.status}")
return "❌ خطا در دریافت پاسخ از مدل زبان."
except asyncio.TimeoutError:
return "⏱️ مدل دیر پاسخ داد. لطفاً دوباره تلاش کنید."
except Exception as e:
logging.exception("خطا در ارتباط با مدل:")
return "⚠️ خطا در پردازش درخواست شما."
# هندل کردن پیامهای دستوری
async def handle_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
message = update.message
if message and message.text:
user_input = message.text.lstrip('/')
await message.chat.send_action("typing")
response = await get_llama_response(user_input)
await message.reply_text(response)
# راهاندازی ربات
def main():
app = ApplicationBuilder().token(BOT_TOKEN).build()
app.add_handler(MessageHandler(filters.COMMAND, handle_command))
app.run_polling()
if __name__ == "__main__":
main()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556import asyncio
import aiohttp
from telegram import Update
from telegram.ext import ApplicationBuilder, MessageHandler, ContextTypes, filters
import logging
BOT_TOKEN = "7490823724:AAEcskSIKg9t63nBME3Igkxw_QE4dl2Ql_U"
LLAMA_API_URL = "http://127.0.0.1:8080/completion"
logging.basicConfig(
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
)
# گرفتن پاسخ از LLaMA با timeout بلند و مدیریت خطا
async def get_llama_response(prompt: str) -> str:
system_prompt = f"User: {prompt}\nAssistant:"
payload = {
"prompt": system_prompt,
"max_tokens": 60,
"temperature": 0.5,
"stop": ["</s>", "User:"]
}
try:
timeout = aiohttp.ClientTimeout(total=120) # افزایش timeout به 30 ثانیه
async with aiohttp.ClientSession(timeout=timeout) as session:
async with session.post(LLAMA_API_URL, json=payload) as resp:
if resp.status == 200:
data = await resp.json()
return data.get("content", "").strip() or "❔ مدل پاسخی نداد."
else:
text = await resp.text()
logging.error(f"خطای مدل: {resp.status} - {text}")
return f"❌ خطا از مدل ({resp.status}):\n{text}"
except asyncio.TimeoutError:
return "⏱️ مدل دیر پاسخ داد (بیش از ۳۰ ثانیه)."
except aiohttp.ClientConnectionError:
return "🔌 اتصال به مدل برقرار نشد."
except Exception as e:
logging.exception("خطای کلی:")
return f"⚠️ خطای غیرمنتظره: {str(e)}"
async def handle_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
message = update.message
if message and message.text and "/gemma" in message.text.lower():
prompt = message.text.replace("/gemma", "").strip()
await message.chat.send_action("typing")
response = await get_llama_response(prompt)
await message.reply_text(response)
def main():
app = ApplicationBuilder().token(BOT_TOKEN).build()
app.add_handler(MessageHandler(filters.COMMAND, handle_command))
app.run_polling()
if __name__ == "__main__":
main()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455import asyncio
import aiohttp
from telegram import Update
from telegram.ext import ApplicationBuilder, MessageHandler, ContextTypes, filters
import logging
BOT_TOKEN = "7490823724:AAEcskSIKg9t63nBME3Igkxw_QE4dl2Ql_U"
LLAMA_API_URL = "http://127.0.0.1:8080/completion"
logging.basicConfig(
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
)
async def get_llama_response(prompt: str) -> str:
system_prompt = f"User: {prompt}\nAssistant:"
payload = {
"prompt": system_prompt,
"max_tokens": 100,
"temperature": 0.7,
"stop": ["</s>", "User:"]
}
try:
timeout = aiohttp.ClientTimeout(total=60)
async with aiohttp.ClientSession(timeout=timeout) as session:
async with session.post(LLAMA_API_URL, json=payload) as resp:
if resp.status == 200:
data = await resp.json()
return data.get("content", "").strip() or "❔ مدل پاسخی نداد."
else:
text = await resp.text()
logging.error(f"خطای مدل: {resp.status} - {text}")
return f"❌ خطا از مدل ({resp.status}):\n{text}"
except asyncio.TimeoutError:
return "⏱️ مدل دیر پاسخ داد."
except aiohttp.ClientConnectionError:
return "🔌 اتصال به مدل برقرار نشد."
except Exception as e:
logging.exception("خطای کلی:")
return f"⚠️ خطای غیرمنتظره: {str(e)}"
async def handle_gemma(update: Update, context: ContextTypes.DEFAULT_TYPE):
message = update.message
if message and message.text and "/gemma" in message.text.lower():
prompt = message.text.replace("/gemma", "").strip()
await message.chat.send_action("typing")
response = await get_llama_response(prompt)
await message.reply_text(response)
def main():
app = ApplicationBuilder().token(BOT_TOKEN).build()
app.add_handler(MessageHandler(filters.TEXT & (~filters.COMMAND), handle_gemma))
app.run_polling()
if __name__ == "__main__":
main()runs/python/__pycache__/config.cpython-312.pycAdded
runs/python/__pycache__/telegram.cpython-312.pycAdded
runs/python/__pycache__/telegram_gemini.cpython-312.pycAdded
runs/python/bot.pyAdded+27
runs/python/config.pyAdded+3
runs/python/gemini_telegram.pyAdded+36
runs/python/radar.pyAdded+263
runs/python/telegram_gemini.pyAdded+34
runs/python/telegram_gemini2.pyAdded+56
runs/python/telegram_gemini3.pyAdded+56
runs/python/telegram_gemini4.pyAdded+55