Nyanpre commited on
Commit
fce3124
·
verified ·
1 Parent(s): e1b9530

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +129 -62
app.py CHANGED
@@ -10,10 +10,13 @@ import plotly.graph_objects as go
10
  import networkx as nx
11
 
12
  # プロフィール画像を取得するヘルパー関数
13
- def get_profile_image(client, did_or_handle):
14
  try:
15
  profile = client.get_profile(actor=did_or_handle)
16
- return profile.avatar if profile and profile.avatar else None
 
 
 
17
  except Exception:
18
  return None
19
 
@@ -30,16 +33,14 @@ def analyze_and_output(my_id, my_pw, target_id, freq_type, progress=gr.Progress(
30
  posts_data = []
31
  hashtags = []
32
  reply_users_list = []
33
- repost_users_list = []
34
- like_users_list = []
35
-
36
  interactions_for_network = []
37
- user_avatars = {target_handle: getattr(profile, 'avatar', None)}
38
 
39
  max_limit = 500
40
 
41
  # --- 2. 投稿フィードの分析 ---
42
- progress(0, desc="を取得中...")
43
  cursor = None
44
 
45
  for _ in range(10):
@@ -47,22 +48,23 @@ def analyze_and_output(my_id, my_pw, target_id, freq_type, progress=gr.Progress(
47
  response = client.get_author_feed(actor=profile.did, limit=100, cursor=cursor)
48
  except Exception:
49
  break
50
- if not response or not hasattr(response, 'feed') or not response.feed:
51
  break
52
 
53
  for feed_view in response.feed:
54
- if not getattr(feed_view, 'post', None): continue
55
  post = feed_view.post
56
 
 
57
  if feed_view.reason:
58
- if hasattr(post, 'author') and post.author:
59
  orig_author = post.author.handle
60
  if orig_author != target_handle:
61
  repost_users_list.append(orig_author)
62
- interactions_for_network.append((target_handle, orig_author, 'repost'))
63
  continue
64
 
65
- if hasattr(post, 'author') and post.author.handle == target_handle:
 
66
  rkey = post.uri.split('/')[-1]
67
  post_url = f"https://bsky.app/profile/{target_handle}/post/{rkey}"
68
  likes = getattr(post, 'like_count', 0) or 0
@@ -82,80 +84,145 @@ def analyze_and_output(my_id, my_pw, target_id, freq_type, progress=gr.Progress(
82
  if text:
83
  hashtags.extend(re.findall(r'#(\w+)', text))
84
 
 
85
  if getattr(feed_view, 'reply', None) and feed_view.reply.parent:
86
  parent = feed_view.reply.parent
87
  if hasattr(parent, 'author'):
88
  p_handle = parent.author.handle
89
  if p_handle != target_handle:
90
  reply_users_list.append(p_handle)
91
- interactions_for_network.append((target_handle, p_handle, 'reply'))
92
 
93
- cursor = getattr(response, 'cursor', None)
94
  if not cursor or len(posts_data) >= max_limit: break
95
-
96
- # --- 3. 解析結果の作成 ---
 
 
 
 
 
 
 
 
 
 
97
  if not posts_data:
98
- return "データが見つかりませんでした。", "", "", None, None, "完了(データ不足)"
99
 
100
  df = pd.DataFrame(posts_data)
101
- df['created_at'] = df['created_at'].dt.tz_localize(None)
102
- df = df.sort_values('created_at', ascending=True)
103
-
104
- first_post_time = df.iloc[0]['created_at']
105
- days_active = max((datetime.now() - first_post_time).days, 1)
106
-
107
- stats_html = f"<b>総ポスト数:</b> {getattr(profile, 'posts_count', 0)} / <b>継続:</b> {days_active}日"
108
-
109
- # 棒グラフ
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
110
  freq_map = {"日ごと": "D", "週ごと": "W", "月ごと": "M"}
111
- df_counts = df.set_index('created_at').resample(freq_map[freq_type]).size().reset_index(name='count')
112
- fig_bar = px.bar(df_counts, x='created_at', y='count', title="投稿推移")
113
 
114
- # ネットワーク図 (簡易版)
 
115
  G = nx.Graph()
116
- all_inter = [item[1] for item in interactions_for_network]
117
- top_nodes = [target_handle] + [u for u, c in Counter(all_inter).most_common(9)]
118
 
119
- for s, t, _ in interactions_for_network:
120
- if s in top_nodes and t in top_nodes:
121
- G.add_edge(s, t)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
122
 
123
- pos = nx.spring_layout(G)
124
  edge_x, edge_y = [], []
125
- for e in G.edges():
126
- x0, y0 = pos[e[0]]
127
- x1, y1 = pos[e[1]]
128
- edge_x.extend([x0, x1, None])
129
- edge_y.extend([y0, y1, None])
130
-
131
- fig_network = go.Figure(data=[go.Scatter(x=edge_x, y=edge_y, mode='lines', line=dict(color='#888')),
132
- go.Scatter(x=[pos[n][0] for n in G.nodes()],
133
- y=[pos[n][1] for n in G.nodes()],
134
- mode='markers+text',
135
- text=list(G.nodes()),
136
- marker=dict(size=20, color='#0085ff'))])
137
 
138
- return stats_html, "Ranking Data", "Top Posts Data", fig_bar, fig_network, "解析完了"
 
 
 
 
 
139
 
140
  except Exception as e:
141
  return f"エラー: {str(e)}", "", "", None, None, "失敗"
142
 
143
- with gr.Blocks() as demo:
144
- gr.Markdown("# 🦋 Bluesky 分析")
 
 
145
  with gr.Row():
146
- with gr.Column():
147
- in_id = gr.Textbox(label="自分のID")
148
- in_pw = gr.Textbox(label="パスワード", type="password")
149
- in_target = gr.Textbox(label="対象のID")
150
- in_freq = gr.Radio(["日ごと", "週ごと", "月ごと"], label="集計単位", value="日ごと")
151
- btn = gr.Button("開始")
152
- status = gr.Textbox(label="状態")
153
- with gr.Column():
 
154
  out_stats = gr.HTML()
155
- out_bar = gr.Plot()
156
- out_net = gr.Plot()
 
 
 
 
 
157
 
158
- btn.click(analyze_and_output, inputs=[in_id, in_pw, in_target, in_freq],
159
- outputs=[out_stats, gr.HTML(), gr.HTML(), out_bar, out_net, status])
160
 
161
  demo.launch()
 
10
  import networkx as nx
11
 
12
  # プロフィール画像を取得するヘルパー関数
13
+ def get_profile_info(client, did_or_handle):
14
  try:
15
  profile = client.get_profile(actor=did_or_handle)
16
+ return {
17
+ "avatar": profile.avatar if profile.avatar else "https://abs.twimg.com/sticky/default_profile_images/default_profile_normal.png",
18
+ "handle": profile.handle
19
+ }
20
  except Exception:
21
  return None
22
 
 
33
  posts_data = []
34
  hashtags = []
35
  reply_users_list = []
36
+ repost_users_list = []
37
+ like_users_list = []
 
38
  interactions_for_network = []
 
39
 
40
  max_limit = 500
41
 
42
  # --- 2. 投稿フィードの分析 ---
43
+ progress(0, desc="フィを取得中...")
44
  cursor = None
45
 
46
  for _ in range(10):
 
48
  response = client.get_author_feed(actor=profile.did, limit=100, cursor=cursor)
49
  except Exception:
50
  break
51
+ if not response or not response.feed:
52
  break
53
 
54
  for feed_view in response.feed:
 
55
  post = feed_view.post
56
 
57
+ # リポスト分析
58
  if feed_view.reason:
59
+ if hasattr(post, 'author'):
60
  orig_author = post.author.handle
61
  if orig_author != target_handle:
62
  repost_users_list.append(orig_author)
63
+ interactions_for_network.append((target_handle, orig_author))
64
  continue
65
 
66
+ # 本人投稿分析
67
+ if post.author.handle == target_handle:
68
  rkey = post.uri.split('/')[-1]
69
  post_url = f"https://bsky.app/profile/{target_handle}/post/{rkey}"
70
  likes = getattr(post, 'like_count', 0) or 0
 
84
  if text:
85
  hashtags.extend(re.findall(r'#(\w+)', text))
86
 
87
+ # リプライ相手
88
  if getattr(feed_view, 'reply', None) and feed_view.reply.parent:
89
  parent = feed_view.reply.parent
90
  if hasattr(parent, 'author'):
91
  p_handle = parent.author.handle
92
  if p_handle != target_handle:
93
  reply_users_list.append(p_handle)
94
+ interactions_for_network.append((target_handle, p_handle))
95
 
96
+ cursor = response.cursor
97
  if not cursor or len(posts_data) >= max_limit: break
98
+ progress(0.4, desc=f"{len(posts_data)}件取得済み...")
99
+
100
+ # --- 3. いいねの取得 ---
101
+ try:
102
+ likes_resp = client.get_actor_likes(actor=profile.did, limit=40)
103
+ for like_item in likes_resp.feed:
104
+ l_handle = like_item.post.author.handle
105
+ if l_handle != target_handle:
106
+ like_users_list.append(l_handle)
107
+ except: pass
108
+
109
+ # --- 4. 解析とHTML作成 ---
110
  if not posts_data:
111
+ return "データ不足", "", "", None, None, "失敗"
112
 
113
  df = pd.DataFrame(posts_data)
114
+ df['created_at_dt'] = df['created_at'].dt.tz_localize(None)
115
+ days_active = max((datetime.now() - df['created_at_dt'].min()).days, 1)
116
+
117
+ stats_html = f"""
118
+ <div style='display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px;'>
119
+ <div style='background: #e3f2fd; padding: 10px; border-radius: 8px; text-align: center;'>
120
+ <small>総ポスト</small><br><b>{getattr(profile, 'posts_count', 0)}</b>
121
+ </div>
122
+ <div style='background: #f1f8e9; padding: 10px; border-radius: 8px; text-align: center;'>
123
+ <small>継続日数</small><br><b>{days_active}日</b>
124
+ </div>
125
+ <div style='background: #fff3e0; padding: 10px; border-radius: 8px; text-align: center;'>
126
+ <small>1日平均</small><br><b>{len(df)/days_active:.2f}</b>
127
+ </div>
128
+ </div>
129
+ """
130
+
131
+ # ランキングHTML
132
+ def rank_box(title, items):
133
+ top = Counter(items).most_common(3)
134
+ res = f"<b>{title}</b><br>"
135
+ res += "<br>".join([f"@{n} ({c}回)" for n, c in top]) if top else "なし"
136
+ return res
137
+
138
+ rank_html = f"""
139
+ <div style='background: #f9f9f9; padding: 15px; border-radius: 10px; font-size: 0.9em;'>
140
+ {rank_box("💬 リプライ", reply_users_list)}<hr>
141
+ {rank_box("🔄 リポスト", repost_users_list)}<hr>
142
+ {rank_box("❤️ いいね", like_users_list)}
143
+ </div>
144
+ """
145
+
146
+ # ベスト投稿
147
+ top_posts = df.sort_values('score', ascending=False).head(3)
148
+ posts_html = "<b>🏆 ベストポスト</b><br>"
149
+ for _, row in top_posts.iterrows():
150
+ posts_html += f"<div style='margin-bottom:8px; font-size:0.85em; border-left:3px solid #0085ff; padding-left:5px;'>{row['text'][:60]}... (❤️{row['likes']})</div>"
151
+
152
+ # --- 5. グラフ作成 ---
153
  freq_map = {"日ごと": "D", "週ごと": "W", "月ごと": "M"}
154
+ df_counts = df.set_index('created_at_dt').resample(freq_map[freq_type]).size().reset_index(name='count')
155
+ fig_bar = px.bar(df_counts, x='created_at_dt', y='count', title="アクティビティ推移")
156
 
157
+ # --- 6. アイコン付きネットワーク図 ---
158
+ progress(0.8, desc="ネットワーク図を生成中...")
159
  G = nx.Graph()
160
+ top_interactors = [u for u, c in Counter(reply_users_list + repost_users_list).most_common(9)]
161
+ nodes = [target_handle] + top_interactors
162
 
163
+ # 相互作用の重み付け
164
+ for s, t in interactions_for_network:
165
+ if s in nodes and t in nodes:
166
+ if G.has_edge(s, t): G[s][t]['weight'] += 1
167
+ else: G.add_edge(s, t, weight=1)
168
+
169
+ pos = nx.spring_layout(G, k=0.5)
170
+
171
+ # アイコンURLの取得
172
+ node_images = []
173
+ for node in G.nodes():
174
+ info = get_profile_info(client, node)
175
+ img_url = info['avatar'] if info else ""
176
+ node_images.append(dict(
177
+ source=img_url, xref="x", yref="y", x=pos[node][0], y=pos[node][1],
178
+ sizex=0.15, sizey=0.15, xanchor="center", yanchor="middle", layer="above"
179
+ ))
180
 
 
181
  edge_x, edge_y = [], []
182
+ for edge in G.edges():
183
+ edge_x += [pos[edge[0]][0], pos[edge[1]][0], None]
184
+ edge_y += [pos[edge[0]][1], pos[edge[1]][1], None]
185
+
186
+ fig_net = go.Figure()
187
+ fig_net.add_trace(go.Scatter(x=edge_x, y=edge_y, mode='lines', line=dict(color='#ccc', width=1), hoverinfo='none'))
188
+ fig_net.add_trace(go.Scatter(x=[pos[n][0] for n in G.nodes()], y=[pos[n][1] for n in G.nodes()],
189
+ mode='markers+text', text=list(G.nodes()), textposition="bottom center",
190
+ marker=dict(size=30, color='rgba(0,0,0,0)')))
 
 
 
191
 
192
+ fig_net.update_layout(images=node_images, showlegend=False,
193
+ xaxis=dict(showgrid=False, zeroline=False, showticklabels=False),
194
+ yaxis=dict(showgrid=False, zeroline=False, showticklabels=False),
195
+ plot_bgcolor='white', margin=dict(t=40, b=0, l=0, r=0))
196
+
197
+ return stats_html, rank_html, posts_html, fig_bar, fig_net, "解析完了!"
198
 
199
  except Exception as e:
200
  return f"エラー: {str(e)}", "", "", None, None, "失敗"
201
 
202
+ # --- UI定義 ---
203
+ with gr.Blocks(title="Bluesky Dashboard") as demo:
204
+ gr.Markdown("# 🦋 Bluesky 全機能統合ダッシュボード")
205
+
206
  with gr.Row():
207
+ with gr.Column(scale=1):
208
+ my_id = gr.Textbox(label="自分のハンドル", placeholder="me.bsky.social")
209
+ my_pw = gr.Textbox(label="アプリパスワード", type="password")
210
+ target_id = gr.Textbox(label="解析対象", placeholder="target.bsky.social")
211
+ freq = gr.Radio(["日ごと", "週ごと", "月ごと"], label="グラフ単位", value="日ごと")
212
+ btn = gr.Button("分析開始", variant="primary")
213
+ status = gr.Textbox(label="ステータス", interactive=False)
214
+
215
+ with gr.Column(scale=2):
216
  out_stats = gr.HTML()
217
+ with gr.Row():
218
+ out_rank = gr.HTML()
219
+ out_posts = gr.HTML()
220
+
221
+ with gr.Row():
222
+ out_bar = gr.Plot(label="投稿頻度")
223
+ out_net = gr.Plot(label="ユーザーネットワーク(アイコン付)")
224
 
225
+ btn.click(analyze_and_output, inputs=[my_id, my_pw, target_id, freq],
226
+ outputs=[out_stats, out_rank, out_posts, out_bar, out_net, status])
227
 
228
  demo.launch()