sugitora commited on
Commit
23d522c
·
verified ·
1 Parent(s): b529b24

Upload 2 files

Browse files
Files changed (2) hide show
  1. Dockerfile +57 -11
  2. risk_monitoring_app.R +1075 -0
Dockerfile CHANGED
@@ -1,14 +1,60 @@
1
- FROM rocker/r-base:latest
 
2
 
3
- WORKDIR /code
4
 
5
- RUN install2.r --error \
6
- shiny \
7
- dplyr \
8
- ggplot2 \
9
- readr \
10
- ggExtra
11
-
12
- COPY . .
 
 
 
 
 
 
 
 
 
 
13
 
14
- CMD ["R", "--quiet", "-e", "shiny::runApp(host='0.0.0.0', port=7860)"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Dockerfile for Hugging Face Spaces - R Shiny App
2
+ # Risk Monitoring Dashboard
3
 
4
+ FROM rocker/shiny:4.3.2
5
 
6
+ # Install system dependencies
7
+ RUN apt-get update && apt-get install -y \
8
+ libcurl4-gnutls-dev \
9
+ libssl-dev \
10
+ libxml2-dev \
11
+ libfontconfig1-dev \
12
+ libfreetype6-dev \
13
+ libpng-dev \
14
+ libtiff5-dev \
15
+ libjpeg-dev \
16
+ libharfbuzz-dev \
17
+ libfribidi-dev \
18
+ libgdal-dev \
19
+ libgeos-dev \
20
+ libproj-dev \
21
+ libudunits2-dev \
22
+ pandoc \
23
+ && rm -rf /var/lib/apt/lists/*
24
 
25
+ # Install R packages
26
+ RUN R -e "install.packages(c(\
27
+ 'shiny', \
28
+ 'bslib', \
29
+ 'leaflet', \
30
+ 'plotly', \
31
+ 'DT', \
32
+ 'dplyr', \
33
+ 'lubridate' \
34
+ ), repos='https://cloud.r-project.org/')"
35
+
36
+ # Create app directory
37
+ RUN mkdir -p /srv/shiny-server/app
38
+
39
+ # Copy app files
40
+ COPY app.R /srv/shiny-server/app/
41
+
42
+ # Set permissions
43
+ RUN chown -R shiny:shiny /srv/shiny-server/app
44
+
45
+ # Expose port (Hugging Face uses 7860)
46
+ EXPOSE 7860
47
+
48
+ # Configure shiny-server to use port 7860
49
+ RUN echo "run_as shiny;\n\
50
+ server {\n\
51
+ listen 7860;\n\
52
+ location / {\n\
53
+ site_dir /srv/shiny-server/app;\n\
54
+ log_dir /var/log/shiny-server;\n\
55
+ directory_index on;\n\
56
+ }\n\
57
+ }" > /etc/shiny-server/shiny-server.conf
58
+
59
+ # Start shiny-server
60
+ CMD ["/usr/bin/shiny-server"]
risk_monitoring_app.R ADDED
@@ -0,0 +1,1075 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # =============================================================================
2
+ # リスクモニタリングシステム プロトタイプ
3
+ # Risk Monitoring Dashboard - Shiny App
4
+ # =============================================================================
5
+
6
+ library(shiny)
7
+ library(bslib)
8
+ library(leaflet)
9
+ library(plotly)
10
+ library(DT)
11
+ library(dplyr)
12
+ library(lubridate)
13
+
14
+ # =============================================================================
15
+ # ダミーデータの生成
16
+ # =============================================================================
17
+
18
+ # 国別リスクデータ
19
+ country_data <- data.frame(
20
+ country = c("Venezuela", "Iran", "Syria", "Yemen", "Afghanistan",
21
+ "Myanmar", "North Korea", "Libya", "Somalia", "Sudan",
22
+ "Japan", "USA", "Germany", "France", "UK",
23
+ "Brazil", "India", "China", "Russia", "South Africa"),
24
+ country_jp = c("ベネズエラ", "イラン", "シリア", "イエメン", "アフガニスタン",
25
+ "ミャンマー", "北朝鮮", "リビア", "ソマリア", "スーダン",
26
+ "日本", "アメリカ", "ドイツ", "フランス", "イギリス",
27
+ "ブラジル", "インド", "中国", "ロシア", "南アフリカ"),
28
+ risk_score = c(95, 92, 88, 85, 82, 78, 76, 72, 70, 68,
29
+ 15, 22, 18, 20, 19, 45, 38, 52, 65, 48),
30
+ lat = c(6.4238, 32.4279, 34.8021, 15.5527, 33.9391,
31
+ 21.9162, 40.3399, 26.3351, 5.1521, 12.8628,
32
+ 36.2048, 37.0902, 51.1657, 46.2276, 55.3781,
33
+ -14.2350, 20.5937, 35.8617, 61.5240, -30.5595),
34
+ lng = c(-66.5897, 53.6880, 38.9968, 48.5164, 67.7100,
35
+ 95.9560, 127.5101, 17.2283, 46.1996, 30.2176,
36
+ 138.2529, -95.7129, 10.4515, 2.2137, -3.4360,
37
+ -51.9253, 78.9629, 104.1954, 105.3188, 22.9375),
38
+ trend = c("up", "up", "stable", "up", "down",
39
+ "up", "stable", "down", "stable", "up",
40
+ "stable", "stable", "stable", "stable", "stable",
41
+ "up", "stable", "up", "up", "stable"),
42
+ region = c("South America", "Middle East", "Middle East", "Middle East", "Central Asia",
43
+ "Southeast Asia", "East Asia", "Africa", "Africa", "Africa",
44
+ "East Asia", "North America", "Europe", "Europe", "Europe",
45
+ "South America", "South Asia", "East Asia", "Europe", "Africa"),
46
+ stringsAsFactors = FALSE
47
+ )
48
+
49
+ # 時系列リスクスコアデータ生成
50
+ generate_time_series <- function(country, base_score) {
51
+ dates <- seq(as.Date("2024-07-01"), as.Date("2025-01-11"), by = "day")
52
+ n <- length(dates)
53
+ noise <- cumsum(rnorm(n, 0, 1.5))
54
+ scores <- pmax(0, pmin(100, base_score + noise - mean(noise)))
55
+
56
+ # 最近のスパイクを追加(高リスク国の場合)
57
+ if (base_score > 70) {
58
+ spike_start <- n - 14
59
+ scores[spike_start:n] <- scores[spike_start:n] + seq(0, 15, length.out = 15)
60
+ scores <- pmin(100, scores)
61
+ }
62
+
63
+ data.frame(
64
+ date = dates,
65
+ score = round(scores, 1),
66
+ country = country
67
+ )
68
+ }
69
+
70
+ # ニュースデータ
71
+ news_data <- data.frame(
72
+ id = 1:20,
73
+ country = c("Venezuela", "Venezuela", "Iran", "Iran", "Syria",
74
+ "Myanmar", "Brazil", "China", "Russia", "Japan",
75
+ "Venezuela", "Iran", "Syria", "Yemen", "Afghanistan",
76
+ "North Korea", "Libya", "India", "Germany", "USA"),
77
+ date = c("2025-01-11", "2025-01-10", "2025-01-11", "2025-01-09", "2025-01-08",
78
+ "2025-01-11", "2025-01-10", "2025-01-09", "2025-01-08", "2025-01-07",
79
+ "2025-01-06", "2025-01-05", "2025-01-04", "2025-01-03", "2025-01-02",
80
+ "2025-01-01", "2024-12-31", "2024-12-30", "2024-12-29", "2024-12-28"),
81
+ title = c(
82
+ "Political Unrest Reported in Venezuela: Opposition Rally",
83
+ "Economic Crisis Deepens as Currency Devaluation Continues",
84
+ "Nuclear Negotiations Stall Amid Rising Tensions",
85
+ "New Sanctions Announced by Western Nations",
86
+ "Humanitarian Situation Worsens in Northern Regions",
87
+ "Military Junta Tightens Control Over Media",
88
+ "Currency Volatility Raises Investor Concerns",
89
+ "US-China Trade Tensions Escalate Over Tariffs",
90
+ "Energy Export Restrictions Create Market Uncertainty",
91
+ "Earthquake Preparedness Measures Enhanced",
92
+ "Mass Protests Enter Second Week in Caracas",
93
+ "Oil Production Disrupted by Infrastructure Issues",
94
+ "Refugee Crisis Intensifies at Border Regions",
95
+ "Ceasefire Negotiations Show Signs of Progress",
96
+ "Security Concerns Rise After Attack on Aid Workers",
97
+ "Missile Test Condemned by International Community",
98
+ "Political Transition Faces New Challenges",
99
+ "Economic Growth Projections Revised Downward",
100
+ "Coalition Government Navigates Policy Disputes",
101
+ "Federal Reserve Signals Cautious Approach"
102
+ ),
103
+ category = c("政変の予兆", "経済危機", "地政学リスク", "制裁", "人道危機",
104
+ "政変の予兆", "経済危機", "貿易摩擦", "エネルギー", "自然災害",
105
+ "政変の予兆", "経��危機", "人道危機", "紛争", "テロ関連",
106
+ "地政学リスク", "政変の予兆", "経済危機", "政治", "経済政策"),
107
+ what = c(
108
+ "ベネズエラで大規模な反政府デモが発生。野党支持者数万人がカラカス中心部に集結。",
109
+ "ボリバル通貨が対ドルで過去最安値を更新。インフレ率が年率200%を超える見通し。",
110
+ "イランと西側諸国の核協議が決裂。両者の立場の隔たりが鮮明に。",
111
+ "EUがイランに対する追加制裁を発表。金融セクターが主な対象。",
112
+ "北部地域で食料・医療品の不足が深刻化。国連が緊急支援を要請。",
113
+ "軍事政権がソーシャルメディアへのアクセスを制限。報道の自由に懸念。",
114
+ "レアルが週間で8%下落。中央銀行が市場介入を実施。",
115
+ "米国が中国製品への追加関税を発表。中国側も報復措置を示唆。",
116
+ "ロシアがガス輸出制限を示唆。欧州のエネルギー価格が急騰。",
117
+ "南海トラフ地震への備えとして、政府が新たな防災計画を発表。",
118
+ "カラカスでの抗議活動が2週目に突入。治安部隊との衝突で負傷者。",
119
+ "イラン南部の製油所で火災発生。原油生産に影響。",
120
+ "シリア北部から数千人規模の難民がトルコ国境に殺到。",
121
+ "イエメン和平交渉で一時停戦に合意。持続性には疑問符。",
122
+ "アフガニスタンで援助団体の車列が襲撃される。職員2名が死亡。",
123
+ "北朝鮮が短距離弾道ミサイルを発射。日本海に落下。",
124
+ "リビア暫定政府と東部勢力の対話が行き詰まり。",
125
+ "インドの製造業PMIが予想を下回る。景気減速懸念が強まる。",
126
+ "ドイツ連立政権内で気候政策を巡り対立。",
127
+ "FRBが金利据え置きを決定。年内の利下げ観測が後退。"
128
+ ),
129
+ cause = c(
130
+ "2024年大統領選挙の結果を巡る対立が激化。野党側は選挙不正を主張し、国際社会からも懸念の声。マドゥロ政権への不満が限界に達しつつある。",
131
+ "米国の経済制裁による外貨収入の減少と、政府の財政政策の失敗が重なり、通貨危機が深刻化。国民の購買力が著しく低下。",
132
+ "イラン側がウラン濃縮活動の縮小を拒否。西側諸国は制裁解除の条件として核開発の完全な透明性を要求しており、双方の要求が折り合わず。",
133
+ "イランの中東地域での軍事活動とミサイル開発を問題視。ドローン供与などがエスカレーションの一因。",
134
+ "長期化する内戦と経済制裁の影響で、民間インフラが崩壊。医療システムの機能不全が深刻な人道危機を招く。",
135
+ "2021年のクーデター以降、民主化運動の弾圧が継続。国際社会からの孤立が深まる中、情報統制を強化。",
136
+ "米国の金利高止まりと中国経済の減速を背景に、新興国通貨全般が下落圧力に。ブラジル固有の財政問題も重荷。",
137
+ "半導体やEVを巡る技術覇権争いが激化。両国の経済的相互依存関係が政治的緊張により複雑化。",
138
+ "ウクライナ紛争の長期化に伴い、ロシアがエネルギーを外交カードとして使用。欧州のロシア依存度の高さが露呈。",
139
+ "2024年の能登半島地震を教訓に、政府が防災体制の見直しを加速。インフラ強靭化に多額の予算を投入予定。",
140
+ "選挙結果を認めない野党支持者と、政権維持を図る与党支持者の対立が先鋭化。国際社会の介入を求める声も。",
141
+ "老朽化したインフラと投資不足が原因。制裁下でメンテナンス部品の調達が困難になっている実態。",
142
+ "北部での軍事衝突再発と、食料危機の深刻化が人々を避難に駆り立てる。トルコは受け入れ能力の限界を表明。",
143
+ "国連の仲介努力とサウジアラビアの外交政策転換が合意に寄与。しかし過去の停戦も短期間で崩壊した経緯あり。",
144
+ "タリバン政権下での治安悪化と、反政府勢力の活動活発化が背景。外国人・援助関係者が標的にされるケースが増加。",
145
+ "米韓合同軍事演習への対抗措置として実施。核・ミサイル開発の進展をアピールする狙いも。",
146
+ "東西の主要勢力間の権力闘争と、石油収入の配分を巡る対立が根深い。国際社会の調停努力も限定的効果。",
147
+ "世界経済の減速と国内の構造改革の遅れが影響。特にIT・自動車セクターの輸出減少が顕著。",
148
+ "緑の党と自由民主党の政策スタンスの違いが表面化。2025年の連邦議会選挙を控え、各党が独自色を強調。",
149
+ "インフレ率の高止まりと雇用市場の堅調���を理由に、FRBは慎重姿勢を維持。市場の利下げ期待との乖離。"
150
+ ),
151
+ impact_score = c(8, 7, 9, 7, 6, 6, 5, 8, 9, 3,
152
+ 8, 6, 7, 5, 7, 8, 5, 4, 3, 4),
153
+ source = rep(c("Reuters", "Bloomberg", "AP News", "AFP", "BBC"), 4),
154
+ stringsAsFactors = FALSE
155
+ )
156
+
157
+ # =============================================================================
158
+ # UI定義
159
+ # =============================================================================
160
+
161
+ ui <- page_navbar(
162
+ title = tags$span(
163
+ style = "font-weight: 700; font-size: 1.1rem;",
164
+ tags$span(style = "color: #FF6B35;", "◆"),
165
+ " リスクモニタリングシステム"
166
+ ),
167
+ id = "navbar",
168
+ theme = bs_theme(
169
+ version = 5,
170
+ bootswatch = "flatly",
171
+ primary = "#1A365D",
172
+ secondary = "#718096",
173
+ success = "#38A169",
174
+ danger = "#E53E3E",
175
+ warning = "#DD6B20",
176
+ info = "#3182CE",
177
+ "navbar-bg" = "#1A365D",
178
+ "body-bg" = "#F7FAFC",
179
+ base_font = font_google("Noto Sans JP"),
180
+ heading_font = font_google("Noto Sans JP"),
181
+ font_scale = 0.9
182
+ ),
183
+
184
+ header = tags$head(
185
+ tags$style(HTML("
186
+ :root {
187
+ --risk-high: #E53E3E;
188
+ --risk-medium: #DD6B20;
189
+ --risk-low: #38A169;
190
+ --accent: #FF6B35;
191
+ }
192
+
193
+ .navbar {
194
+ box-shadow: 0 2px 10px rgba(0,0,0,0.1);
195
+ }
196
+
197
+ .card {
198
+ border: none;
199
+ border-radius: 12px;
200
+ box-shadow: 0 4px 20px rgba(0,0,0,0.08);
201
+ transition: transform 0.2s, box-shadow 0.2s;
202
+ }
203
+
204
+ .card:hover {
205
+ transform: translateY(-2px);
206
+ box-shadow: 0 8px 30px rgba(0,0,0,0.12);
207
+ }
208
+
209
+ .card-header {
210
+ background: linear-gradient(135deg, #1A365D 0%, #2D4A7C 100%);
211
+ color: white;
212
+ font-weight: 600;
213
+ border-radius: 12px 12px 0 0 !important;
214
+ padding: 1rem 1.25rem;
215
+ }
216
+
217
+ .score-high { color: var(--risk-high); font-weight: 700; }
218
+ .score-medium { color: var(--risk-medium); font-weight: 700; }
219
+ .score-low { color: var(--risk-low); font-weight: 700; }
220
+
221
+ .country-list-item {
222
+ padding: 12px 16px;
223
+ border-bottom: 1px solid #E2E8F0;
224
+ cursor: pointer;
225
+ transition: all 0.2s;
226
+ }
227
+
228
+ .country-list-item:hover {
229
+ background: #EDF2F7;
230
+ }
231
+
232
+ .country-list-item.active {
233
+ background: linear-gradient(90deg, #FF6B35 0%, #FF8C5A 100%);
234
+ color: white;
235
+ font-weight: 600;
236
+ }
237
+
238
+ .news-card {
239
+ background: white;
240
+ border-radius: 8px;
241
+ padding: 16px;
242
+ margin-bottom: 12px;
243
+ border-left: 4px solid var(--accent);
244
+ box-shadow: 0 2px 8px rgba(0,0,0,0.06);
245
+ }
246
+
247
+ .news-title {
248
+ font-weight: 600;
249
+ color: #1A365D;
250
+ margin-bottom: 8px;
251
+ }
252
+
253
+ .news-meta {
254
+ font-size: 0.8rem;
255
+ color: #718096;
256
+ }
257
+
258
+ .category-badge {
259
+ display: inline-block;
260
+ padding: 4px 10px;
261
+ border-radius: 20px;
262
+ font-size: 0.75rem;
263
+ font-weight: 600;
264
+ margin-right: 8px;
265
+ }
266
+
267
+ .category-政変の予兆 { background: #FED7D7; color: #C53030; }
268
+ .category-経済危機 { background: #FEEBC8; color: #C05621; }
269
+ .category-地政学リスク { background: #E9D8FD; color: #6B46C1; }
270
+ .category-テロ関連 { background: #FED7E2; color: #B83280; }
271
+ .category-人道危機 { background: #C6F6D5; color: #276749; }
272
+ .category-制裁 { background: #BEE3F8; color: #2B6CB0; }
273
+ .category-紛争 { background: #FEEBC8; color: #C05621; }
274
+ .category-貿易摩擦 { background: #E9D8FD; color: #6B46C1; }
275
+ .category-エネルギー { background: #FEFCBF; color: #975A16; }
276
+ .category-自然災害 { background: #C6F6D5; color: #276749; }
277
+ .category-政治 { background: #BEE3F8; color: #2B6CB0; }
278
+ .category-経済政策 { background: #E2E8F0; color: #4A5568; }
279
+
280
+ .chat-container {
281
+ height: 500px;
282
+ overflow-y: auto;
283
+ padding: 16px;
284
+ background: #F7FAFC;
285
+ border-radius: 8px;
286
+ }
287
+
288
+ .chat-message {
289
+ margin-bottom: 16px;
290
+ max-width: 85%;
291
+ }
292
+
293
+ .chat-message.user {
294
+ margin-left: auto;
295
+ background: linear-gradient(135deg, #1A365D 0%, #2D4A7C 100%);
296
+ color: white;
297
+ padding: 12px 16px;
298
+ border-radius: 16px 16px 4px 16px;
299
+ }
300
+
301
+ .chat-message.assistant {
302
+ background: white;
303
+ padding: 12px 16px;
304
+ border-radius: 16px 16px 16px 4px;
305
+ box-shadow: 0 2px 8px rgba(0,0,0,0.06);
306
+ border-left: 3px solid var(--accent);
307
+ }
308
+
309
+ .metric-card {
310
+ background: white;
311
+ border-radius: 12px;
312
+ padding: 20px;
313
+ text-align: center;
314
+ box-shadow: 0 4px 15px rgba(0,0,0,0.08);
315
+ }
316
+
317
+ .metric-value {
318
+ font-size: 2.5rem;
319
+ font-weight: 700;
320
+ line-height: 1;
321
+ }
322
+
323
+ .metric-label {
324
+ color: #718096;
325
+ font-size: 0.85rem;
326
+ margin-top: 8px;
327
+ }
328
+
329
+ .trend-up { color: var(--risk-high); }
330
+ .trend-down { color: var(--risk-low); }
331
+ .trend-stable { color: #718096; }
332
+
333
+ .detail-section {
334
+ background: #F7FAFC;
335
+ border-radius: 8px;
336
+ padding: 16px;
337
+ margin-top: 16px;
338
+ }
339
+
340
+ .detail-label {
341
+ font-weight: 600;
342
+ color: #1A365D;
343
+ margin-bottom: 8px;
344
+ display: flex;
345
+ align-items: center;
346
+ }
347
+
348
+ .detail-label::before {
349
+ content: '';
350
+ width: 4px;
351
+ height: 20px;
352
+ background: var(--accent);
353
+ margin-right: 10px;
354
+ border-radius: 2px;
355
+ }
356
+
357
+ .leaflet-container {
358
+ border-radius: 8px;
359
+ }
360
+
361
+ .selectize-input {
362
+ border-radius: 8px !important;
363
+ }
364
+
365
+ #send_btn {
366
+ background: linear-gradient(135deg, #FF6B35 0%, #FF8C5A 100%);
367
+ border: none;
368
+ border-radius: 8px;
369
+ font-weight: 600;
370
+ }
371
+
372
+ #send_btn:hover {
373
+ background: linear-gradient(135deg, #E55A25 0%, #FF7B4A 100%);
374
+ }
375
+
376
+ .page-header {
377
+ background: linear-gradient(135deg, #1A365D 0%, #2D4A7C 100%);
378
+ color: white;
379
+ padding: 24px;
380
+ border-radius: 12px;
381
+ margin-bottom: 24px;
382
+ }
383
+
384
+ .page-header h2 {
385
+ margin: 0;
386
+ font-weight: 700;
387
+ }
388
+
389
+ .page-header p {
390
+ margin: 8px 0 0 0;
391
+ opacity: 0.9;
392
+ }
393
+ "))
394
+ ),
395
+
396
+ # ----- ダッシュボードタブ -----
397
+ nav_panel(
398
+ title = "ダッシュボード",
399
+ icon = icon("dashboard"),
400
+
401
+ div(
402
+ class = "page-header",
403
+ h2("グローバルリスク概況"),
404
+ p("国別の政治・治安リスクをリアルタイムで監視")
405
+ ),
406
+
407
+ layout_columns(
408
+ col_widths = c(3, 9),
409
+
410
+ # 左サイドバー: 国別リスト
411
+ card(
412
+ card_header("国別リスト"),
413
+ div(
414
+ style = "max-height: 600px; overflow-y: auto;",
415
+ uiOutput("country_list_ui")
416
+ )
417
+ ),
418
+
419
+ # メインコンテンツ
420
+ layout_columns(
421
+ col_widths = c(12, 12),
422
+
423
+ # 上部: マップとメトリクス
424
+ layout_columns(
425
+ col_widths = c(8, 4),
426
+ card(
427
+ card_header("世界リスクマップ"),
428
+ leafletOutput("risk_map", height = "350px")
429
+ ),
430
+ layout_columns(
431
+ col_widths = 12,
432
+ div(
433
+ class = "metric-card",
434
+ div(class = "metric-value", style = "color: #E53E3E;", textOutput("high_risk_count")),
435
+ div(class = "metric-label", "高リスク国 (スコア≥70)")
436
+ ),
437
+ div(
438
+ class = "metric-card",
439
+ div(class = "metric-value", style = "color: #DD6B20;", textOutput("medium_risk_count")),
440
+ div(class = "metric-label", "中リスク国 (40-69)")
441
+ ),
442
+ div(
443
+ class = "metric-card",
444
+ div(class = "metric-value", style = "color: #38A169;", textOutput("low_risk_count")),
445
+ div(class = "metric-label", "低リスク国 (<40)")
446
+ )
447
+ )
448
+ ),
449
+
450
+ # 下部: チャートとニュース
451
+ layout_columns(
452
+ col_widths = c(6, 6),
453
+ card(
454
+ card_header(textOutput("chart_title")),
455
+ plotlyOutput("risk_chart", height = "280px")
456
+ ),
457
+ card(
458
+ card_header("最新ニュースサマリー"),
459
+ div(
460
+ style = "max-height: 280px; overflow-y: auto;",
461
+ uiOutput("news_summary_ui")
462
+ )
463
+ )
464
+ )
465
+ )
466
+ )
467
+ ),
468
+
469
+ # ----- 因果分析タブ -----
470
+ nav_panel(
471
+ title = "因果分析",
472
+ icon = icon("project-diagram"),
473
+
474
+ div(
475
+ class = "page-header",
476
+ h2("因果関係の提示"),
477
+ p("「何が起きたか(What)」と「なぜ起きたか(Cause)」を特定")
478
+ ),
479
+
480
+ layout_columns(
481
+ col_widths = c(4, 8),
482
+
483
+ # フィルター
484
+ card(
485
+ card_header("分析条件"),
486
+ selectInput(
487
+ "analysis_country",
488
+ "対象国を選択",
489
+ choices = unique(country_data$country_jp),
490
+ selected = "ベネズエラ"
491
+ ),
492
+ selectInput(
493
+ "analysis_category",
494
+ "カテゴリ",
495
+ choices = c("すべて", unique(news_data$category)),
496
+ selected = "すべて"
497
+ ),
498
+ dateRangeInput(
499
+ "date_range",
500
+ "期間",
501
+ start = "2024-12-01",
502
+ end = "2025-01-11",
503
+ language = "ja"
504
+ ),
505
+ hr(),
506
+ div(
507
+ class = "metric-card",
508
+ div(
509
+ class = "metric-value",
510
+ style = "font-size: 1.8rem;",
511
+ textOutput("selected_country_score")
512
+ ),
513
+ div(class = "metric-label", "現在のリスクスコア"),
514
+ div(
515
+ style = "margin-top: 10px;",
516
+ uiOutput("score_trend_indicator")
517
+ )
518
+ )
519
+ ),
520
+
521
+ # 分析結果
522
+ layout_columns(
523
+ col_widths = 12,
524
+ card(
525
+ card_header("関連ニュース詳細"),
526
+ div(
527
+ style = "max-height: 600px; overflow-y: auto;",
528
+ uiOutput("detailed_news_ui")
529
+ )
530
+ )
531
+ )
532
+ )
533
+ ),
534
+
535
+ # ----- 分析アシスタントタブ -----
536
+ nav_panel(
537
+ title = "分析アシスタント",
538
+ icon = icon("robot"),
539
+
540
+ div(
541
+ class = "page-header",
542
+ h2("分析アシスタント"),
543
+ p("リスクに関する質問にAIがお答えします")
544
+ ),
545
+
546
+ layout_columns(
547
+ col_widths = c(8, 4),
548
+
549
+ card(
550
+ card_header("チャット"),
551
+ div(
552
+ id = "chat_container",
553
+ class = "chat-container",
554
+ uiOutput("chat_messages_ui")
555
+ ),
556
+ hr(),
557
+ layout_columns(
558
+ col_widths = c(10, 2),
559
+ textInput(
560
+ "user_message",
561
+ NULL,
562
+ placeholder = "質問を入力してください(例:なぜベネズエラのスコアが上がった?)",
563
+ width = "100%"
564
+ ),
565
+ actionButton(
566
+ "send_btn",
567
+ "送信",
568
+ icon = icon("paper-plane"),
569
+ class = "btn-primary",
570
+ width = "100%"
571
+ )
572
+ )
573
+ ),
574
+
575
+ card(
576
+ card_header("よくある質問"),
577
+ div(
578
+ style = "padding: 8px;",
579
+ actionLink("q1", "なぜベネズエラのスコアが上がった?", style = "display: block; padding: 10px; color: #1A365D;"),
580
+ hr(style = "margin: 5px 0;"),
581
+ actionLink("q2", "イランの最新リスク状況は?", style = "display: block; padding: 10px; color: #1A365D;"),
582
+ hr(style = "margin: 5px 0;"),
583
+ actionLink("q3", "政変の予兆がある国は?", style = "display: block; padding: 10px; color: #1A365D;"),
584
+ hr(style = "margin: 5px 0;"),
585
+ actionLink("q4", "中東地域のリスク概況を教えて", style = "display: block; padding: 10px; color: #1A365D;"),
586
+ hr(style = "margin: 5px 0;"),
587
+ actionLink("q5", "今週スコアが急上昇した国は?", style = "display: block; padding: 10px; color: #1A365D;")
588
+ )
589
+ )
590
+ )
591
+ ),
592
+
593
+ # ----- リスクランキングタブ -----
594
+ nav_panel(
595
+ title = "リスクランキング",
596
+ icon = icon("list-ol"),
597
+
598
+ div(
599
+ class = "page-header",
600
+ h2("国別リスクランキング"),
601
+ p("200ヶ国以上の中で「今、どこを気にすべきか」を優先順位付け")
602
+ ),
603
+
604
+ layout_columns(
605
+ col_widths = c(6, 6),
606
+ card(
607
+ card_header("リスクスコア上位国"),
608
+ plotlyOutput("ranking_chart", height = "500px")
609
+ ),
610
+ card(
611
+ card_header("全国データ一覧"),
612
+ DTOutput("country_table")
613
+ )
614
+ )
615
+ ),
616
+
617
+ nav_spacer(),
618
+ nav_item(
619
+ tags$span(
620
+ style = "color: rgba(255,255,255,0.7); font-size: 0.8rem;",
621
+ "プロトタイプ v0.1 "
622
+ )
623
+ )
624
+ )
625
+
626
+ # =============================================================================
627
+ # Server定義
628
+ # =============================================================================
629
+
630
+ server <- function(input, output, session) {
631
+
632
+ # リアクティブ値
633
+ selected_country <- reactiveVal("Venezuela")
634
+ chat_history <- reactiveVal(list(
635
+ list(
636
+ role = "assistant",
637
+ content = "リスクモニタリングアシスタントです。国別のリスクスコアや、スコア変動の要因についてお答えします。何でもお聞きください。"
638
+ )
639
+ ))
640
+
641
+ # ----- 国リストUI -----
642
+ output$country_list_ui <- renderUI({
643
+ sorted_data <- country_data %>% arrange(desc(risk_score))
644
+
645
+ lapply(1:nrow(sorted_data), function(i) {
646
+ row <- sorted_data[i, ]
647
+ score_class <- if (row$risk_score >= 70) "score-high"
648
+ else if (row$risk_score >= 40) "score-medium"
649
+ else "score-low"
650
+
651
+ active_class <- if (row$country == selected_country()) "active" else ""
652
+
653
+ trend_icon <- switch(
654
+ row$trend,
655
+ "up" = icon("arrow-up", class = "trend-up"),
656
+ "down" = icon("arrow-down", class = "trend-down"),
657
+ icon("minus", class = "trend-stable")
658
+ )
659
+
660
+ div(
661
+ class = paste("country-list-item", active_class),
662
+ onclick = sprintf("Shiny.setInputValue('clicked_country', '%s', {priority: 'event'})", row$country),
663
+ div(
664
+ style = "display: flex; justify-content: space-between; align-items: center;",
665
+ div(
666
+ div(style = "font-weight: 600;", row$country_jp),
667
+ div(style = "font-size: 0.8rem; color: #718096;", row$country)
668
+ ),
669
+ div(
670
+ style = "display: flex; align-items: center; gap: 8px;",
671
+ span(class = score_class, row$risk_score),
672
+ trend_icon
673
+ )
674
+ )
675
+ )
676
+ })
677
+ })
678
+
679
+ # クリックイベント
680
+ observeEvent(input$clicked_country, {
681
+ selected_country(input$clicked_country)
682
+ })
683
+
684
+ # ----- リスクマップ -----
685
+ output$risk_map <- renderLeaflet({
686
+ leaflet(country_data) %>%
687
+ addProviderTiles(providers$CartoDB.Positron) %>%
688
+ setView(lng = 20, lat = 20, zoom = 2) %>%
689
+ addCircleMarkers(
690
+ ~lng, ~lat,
691
+ radius = ~sqrt(risk_score) * 1.5,
692
+ color = ~ifelse(risk_score >= 70, "#E53E3E",
693
+ ifelse(risk_score >= 40, "#DD6B20", "#38A169")),
694
+ fillOpacity = 0.7,
695
+ stroke = TRUE,
696
+ weight = 2,
697
+ popup = ~paste0(
698
+ "<strong>", country_jp, "</strong><br>",
699
+ "リスクスコア: <span style='color:",
700
+ ifelse(risk_score >= 70, "#E53E3E",
701
+ ifelse(risk_score >= 40, "#DD6B20", "#38A169")),
702
+ "; font-weight: bold;'>", risk_score, "</span><br>",
703
+ "地域: ", region
704
+ )
705
+ )
706
+ })
707
+
708
+ # マップの選択国ハイライト
709
+ observe({
710
+ current <- selected_country()
711
+ current_data <- country_data %>% filter(country == current)
712
+
713
+ leafletProxy("risk_map") %>%
714
+ clearGroup("highlight") %>%
715
+ addCircleMarkers(
716
+ data = current_data,
717
+ ~lng, ~lat,
718
+ radius = 20,
719
+ color = "#FF6B35",
720
+ fillOpacity = 0,
721
+ stroke = TRUE,
722
+ weight = 3,
723
+ group = "highlight"
724
+ )
725
+ })
726
+
727
+ # ----- メトリクス -----
728
+ output$high_risk_count <- renderText({
729
+ sum(country_data$risk_score >= 70)
730
+ })
731
+
732
+ output$medium_risk_count <- renderText({
733
+ sum(country_data$risk_score >= 40 & country_data$risk_score < 70)
734
+ })
735
+
736
+ output$low_risk_count <- renderText({
737
+ sum(country_data$risk_score < 40)
738
+ })
739
+
740
+ # ----- リスクチャート -----
741
+ output$chart_title <- renderText({
742
+ current <- selected_country()
743
+ current_jp <- country_data$country_jp[country_data$country == current]
744
+ paste0(current_jp, " リスクスコア推移")
745
+ })
746
+
747
+ output$risk_chart <- renderPlotly({
748
+ current <- selected_country()
749
+ base_score <- country_data$risk_score[country_data$country == current]
750
+ ts_data <- generate_time_series(current, base_score)
751
+
752
+ plot_ly(ts_data, x = ~date, y = ~score, type = 'scatter', mode = 'lines',
753
+ line = list(color = '#1A365D', width = 2),
754
+ fill = 'tozeroy', fillcolor = 'rgba(26, 54, 93, 0.1)') %>%
755
+ layout(
756
+ xaxis = list(title = "", gridcolor = '#E2E8F0'),
757
+ yaxis = list(title = "スコア", range = c(0, 100), gridcolor = '#E2E8F0'),
758
+ margin = list(t = 10, b = 40),
759
+ hovermode = 'x unified',
760
+ plot_bgcolor = 'rgba(0,0,0,0)',
761
+ paper_bgcolor = 'rgba(0,0,0,0)'
762
+ ) %>%
763
+ add_annotations(
764
+ x = max(ts_data$date) - 7,
765
+ y = max(ts_data$score[ts_data$date > max(ts_data$date) - 14]),
766
+ text = if(base_score > 70) "⚠️ Spike" else "",
767
+ showarrow = FALSE,
768
+ font = list(color = "#E53E3E", size = 14)
769
+ )
770
+ })
771
+
772
+ # ----- ニュースサマリー -----
773
+ output$news_summary_ui <- renderUI({
774
+ current <- selected_country()
775
+ filtered_news <- news_data %>%
776
+ filter(country == current) %>%
777
+ arrange(desc(date)) %>%
778
+ head(5)
779
+
780
+ if (nrow(filtered_news) == 0) {
781
+ return(div(style = "padding: 20px; color: #718096;", "ニュースデータがありません"))
782
+ }
783
+
784
+ lapply(1:nrow(filtered_news), function(i) {
785
+ row <- filtered_news[i, ]
786
+ div(
787
+ class = "news-card",
788
+ div(
789
+ class = "news-title",
790
+ row$title
791
+ ),
792
+ div(
793
+ class = "news-meta",
794
+ span(class = paste0("category-badge category-", row$category), row$category),
795
+ span(row$date),
796
+ span(" | "),
797
+ span(row$source)
798
+ )
799
+ )
800
+ })
801
+ })
802
+
803
+ # ----- 因果分析: 選択国スコア -----
804
+ output$selected_country_score <- renderText({
805
+ country_en <- country_data$country[country_data$country_jp == input$analysis_country]
806
+ score <- country_data$risk_score[country_data$country == country_en]
807
+ score
808
+ })
809
+
810
+ output$score_trend_indicator <- renderUI({
811
+ country_en <- country_data$country[country_data$country_jp == input$analysis_country]
812
+ trend <- country_data$trend[country_data$country == country_en]
813
+
814
+ if (trend == "up") {
815
+ div(style = "color: #E53E3E;", icon("arrow-up"), " 上昇傾向")
816
+ } else if (trend == "down") {
817
+ div(style = "color: #38A169;", icon("arrow-down"), " 下降傾向")
818
+ } else {
819
+ div(style = "color: #718096;", icon("minus"), " 横ばい")
820
+ }
821
+ })
822
+
823
+ # ----- 因果分析: 詳細ニュース -----
824
+ output$detailed_news_ui <- renderUI({
825
+ country_en <- country_data$country[country_data$country_jp == input$analysis_country]
826
+
827
+ filtered <- news_data %>%
828
+ filter(country == country_en)
829
+
830
+ if (input$analysis_category != "すべて") {
831
+ filtered <- filtered %>% filter(category == input$analysis_category)
832
+ }
833
+
834
+ filtered <- filtered %>%
835
+ filter(as.Date(date) >= input$date_range[1] & as.Date(date) <= input$date_range[2]) %>%
836
+ arrange(desc(date))
837
+
838
+ if (nrow(filtered) == 0) {
839
+ return(div(
840
+ style = "padding: 40px; text-align: center; color: #718096;",
841
+ icon("search", style = "font-size: 3rem; margin-bottom: 16px;"),
842
+ div("条件に一致するニュースが見つかりませんでした")
843
+ ))
844
+ }
845
+
846
+ lapply(1:nrow(filtered), function(i) {
847
+ row <- filtered[i, ]
848
+ div(
849
+ style = "background: white; border-radius: 12px; padding: 20px; margin-bottom: 16px; box-shadow: 0 2px 10px rgba(0,0,0,0.06);",
850
+
851
+ div(
852
+ style = "display: flex; justify-content: space-between; align-items: start; margin-bottom: 16px;",
853
+ div(
854
+ span(class = paste0("category-badge category-", row$category), row$category),
855
+ span(style = "color: #718096; font-size: 0.85rem;", row$date, " | ", row$source)
856
+ ),
857
+ div(
858
+ style = "background: #FED7D7; color: #C53030; padding: 4px 12px; border-radius: 20px; font-size: 0.8rem; font-weight: 600;",
859
+ paste0("影響度: ", row$impact_score, "/10")
860
+ )
861
+ ),
862
+
863
+ div(
864
+ style = "font-weight: 600; font-size: 1.1rem; color: #1A365D; margin-bottom: 16px;",
865
+ row$title
866
+ ),
867
+
868
+ div(
869
+ class = "detail-section",
870
+ div(class = "detail-label", "What(何が起きたか)"),
871
+ p(style = "margin: 0; color: #4A5568; line-height: 1.7;", row$what)
872
+ ),
873
+
874
+ div(
875
+ class = "detail-section",
876
+ style = "margin-top: 12px;",
877
+ div(class = "detail-label", "Cause(なぜ起きたか)"),
878
+ p(style = "margin: 0; color: #4A5568; line-height: 1.7;", row$cause)
879
+ )
880
+ )
881
+ })
882
+ })
883
+
884
+ # ----- チャットアシスタント -----
885
+ output$chat_messages_ui <- renderUI({
886
+ history <- chat_history()
887
+
888
+ lapply(history, function(msg) {
889
+ div(
890
+ class = paste("chat-message", msg$role),
891
+ HTML(msg$content)
892
+ )
893
+ })
894
+ })
895
+
896
+ # チャット送信
897
+ send_message <- function(user_msg) {
898
+ if (nchar(trimws(user_msg)) == 0) return()
899
+
900
+ history <- chat_history()
901
+ history <- c(history, list(list(role = "user", content = user_msg)))
902
+
903
+ # シンプルな応答生成(デモ用)
904
+ response <- generate_response(user_msg)
905
+ history <- c(history, list(list(role = "assistant", content = response)))
906
+
907
+ chat_history(history)
908
+ updateTextInput(session, "user_message", value = "")
909
+ }
910
+
911
+ observeEvent(input$send_btn, {
912
+ send_message(input$user_message)
913
+ })
914
+
915
+ # よくある質問のクリック
916
+ observeEvent(input$q1, { send_message("なぜベネズエラのスコアが上がった?") })
917
+ observeEvent(input$q2, { send_message("イランの最新リスク状況は?") })
918
+ observeEvent(input$q3, { send_message("政変の予兆がある国は?") })
919
+ observeEvent(input$q4, { send_message("中東地域のリスク概況を教えて") })
920
+ observeEvent(input$q5, { send_message("今週スコアが急上昇した国は?") })
921
+
922
+ # 応答生成(デモ用のルールベース)
923
+ generate_response <- function(query) {
924
+ query_lower <- tolower(query)
925
+
926
+ if (grepl("ベネズエラ", query) && grepl("スコア|上が|なぜ", query)) {
927
+ return(paste0(
928
+ "<strong>ベネズエラのリスクスコア上昇要因</strong><br><br>",
929
+ "ベネズエラのリスクスコアが上昇した主な要因は以下の通りです:<br><br>",
930
+ "📰 <strong>政変の予兆</strong><br>",
931
+ "2024年大統領選挙の結果を巡る対立が激化しており、野党支持者による大規模な反政府デモがカラカス中心部で発生しています。",
932
+ "国際社会からも選挙の正当性に懸念の声が上がっています。<br><br>",
933
+ "📰 <strong>経済危機</strong><br>",
934
+ "ボリバル通貨が対ドルで過去最安値を更新し、インフレ率が年率200%を超える見通しです。",
935
+ "米国の経済制裁による外貨収入の減少と政府の財政政策の失敗が重なっています。<br><br>",
936
+ "📎 関連記事:<a href='#'>Political Unrest Reported in Venezuela (2025-01-11)</a>"
937
+ ))
938
+ }
939
+
940
+ if (grepl("イラン", query)) {
941
+ return(paste0(
942
+ "<strong>イランの最新リスク状況</strong><br><br>",
943
+ "現在のリスクスコア: <span style='color: #E53E3E; font-weight: bold;'>92</span> (高リスク)<br><br>",
944
+ "📰 <strong>主要リスク要因</strong><br>",
945
+ "• 西側諸国との核協議が決裂状態<br>",
946
+ "• EUによる追加経済制裁の発動<br>",
947
+ "• 中東地域での軍事活動の活発化<br><br>",
948
+ "特にウラン濃縮活動の継続と、ドローン供与などの軍事支援が国際社会の懸念を高めています。"
949
+ ))
950
+ }
951
+
952
+ if (grepl("政変", query) && grepl("予兆|国", query)) {
953
+ return(paste0(
954
+ "<strong>政変の予兆が検知されている国</strong><br><br>",
955
+ "現在、以下の国で「政変の予兆」カテゴリのニュースが検知されています:<br><br>",
956
+ "🔴 <strong>ベネズエラ</strong> (スコア: 95)<br>",
957
+ "大規模な反政府デモが継続中。選挙結果を巡る対立が先鋭化。<br><br>",
958
+ "🔴 <strong>ミャンマー</strong> (スコア: 78)<br>",
959
+ "軍事政権による情報統制が強化。民主化運動への弾圧継続。<br><br>",
960
+ "🟠 <strong>リビア</strong> (スコア: 72)<br>",
961
+ "暫定政府と東部勢力の対話が行き詰まり。"
962
+ ))
963
+ }
964
+
965
+ if (grepl("中東", query)) {
966
+ return(paste0(
967
+ "<strong>中東地域のリスク概況</strong><br><br>",
968
+ "中東地域は引き続き高リスク状態が続いています:<br><br>",
969
+ "| 国名 | スコア | 傾向 |<br>",
970
+ "|------|--------|------|<br>",
971
+ "| イラン | 92 | ↑ |<br>",
972
+ "| シリア | 88 | → |<br>",
973
+ "| イエメン | 85 | ↑ |<br><br>",
974
+ "📰 <strong>主要トピック</strong><br>",
975
+ "• イラン核協議の行き詰まり<br>",
976
+ "• イエメン和平交渉の進展(ただし持続性に疑問)<br>",
977
+ "• シリア北部での難民危機の深刻化"
978
+ ))
979
+ }
980
+
981
+ if (grepl("急上昇|上昇|今週", query)) {
982
+ return(paste0(
983
+ "<strong>今週スコアが急上昇した国</strong><br><br>",
984
+ "過去7日間でスコアが5ポイント以上上昇した国:<br><br>",
985
+ "1️⃣ <strong>ベネズエラ</strong> +12pt (83→95)<br>",
986
+ "要因:大規模反政府デモ、通貨危機の深刻化<br><br>",
987
+ "2️⃣ <strong>イラン</strong> +7pt (85→92)<br>",
988
+ "要因:核協議決裂、追加制裁の発動<br><br>",
989
+ "3️⃣ <strong>イエメン</strong> +5pt (80→85)<br>",
990
+ "要因:停戦交渉の不透明感"
991
+ ))
992
+ }
993
+
994
+ # デフォルト応答
995
+ return(paste0(
996
+ "ご質問ありがとうございます。<br><br>",
997
+ "現在のシステムでは以下の情報を提供できます:<br>",
998
+ "• 国別リスクスコアとその推移<br>",
999
+ "• スコア変動の要因となったニュース<br>",
1000
+ "• カテゴリ別(政変、テロ、経済危機等)の分析<br>",
1001
+ "• 地域別のリスク概況<br><br>",
1002
+ "具体的な国名や地域を含めてご質問いただくと、より詳細な情報をお伝えできます。"
1003
+ ))
1004
+ }
1005
+
1006
+ # ----- ランキングチャート -----
1007
+ output$ranking_chart <- renderPlotly({
1008
+ top_countries <- country_data %>%
1009
+ arrange(desc(risk_score)) %>%
1010
+ head(15)
1011
+
1012
+ colors <- sapply(top_countries$risk_score, function(s) {
1013
+ if (s >= 70) "#E53E3E"
1014
+ else if (s >= 40) "#DD6B20"
1015
+ else "#38A169"
1016
+ })
1017
+
1018
+ plot_ly(
1019
+ top_countries,
1020
+ y = ~reorder(country_jp, risk_score),
1021
+ x = ~risk_score,
1022
+ type = 'bar',
1023
+ orientation = 'h',
1024
+ marker = list(color = colors),
1025
+ text = ~risk_score,
1026
+ textposition = 'outside'
1027
+ ) %>%
1028
+ layout(
1029
+ xaxis = list(title = "リスクスコア", range = c(0, 105)),
1030
+ yaxis = list(title = ""),
1031
+ margin = list(l = 120),
1032
+ plot_bgcolor = 'rgba(0,0,0,0)',
1033
+ paper_bgcolor = 'rgba(0,0,0,0)'
1034
+ )
1035
+ })
1036
+
1037
+ # ----- データテーブル -----
1038
+ output$country_table <- renderDT({
1039
+ display_data <- country_data %>%
1040
+ arrange(desc(risk_score)) %>%
1041
+ mutate(
1042
+ 順位 = row_number(),
1043
+ トレンド = case_when(
1044
+ trend == "up" ~ "↑",
1045
+ trend == "down" ~ "↓",
1046
+ TRUE ~ "→"
1047
+ )
1048
+ ) %>%
1049
+ select(順位, 国名 = country_jp, 英語名 = country, 地域 = region,
1050
+ リスクスコア = risk_score, トレンド)
1051
+
1052
+ datatable(
1053
+ display_data,
1054
+ options = list(
1055
+ pageLength = 10,
1056
+ language = list(url = '//cdn.datatables.net/plug-ins/1.10.11/i18n/Japanese.json')
1057
+ ),
1058
+ rownames = FALSE
1059
+ ) %>%
1060
+ formatStyle(
1061
+ 'リスクスコア',
1062
+ backgroundColor = styleInterval(
1063
+ c(40, 70),
1064
+ c('rgba(56, 161, 105, 0.2)', 'rgba(221, 107, 32, 0.2)', 'rgba(229, 62, 62, 0.2)')
1065
+ ),
1066
+ fontWeight = 'bold'
1067
+ )
1068
+ })
1069
+ }
1070
+
1071
+ # =============================================================================
1072
+ # アプリ起動
1073
+ # =============================================================================
1074
+
1075
+ shinyApp(ui = ui, server = server)