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import json
|
| 8 |
+
|
| 9 |
+
class BulletDistanceCalculator:
|
| 10 |
+
"""A comprehensive bullet distance calculator with physics modeling."""
|
| 11 |
+
|
| 12 |
+
def __init__(self):
|
| 13 |
+
self.gravity = 9.81 # m/sΒ²
|
| 14 |
+
self.air_density = 1.225 # kg/mΒ³ at sea level
|
| 15 |
+
|
| 16 |
+
def calculate_trajectory(self,
|
| 17 |
+
initial_velocity: float,
|
| 18 |
+
angle: float,
|
| 19 |
+
bullet_mass: float = 0.01,
|
| 20 |
+
drag_coefficient: float = 0.3,
|
| 21 |
+
bullet_diameter: float = 0.007) -> Tuple[np.ndarray, np.ndarray, dict]:
|
| 22 |
+
"""
|
| 23 |
+
Calculate bullet trajectory with air resistance.
|
| 24 |
+
|
| 25 |
+
Args:
|
| 26 |
+
initial_velocity: Initial velocity in m/s
|
| 27 |
+
angle: Launch angle in degrees
|
| 28 |
+
bullet_mass: Mass of bullet in kg
|
| 29 |
+
drag_coefficient: Drag coefficient
|
| 30 |
+
bullet_diameter: Bullet diameter in meters
|
| 31 |
+
|
| 32 |
+
Returns:
|
| 33 |
+
Tuple of (x_coords, y_coords, results_dict)
|
| 34 |
+
"""
|
| 35 |
+
angle_rad = math.radians(angle)
|
| 36 |
+
vx = initial_velocity * math.cos(angle_rad)
|
| 37 |
+
vy = initial_velocity * math.sin(angle_rad)
|
| 38 |
+
|
| 39 |
+
# Calculate cross-sectional area
|
| 40 |
+
area = math.pi * (bullet_diameter / 2) ** 2
|
| 41 |
+
|
| 42 |
+
# Time step for numerical integration
|
| 43 |
+
dt = 0.01
|
| 44 |
+
max_time = 20 # seconds
|
| 45 |
+
|
| 46 |
+
x_coords = [0]
|
| 47 |
+
y_coords = [0]
|
| 48 |
+
t = 0
|
| 49 |
+
|
| 50 |
+
while t < max_time and y_coords[-1] >= 0:
|
| 51 |
+
# Calculate drag force
|
| 52 |
+
velocity = math.sqrt(vx**2 + vy**2)
|
| 53 |
+
if velocity > 0:
|
| 54 |
+
drag_force = 0.5 * self.air_density * velocity**2 * drag_coefficient * area
|
| 55 |
+
drag_x = -drag_force * (vx / velocity)
|
| 56 |
+
drag_y = -drag_force * (vy / velocity)
|
| 57 |
+
else:
|
| 58 |
+
drag_x = drag_y = 0
|
| 59 |
+
|
| 60 |
+
# Update velocities
|
| 61 |
+
vx += (drag_x / bullet_mass) * dt
|
| 62 |
+
vy += ((drag_y / bullet_mass) - self.gravity) * dt
|
| 63 |
+
|
| 64 |
+
# Update positions
|
| 65 |
+
x = x_coords[-1] + vx * dt
|
| 66 |
+
y = y_coords[-1] + vy * dt
|
| 67 |
+
|
| 68 |
+
if y < 0: # Ground impact
|
| 69 |
+
# Linear interpolation to find exact impact point
|
| 70 |
+
y_prev = y_coords[-1]
|
| 71 |
+
x_prev = x_coords[-1]
|
| 72 |
+
t_impact = t - dt + dt * (-y_prev) / (y - y_prev)
|
| 73 |
+
x_impact = x_prev + vx * (t_impact - t + dt)
|
| 74 |
+
x_coords.append(x_impact)
|
| 75 |
+
y_coords.append(0)
|
| 76 |
+
break
|
| 77 |
+
|
| 78 |
+
x_coords.append(x)
|
| 79 |
+
y_coords.append(y)
|
| 80 |
+
t += dt
|
| 81 |
+
|
| 82 |
+
# Calculate results
|
| 83 |
+
max_height = max(y_coords)
|
| 84 |
+
range_distance = x_coords[-1]
|
| 85 |
+
flight_time = t
|
| 86 |
+
|
| 87 |
+
results = {
|
| 88 |
+
'range': range_distance,
|
| 89 |
+
'max_height': max_height,
|
| 90 |
+
'flight_time': flight_time,
|
| 91 |
+
'final_velocity': math.sqrt(vx**2 + vy**2),
|
| 92 |
+
'impact_angle': math.degrees(math.atan2(vy, vx))
|
| 93 |
+
}
|
| 94 |
+
|
| 95 |
+
return np.array(x_coords), np.array(y_coords), results
|
| 96 |
+
|
| 97 |
+
def create_trajectory_plot(x_coords: np.ndarray, y_coords: np.ndarray, results: dict) -> str:
|
| 98 |
+
"""Create a matplotlib plot of the trajectory."""
|
| 99 |
+
plt.figure(figsize=(10, 6))
|
| 100 |
+
plt.plot(x_coords, y_coords, 'b-', linewidth=2, label='Trajectory')
|
| 101 |
+
plt.scatter([0], [0], color='green', s=100, label='Launch Point', zorder=5)
|
| 102 |
+
plt.scatter([x_coords[-1]], [y_coords[-1]], color='red', s=100, label='Impact Point', zorder=5)
|
| 103 |
+
|
| 104 |
+
plt.xlabel('Distance (m)')
|
| 105 |
+
plt.ylabel('Height (m)')
|
| 106 |
+
plt.title(f'Bullet Trajectory\nRange: {results["range"]:.1f}m, Max Height: {results["max_height"]:.1f}m')
|
| 107 |
+
plt.grid(True, alpha=0.3)
|
| 108 |
+
plt.legend()
|
| 109 |
+
plt.axis('equal')
|
| 110 |
+
|
| 111 |
+
# Save plot
|
| 112 |
+
plot_path = "trajectory_plot.png"
|
| 113 |
+
plt.savefig(plot_path, dpi=150, bbox_inches='tight')
|
| 114 |
+
plt.close()
|
| 115 |
+
|
| 116 |
+
return plot_path
|
| 117 |
+
|
| 118 |
+
def calculate_bullet_distance(velocity: float,
|
| 119 |
+
angle: float,
|
| 120 |
+
mass: float,
|
| 121 |
+
drag_coeff: float,
|
| 122 |
+
diameter: float) -> Tuple[str, str, str]:
|
| 123 |
+
"""
|
| 124 |
+
Main function for Gradio interface.
|
| 125 |
+
|
| 126 |
+
Returns:
|
| 127 |
+
Tuple of (results_text, plot_path, detailed_info)
|
| 128 |
+
"""
|
| 129 |
+
try:
|
| 130 |
+
calculator = BulletDistanceCalculator()
|
| 131 |
+
x_coords, y_coords, results = calculator.calculate_trajectory(
|
| 132 |
+
velocity, angle, mass, drag_coeff, diameter
|
| 133 |
+
)
|
| 134 |
+
|
| 135 |
+
# Create plot
|
| 136 |
+
plot_path = create_trajectory_plot(x_coords, y_coords, results)
|
| 137 |
+
|
| 138 |
+
# Format results
|
| 139 |
+
results_text = f"""
|
| 140 |
+
π― **Bullet Distance Calculation Results**
|
| 141 |
+
|
| 142 |
+
π **Range**: {results['range']:.2f} meters
|
| 143 |
+
π **Maximum Height**: {results['max_height']:.2f} meters
|
| 144 |
+
β±οΈ **Flight Time**: {results['flight_time']:.2f} seconds
|
| 145 |
+
π **Final Velocity**: {results['final_velocity']:.2f} m/s
|
| 146 |
+
π **Impact Angle**: {results['impact_angle']:.1f}Β°
|
| 147 |
+
"""
|
| 148 |
+
|
| 149 |
+
detailed_info = f"""
|
| 150 |
+
**Physics Parameters:**
|
| 151 |
+
- Initial Velocity: {velocity} m/s
|
| 152 |
+
- Launch Angle: {angle}Β°
|
| 153 |
+
- Bullet Mass: {mass} kg
|
| 154 |
+
- Drag Coefficient: {drag_coeff}
|
| 155 |
+
- Bullet Diameter: {diameter} m
|
| 156 |
+
|
| 157 |
+
**Environmental Conditions:**
|
| 158 |
+
- Gravity: {calculator.gravity} m/sΒ²
|
| 159 |
+
- Air Density: {calculator.air_density} kg/mΒ³
|
| 160 |
+
"""
|
| 161 |
+
|
| 162 |
+
return results_text, plot_path, detailed_info
|
| 163 |
+
|
| 164 |
+
except Exception as e:
|
| 165 |
+
error_msg = f"β Error in calculation: {str(e)}"
|
| 166 |
+
return error_msg, None, error_msg
|
| 167 |
+
|
| 168 |
+
def get_huggingface_model_info(model_name: str) -> str:
|
| 169 |
+
"""Get information about a Hugging Face model."""
|
| 170 |
+
try:
|
| 171 |
+
api_url = f"https://huggingface.co/api/models/{model_name}"
|
| 172 |
+
response = requests.get(api_url, timeout=10)
|
| 173 |
+
|
| 174 |
+
if response.status_code == 200:
|
| 175 |
+
model_data = response.json()
|
| 176 |
+
info = f"""
|
| 177 |
+
π€ **Hugging Face Model Information**
|
| 178 |
+
|
| 179 |
+
**Model**: {model_data.get('modelId', 'Unknown')}
|
| 180 |
+
**Downloads**: {model_data.get('downloads', 0):,}
|
| 181 |
+
**Tags**: {', '.join(model_data.get('tags', []))}
|
| 182 |
+
**Pipeline Tag**: {model_data.get('pipeline_tag', 'N/A')}
|
| 183 |
+
**Library**: {model_data.get('library_name', 'N/A')}
|
| 184 |
+
**Last Modified**: {model_data.get('lastModified', 'N/A')}
|
| 185 |
+
"""
|
| 186 |
+
return info
|
| 187 |
+
else:
|
| 188 |
+
return f"β Error fetching model info: HTTP {response.status_code}"
|
| 189 |
+
|
| 190 |
+
except Exception as e:
|
| 191 |
+
return f"β Error connecting to Hugging Face: {str(e)}"
|
| 192 |
+
|
| 193 |
+
# Create Gradio interface
|
| 194 |
+
with gr.Blocks(title="Bullet Distance Calculator", theme=gr.themes.Soft()) as demo:
|
| 195 |
+
gr.Markdown("""
|
| 196 |
+
# π― Bullet Distance Calculator
|
| 197 |
+
|
| 198 |
+
Calculate bullet trajectory with realistic physics including air resistance, drag, and gravity.
|
| 199 |
+
This app interfaces with Hugging Face and provides comprehensive ballistics calculations.
|
| 200 |
+
""")
|
| 201 |
+
|
| 202 |
+
with gr.Tabs():
|
| 203 |
+
with gr.TabItem("π― Ballistics Calculator"):
|
| 204 |
+
with gr.Row():
|
| 205 |
+
with gr.Column(scale=1):
|
| 206 |
+
gr.Markdown("### Input Parameters")
|
| 207 |
+
|
| 208 |
+
velocity = gr.Slider(
|
| 209 |
+
minimum=100, maximum=1000, value=300, step=10,
|
| 210 |
+
label="Initial Velocity (m/s)",
|
| 211 |
+
info="Typical rifle: 300-800 m/s"
|
| 212 |
+
)
|
| 213 |
+
|
| 214 |
+
angle = gr.Slider(
|
| 215 |
+
minimum=0, maximum=90, value=30, step=1,
|
| 216 |
+
label="Launch Angle (degrees)",
|
| 217 |
+
info="0Β° = horizontal, 90Β° = vertical"
|
| 218 |
+
)
|
| 219 |
+
|
| 220 |
+
mass = gr.Slider(
|
| 221 |
+
minimum=0.001, maximum=0.1, value=0.01, step=0.001,
|
| 222 |
+
label="Bullet Mass (kg)",
|
| 223 |
+
info="Typical: 0.005-0.02 kg"
|
| 224 |
+
)
|
| 225 |
+
|
| 226 |
+
drag_coeff = gr.Slider(
|
| 227 |
+
minimum=0.1, maximum=1.0, value=0.3, step=0.01,
|
| 228 |
+
label="Drag Coefficient",
|
| 229 |
+
info="Typical: 0.2-0.5"
|
| 230 |
+
)
|
| 231 |
+
|
| 232 |
+
diameter = gr.Slider(
|
| 233 |
+
minimum=0.005, maximum=0.02, value=0.007, step=0.001,
|
| 234 |
+
label="Bullet Diameter (m)",
|
| 235 |
+
info="Typical: 0.005-0.01 m"
|
| 236 |
+
)
|
| 237 |
+
|
| 238 |
+
calculate_btn = gr.Button("π Calculate Trajectory", variant="primary")
|
| 239 |
+
|
| 240 |
+
with gr.Column(scale=2):
|
| 241 |
+
gr.Markdown("### Results")
|
| 242 |
+
results_output = gr.Markdown()
|
| 243 |
+
|
| 244 |
+
gr.Markdown("### Trajectory Plot")
|
| 245 |
+
plot_output = gr.Image(label="Trajectory Visualization")
|
| 246 |
+
|
| 247 |
+
gr.Markdown("### Detailed Information")
|
| 248 |
+
detailed_output = gr.Markdown()
|
| 249 |
+
|
| 250 |
+
with gr.TabItem("π€ Hugging Face Integration"):
|
| 251 |
+
gr.Markdown("### Hugging Face Model Information")
|
| 252 |
+
|
| 253 |
+
with gr.Row():
|
| 254 |
+
model_input = gr.Textbox(
|
| 255 |
+
label="Model Name",
|
| 256 |
+
placeholder="e.g., microsoft/DialoGPT-medium",
|
| 257 |
+
value="microsoft/DialoGPT-medium"
|
| 258 |
+
)
|
| 259 |
+
fetch_btn = gr.Button("π Get Model Info", variant="secondary")
|
| 260 |
+
|
| 261 |
+
hf_output = gr.Markdown()
|
| 262 |
+
|
| 263 |
+
with gr.TabItem("π About"):
|
| 264 |
+
gr.Markdown("""
|
| 265 |
+
## About This App
|
| 266 |
+
|
| 267 |
+
This Bullet Distance Calculator provides:
|
| 268 |
+
|
| 269 |
+
- **Realistic Physics**: Includes air resistance, drag, and gravity
|
| 270 |
+
- **Interactive Visualization**: Real-time trajectory plotting
|
| 271 |
+
- **Hugging Face Integration**: Access to model information
|
| 272 |
+
- **Comprehensive Results**: Range, height, flight time, and more
|
| 273 |
+
|
| 274 |
+
### Physics Model
|
| 275 |
+
The calculator uses numerical integration to solve the equations of motion:
|
| 276 |
+
- Accounts for air resistance using drag coefficient
|
| 277 |
+
- Considers bullet mass and cross-sectional area
|
| 278 |
+
- Models realistic environmental conditions
|
| 279 |
+
|
| 280 |
+
### Hugging Face Features
|
| 281 |
+
- Fetch model information and statistics
|
| 282 |
+
- Access model metadata and tags
|
| 283 |
+
- Real-time API integration
|
| 284 |
+
|
| 285 |
+
Built with Gradio and designed for Hugging Face Spaces deployment.
|
| 286 |
+
""")
|
| 287 |
+
|
| 288 |
+
# Event handlers
|
| 289 |
+
calculate_btn.click(
|
| 290 |
+
fn=calculate_bullet_distance,
|
| 291 |
+
inputs=[velocity, angle, mass, drag_coeff, diameter],
|
| 292 |
+
outputs=[results_output, plot_output, detailed_output]
|
| 293 |
+
)
|
| 294 |
+
|
| 295 |
+
fetch_btn.click(
|
| 296 |
+
fn=get_huggingface_model_info,
|
| 297 |
+
inputs=[model_input],
|
| 298 |
+
outputs=[hf_output]
|
| 299 |
+
)
|
| 300 |
+
|
| 301 |
+
if __name__ == "__main__":
|
| 302 |
+
demo.launch(share=True,mcp_server=True)
|
requirements.txt
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
matplotlib
|
| 2 |
+
gradio
|