naokimatui commited on
Commit
447f7ae
·
verified ·
1 Parent(s): cf319d2

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +85 -50
  2. requirements.txt +2 -1
app.py CHANGED
@@ -1,50 +1,85 @@
1
- import streamlit as st
2
- import requests
3
- import os
4
-
5
- # タイトルと説明
6
- st.title("🌤️ 都市の天気情報アプリ")
7
- st.write("都市名入力すると、現在の天気情報を表示します!")
8
-
9
- # OpenWeatherMap APIキーの設定
10
- # 環境変数から取得(Hugging Face SpacesはSecretsで設
11
- API_KEY = os.getenv("OPENWEATHER_API_KEY", "fa76b00a019956810e72e5b332e8f61e") # ローカルテスト用にここに直接書くか、SpacesのSecretsで設定
12
- BASE_URL = "http://api.openweathermap.org/data/2.5/weather"
13
-
14
- # ユーザー
15
- city = st.text_input("都市名入力してください(例: Tokyo)", "Tokyo")
16
-
17
- # APIリクエストと結果表示
18
- if st.button("天気を取得"):
19
- if city:
20
- # APIリクエストパラメータ
21
- params = {
22
- "q": city,
23
- "appid": API_KEY,
24
- "units": "metric", # 摂氏取得
25
- "lang": "ja" # 日本語で天気情報を取得
26
- }
27
-
28
- try:
29
- # APIリクエスト送信
30
- response = requests.get(BASE_URL, params=params)
31
- data = response.json()
32
-
33
- # レスポンスが正常か確認
34
- if response.status_code == 200:
35
- # 天気情報の抽出
36
- temp = data["main"]["temp"]
37
- weather = data["weather"][0]["description"]
38
- st.success(f"**{city}天気**")
39
- st.write(f"**気温**: {temp}℃")
40
- st.write(f"**天気**: {weather}")
41
- else:
42
- st.error(f"エラー: 都市 '{city}' が見つかりません。別都市名を試してください。")
43
-
44
- except Exception as e:
45
- st.error(f"エラーが発生しました: {str(e)}")
46
- else:
47
- st.warning("都市名を入力してください!")
48
-
49
- # フッター
50
- st.markdown("Powered by [OpenWeatherMap](https://openweathermap.org/)")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import numpy as np
3
+ import matplotlib.pyplot as plt
4
+ import math
5
+
6
+ # ページ設定
7
+ st.set_page_config(page_title="モンテカルロで円周率推定", page_icon="🔵", layout="wide")
8
+
9
+ # タイトルと説明
10
+ st.title("🔵 モンテカルロ法円周率を推")
11
+ st.markdown("""
12
+ このアプリは、ランダムに点を打って円周率(π)を推定します!
13
+ - 円(半径1)と外接正方形(辺の長さ2)にランダムに点を打ちます。
14
+ - 円の中にる点の割合からπを近似します。
15
+ - スライダーで点の数調整して、結果の変化を観察してみてください
16
+ """)
17
+
18
+ # サイドバーで設定
19
+ st.sidebar.header("設定")
20
+ num_points = st.sidebar.slider("点数", min_value=100, max_value=100000, value=1000, step=100)
21
+ point_color = st.sidebar.color_picker("点の色", "#FF4B4B")
22
+ show_points = st.sidebar.checkbox("点をプロットする", value=True)
23
+
24
+ # セッション状態計算トリガーを管理
25
+ if 'run_calc' not in st.session_state:
26
+ st.session_state.run_calc = False
27
+
28
+ # 計算ボタン
29
+ if st.button("計算を実行!"):
30
+ st.session_state.run_calc = True
31
+
32
+ # モンテカルロ計算とプロット
33
+ if st.session_state.run_calc:
34
+ # ランダムに点を生成
35
+ x = np.random.uniform(-1, 1, num_points)
36
+ y = np.random.uniform(-1, 1, num_points)
37
+
38
+ # 円中か判定(x^2 + y^2 <= 1)
39
+ distances = x**2 + y**2
40
+ inside_circle = distances <= 1
41
+
42
+ # 円周率推定
43
+ pi_estimate = 4 * np.sum(inside_circle) / num_points
44
+
45
+ # 結果表示
46
+ st.subheader("結果")
47
+ col1, col2 = st.columns(2)
48
+ with col1:
49
+ st.metric("推定された円周率", f"{pi_estimate:.6f}")
50
+ st.metric("実際の円周率との誤差", f"{abs(pi_estimate - math.pi):.6f}")
51
+ with col2:
52
+ st.write(f"**点の数**: {num_points}")
53
+ st.write(f"**円内の点**: {np.sum(inside_circle)}")
54
+ st.write(f"**円外の点**: {num_points - np.sum(inside_circle)}")
55
+
56
+ # プロット
57
+ st.subheader("プロット")
58
+ fig, ax = plt.subplots(figsize=(6, 6))
59
+
60
+ # 円を描画
61
+ circle = plt.Circle((0, 0), 1, edgecolor='blue', facecolor='none', linewidth=2)
62
+ ax.add_patch(circle)
63
+
64
+ # 点をプロット(オプションで非表示)
65
+ if show_points:
66
+ ax.scatter(x[inside_circle], y[inside_circle], c=point_color, s=1, alpha=0.5, label="円内")
67
+ ax.scatter(x[~inside_circle], y[~inside_circle], c="gray", s=1, alpha=0.5, label="円外")
68
+
69
+ # グラフ設定
70
+ ax.set_xlim(-1.5, 1.5)
71
+ ax.set_ylim(-1.5, 1.5)
72
+ ax.set_aspect('equal')
73
+ ax.grid(True, linestyle='--', alpha=0.7)
74
+ ax.legend()
75
+ ax.set_title(f"モンテカルロ法 (点の数: {num_points})")
76
+
77
+ # Streamlitにプロットを表示
78
+ st.pyplot(fig)
79
+
80
+ # 注意書き
81
+ st.markdown("*注*: 点が多いほど推定値は正確になりますが、計算とプロットに時間がかかる場合があります。")
82
+
83
+ # フッター
84
+ st.markdown("---")
85
+ st.markdown("Created with 💙 by Streamlit & Hugging Face Spaces")
requirements.txt CHANGED
@@ -1,2 +1,3 @@
1
  streamlit==1.24.0
2
- requests==2.31.0
 
 
1
  streamlit==1.24.0
2
+ numpy==1.26.0
3
+ matplotlib==3.7.1