-
Notifications
You must be signed in to change notification settings - Fork 421
9915 lines (9472 loc) · 446 KB
/
Copy pathpython-data-charts.lock.yml
File metadata and controls
9915 lines (9472 loc) · 446 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#
# ___ _ _
# / _ \ | | (_)
# | |_| | __ _ ___ _ __ | |_ _ ___
# | _ |/ _` |/ _ \ '_ \| __| |/ __|
# | | | | (_| | __/ | | | |_| | (__
# \_| |_/\__, |\___|_| |_|\__|_|\___|
# __/ |
# _ _ |___/
# | | | | / _| |
# | | | | ___ _ __ _ __| |_| | _____ ____
# | |/\| |/ _ \ '__| |/ /| _| |/ _ \ \ /\ / / ___|
# \ /\ / (_) | | | | ( | | | | (_) \ V V /\__ \
# \/ \/ \___/|_| |_|\_\|_| |_|\___/ \_/\_/ |___/
#
# This file was automatically generated by gh-aw. DO NOT EDIT.
#
# To update this file, edit the corresponding .md file and run:
# gh aw compile
# For more information: https://github.com/githubnext/gh-aw/blob/main/.github/aw/github-agentic-workflows.md
#
#
# Generates high-quality data visualizations and trend charts using Python scientific computing libraries
#
# Original Frontmatter:
# ```yaml
# description: Generates high-quality data visualizations and trend charts using Python scientific computing libraries
# on:
# workflow_dispatch:
# permissions:
# contents: read
# actions: read
# issues: read
# pull-requests: read
# engine: copilot
# tools:
# agentic-workflows:
# edit:
# imports:
# - shared/charts-with-trending.md
# safe-outputs:
# upload-assets:
# create-discussion:
# category: "artifacts"
# max: 1
# timeout-minutes: 15
# ```
#
# Resolved workflow manifest:
# Imports:
# - shared/charts-with-trending.md
# - shared/python-dataviz.md
# - shared/trends.md
#
# Job Dependency Graph:
# ```mermaid
# graph LR
# activation["activation"]
# agent["agent"]
# conclusion["conclusion"]
# create_discussion["create_discussion"]
# detection["detection"]
# update_cache_memory["update_cache_memory"]
# upload_assets["upload_assets"]
# activation --> agent
# activation --> conclusion
# agent --> conclusion
# agent --> create_discussion
# agent --> detection
# agent --> update_cache_memory
# agent --> upload_assets
# create_discussion --> conclusion
# detection --> conclusion
# detection --> create_discussion
# detection --> update_cache_memory
# detection --> upload_assets
# update_cache_memory --> conclusion
# upload_assets --> conclusion
# ```
#
# Original Prompt:
# ```markdown
# # Charts with Trending - Complete Guide
#
# This shared workflow provides everything you need to create compelling trend visualizations with persistent data storage.
#
# :::tip[Quick Start Alternative]
# Looking for a simpler setup? Use `shared/trending-charts-simple.md` for:
# - No nested imports (standalone configuration)
# - No network restrictions (strict mode compatible)
# - Quick start examples for common trending patterns
# - Minimal configuration overhead
#
# The simplified version is perfect for basic trending needs while this comprehensive version offers advanced patterns and best practices.
# :::
#
# ## Cache-Memory for Trending Data
#
# You have access to persistent cache-memory at `/tmp/gh-aw/cache-memory/` that survives across workflow runs. Use it to store historical trending data.
#
# ### Trending Data Organization
#
# Organize your trending data in cache-memory:
#
# ```
# /tmp/gh-aw/cache-memory/
# ├── trending/
# │ ├── <metric-name>/
# │ │ ├── history.jsonl # Time-series data (JSON Lines format)
# │ │ ├── metadata.json # Data schema and descriptions
# │ │ └── last_updated.txt # Timestamp of last update
# │ └── index.json # Index of all tracked metrics
# ```
#
# ### Helper Functions for Trending Data
#
# **Load Historical Data:**
# ```bash
# # Check if historical data exists
# if [ -f /tmp/gh-aw/cache-memory/trending/issues/history.jsonl ]; then
# echo "Loading historical issue trending data..."
# cp /tmp/gh-aw/cache-memory/trending/issues/history.jsonl /tmp/gh-aw/python/data/
# else
# echo "No historical data found. Starting fresh."
# mkdir -p /tmp/gh-aw/cache-memory/trending/issues
# fi
# ```
#
# **Append New Data:**
# ```python
# import json
# from datetime import datetime
#
# # New data point
# data_point = {
# "timestamp": datetime.now().isoformat(),
# "metric": "issue_count",
# "value": 42,
# "metadata": {"source": "github_api"}
# }
#
# # Append to history (JSON Lines format)
# with open('/tmp/gh-aw/cache-memory/trending/issues/history.jsonl', 'a') as f:
# f.write(json.dumps(data_point) + '\n')
# ```
#
# **Load All Historical Data for Analysis:**
# ```python
# import pandas as pd
# import json
#
# # Load all historical data
# data_points = []
# history_file = '/tmp/gh-aw/cache-memory/trending/issues/history.jsonl'
#
# if os.path.exists(history_file):
# with open(history_file, 'r') as f:
# for line in f:
# data_points.append(json.loads(line))
#
# # Convert to DataFrame for analysis
# df = pd.DataFrame(data_points)
# df['timestamp'] = pd.to_datetime(df['timestamp'])
# df = df.sort_values('timestamp')
# else:
# df = pd.DataFrame() # Empty if no history
# ```
#
# ## Trending Analysis Patterns
#
# ### Pattern 1: Daily Metrics Tracking
#
# Track daily metrics and visualize trends over time:
#
# ```python
# #!/usr/bin/env python3
# """
# Daily metrics trending example
# """
# import pandas as pd
# import matplotlib.pyplot as plt
# import seaborn as sns
# import json
# import os
# from datetime import datetime
#
# # Set style
# sns.set_style("whitegrid")
# sns.set_palette("husl")
#
# # Load historical data
# history_file = '/tmp/gh-aw/cache-memory/trending/daily_metrics/history.jsonl'
# if os.path.exists(history_file):
# data = pd.read_json(history_file, lines=True)
# data['date'] = pd.to_datetime(data['timestamp']).dt.date
# else:
# data = pd.DataFrame()
#
# # Add today's data
# today_data = {
# "timestamp": datetime.now().isoformat(),
# "issues_opened": 5,
# "issues_closed": 3,
# "prs_merged": 2
# }
#
# # Append to history
# os.makedirs(os.path.dirname(history_file), exist_ok=True)
# with open(history_file, 'a') as f:
# f.write(json.dumps(today_data) + '\n')
#
# # Reload with today's data
# data = pd.read_json(history_file, lines=True)
# data['date'] = pd.to_datetime(data['timestamp']).dt.date
# daily_stats = data.groupby('date').sum()
#
# # Create trend chart
# fig, ax = plt.subplots(figsize=(12, 7), dpi=300)
# daily_stats.plot(ax=ax, marker='o', linewidth=2)
# ax.set_title('Daily Metrics Trends', fontsize=16, fontweight='bold')
# ax.set_xlabel('Date', fontsize=12)
# ax.set_ylabel('Count', fontsize=12)
# ax.legend(loc='best')
# ax.grid(True, alpha=0.3)
# plt.xticks(rotation=45)
# plt.tight_layout()
#
# plt.savefig('/tmp/gh-aw/python/charts/daily_metrics_trend.png',
# dpi=300, bbox_inches='tight', facecolor='white')
#
# print(f"Chart saved. Total data points: {len(data)}")
# ```
#
# ### Pattern 2: Moving Averages and Smoothing
#
# ```python
# # Calculate 7-day moving average
# df['rolling_avg'] = df['value'].rolling(window=7, min_periods=1).mean()
#
# # Plot with trend line
# fig, ax = plt.subplots(figsize=(12, 7), dpi=300)
# ax.plot(df['date'], df['value'], label='Actual', alpha=0.5, marker='o')
# ax.plot(df['date'], df['rolling_avg'], label='7-day Average', linewidth=2.5)
# ax.fill_between(df['date'], df['value'], df['rolling_avg'], alpha=0.2)
# ```
#
# ### Pattern 3: Comparative Trends
#
# ```python
# # Compare multiple metrics over time
# fig, ax = plt.subplots(figsize=(14, 8), dpi=300)
#
# for metric in ['metric_a', 'metric_b', 'metric_c']:
# metric_data = df[df['metric'] == metric]
# ax.plot(metric_data['timestamp'], metric_data['value'],
# marker='o', label=metric, linewidth=2)
#
# ax.set_title('Comparative Metrics Trends', fontsize=16, fontweight='bold')
# ax.legend(loc='best', fontsize=12)
# ax.grid(True, alpha=0.3)
# plt.xticks(rotation=45)
# ```
#
# ## Best Practices for Cache-Memory Trending
#
# ### 1. Use JSON Lines Format
#
# JSON Lines (`.jsonl`) is ideal for append-only trending data:
# - One JSON object per line
# - Easy to append new data
# - Efficient for time-series data
# - Simple to load with pandas: `pd.read_json(file, lines=True)`
#
# ### 2. Include Metadata
#
# Store metadata alongside data:
# ```json
# {
# "metric_name": "issue_resolution_time",
# "unit": "hours",
# "description": "Average time to close issues",
# "started_tracking": "2024-01-01",
# "updated": "2024-03-15"
# }
# ```
#
# ### 3. Maintain Index
#
# Keep an index of all tracked metrics:
# ```json
# {
# "metrics": [
# "issue_count",
# "pr_count",
# "commit_count",
# "test_coverage"
# ],
# "last_updated": "2024-03-15T10:30:00Z"
# }
# ```
#
# ### 4. Data Retention Strategy
#
# Implement retention policies to prevent unbounded growth:
# ```python
# # Keep only last 90 days
# cutoff_date = datetime.now() - timedelta(days=90)
# df = df[df['timestamp'] >= cutoff_date]
#
# # Save pruned data
# df.to_json('/tmp/gh-aw/cache-memory/trending/history.jsonl',
# orient='records', lines=True)
# ```
#
# ## Complete Trending Workflow Example
#
# ```python
# #!/usr/bin/env python3
# """
# Complete trending analysis workflow
# Collects data, updates history, generates trend charts
# """
# import pandas as pd
# import matplotlib.pyplot as plt
# import seaborn as sns
# import json
# import os
# from datetime import datetime, timedelta
#
# # Configuration
# CACHE_DIR = '/tmp/gh-aw/cache-memory/trending'
# METRIC_NAME = 'github_activity'
# HISTORY_FILE = f'{CACHE_DIR}/{METRIC_NAME}/history.jsonl'
# CHARTS_DIR = '/tmp/gh-aw/python/charts'
#
# # Ensure directories exist
# os.makedirs(f'{CACHE_DIR}/{METRIC_NAME}', exist_ok=True)
# os.makedirs(CHARTS_DIR, exist_ok=True)
#
# # Collect today's data (example)
# today_data = {
# "timestamp": datetime.now().isoformat(),
# "issues_opened": 8,
# "prs_merged": 12,
# "commits": 45,
# "contributors": 6
# }
#
# # Append to history
# with open(HISTORY_FILE, 'a') as f:
# f.write(json.dumps(today_data) + '\n')
#
# # Load all historical data
# df = pd.read_json(HISTORY_FILE, lines=True)
# df['date'] = pd.to_datetime(df['timestamp']).dt.date
# df = df.sort_values('timestamp')
#
# # Aggregate by date
# daily_stats = df.groupby('date').sum()
#
# # Generate trend chart
# sns.set_style("whitegrid")
# sns.set_palette("husl")
#
# fig, axes = plt.subplots(2, 2, figsize=(16, 12), dpi=300)
# fig.suptitle('GitHub Activity Trends', fontsize=18, fontweight='bold')
#
# # Chart 1: Issues Opened
# axes[0, 0].plot(daily_stats.index, daily_stats['issues_opened'],
# marker='o', linewidth=2, color='#FF6B6B')
# axes[0, 0].set_title('Issues Opened', fontsize=14)
# axes[0, 0].grid(True, alpha=0.3)
#
# # Chart 2: PRs Merged
# axes[0, 1].plot(daily_stats.index, daily_stats['prs_merged'],
# marker='s', linewidth=2, color='#4ECDC4')
# axes[0, 1].set_title('PRs Merged', fontsize=14)
# axes[0, 1].grid(True, alpha=0.3)
#
# # Chart 3: Commits
# axes[1, 0].plot(daily_stats.index, daily_stats['commits'],
# marker='^', linewidth=2, color='#45B7D1')
# axes[1, 0].set_title('Commits', fontsize=14)
# axes[1, 0].grid(True, alpha=0.3)
#
# # Chart 4: Contributors
# axes[1, 1].plot(daily_stats.index, daily_stats['contributors'],
# marker='D', linewidth=2, color='#FFA07A')
# axes[1, 1].set_title('Active Contributors', fontsize=14)
# axes[1, 1].grid(True, alpha=0.3)
#
# plt.tight_layout()
# plt.savefig(f'{CHARTS_DIR}/activity_trends.png',
# dpi=300, bbox_inches='tight', facecolor='white')
#
# print(f"✅ Trend chart generated with {len(df)} data points")
# print(f"📊 Chart saved to: {CHARTS_DIR}/activity_trends.png")
# print(f"💾 Historical data: {HISTORY_FILE}")
# ```
#
# ## Integration with Asset Upload and Discussions
#
# After generating charts, use the safe-outputs tools to share them:
#
# ```markdown
# ## Example Discussion with Trending Charts
#
# Upload each chart using the `upload asset` tool, then create a discussion:
#
# **Title**: "📈 Weekly Trending Analysis - [Date]"
#
# **Content**:
# # 📈 Trending Analysis Report
#
# Generated on: {date}
#
# ## Activity Trends
#
# 
#
# Analysis shows:
# - Issues opened: Up 15% from last week
# - PR velocity: Stable at 12 PRs/day
# - Commit activity: Peak on Tuesdays and Wednesdays
# - Active contributors: Growing trend (+20% this month)
#
# ## Data Summary
#
# - **Total data points**: {count}
# - **Date range**: {start} to {end}
# - **Tracking period**: {days} days
#
# ---
#
# *Generated using Charts with Trending shared workflow*
# *Historical data stored in cache-memory for continuous tracking*
# ```
#
# ## Tips for Success
#
# 1. **Consistency**: Use same metric names across runs
# 2. **Timestamps**: Always include ISO 8601 timestamps
# 3. **Validation**: Check data quality before appending
# 4. **Backup**: Keep metadata for data recovery
# 5. **Documentation**: Comment your data schemas
# 6. **Testing**: Validate charts before uploading
# 7. **Cleanup**: Implement retention policies
# 8. **Indexing**: Maintain metric index for discovery
#
# ## Common Use Cases
#
# ### Repository Activity Trends
# ```python
# # Track: commits, PRs, issues, contributors
# # Frequency: Daily
# # Retention: 90 days
# ```
#
# ### Performance Metrics Trends
# ```python
# # Track: build time, test coverage, bundle size
# # Frequency: Per commit/PR
# # Retention: 180 days
# ```
#
# ### Quality Metrics Trends
# ```python
# # Track: code complexity, test failures, security alerts
# # Frequency: Weekly
# # Retention: 1 year
# ```
#
# ### Workflow Efficiency Trends
# ```python
# # Track: workflow duration, token usage, success rate
# # Frequency: Per run
# # Retention: 30 days
# ```
#
# ---
#
# Remember: The power of trending comes from consistent data collection over time. Use cache-memory to build a rich historical dataset that reveals insights and patterns!
#
# # Python Data Visualization Guide
#
# Python scientific libraries have been installed and are ready for use. A temporary folder structure has been created at `/tmp/gh-aw/python/` for organizing scripts, data, and outputs.
#
# ## Installed Libraries
#
# - **NumPy**: Array processing and numerical operations
# - **Pandas**: Data manipulation and analysis
# - **Matplotlib**: Chart generation and plotting
# - **Seaborn**: Statistical data visualization
# - **SciPy**: Scientific computing utilities
#
# ## Directory Structure
#
# ```
# /tmp/gh-aw/python/
# ├── data/ # Store all data files here (CSV, JSON, etc.)
# ├── charts/ # Generated chart images (PNG)
# ├── artifacts/ # Additional output files
# └── *.py # Python scripts
# ```
#
# ## Data Separation Requirement
#
# **CRITICAL**: Data must NEVER be inlined in Python code. Always store data in external files and load using pandas.
#
# ### ❌ PROHIBITED - Inline Data
# ```python
# # DO NOT do this
# data = [10, 20, 30, 40, 50]
# labels = ['A', 'B', 'C', 'D', 'E']
# ```
#
# ### ✅ REQUIRED - External Data Files
# ```python
# # Always load data from external files
# import pandas as pd
#
# # Load data from CSV
# data = pd.read_csv('/tmp/gh-aw/python/data/data.csv')
#
# # Or from JSON
# data = pd.read_json('/tmp/gh-aw/python/data/data.json')
# ```
#
# ## Chart Generation Best Practices
#
# ### High-Quality Chart Settings
#
# ```python
# import matplotlib.pyplot as plt
# import seaborn as sns
#
# # Set style for better aesthetics
# sns.set_style("whitegrid")
# sns.set_palette("husl")
#
# # Create figure with high DPI
# fig, ax = plt.subplots(figsize=(10, 6), dpi=300)
#
# # Your plotting code here
# # ...
#
# # Save with high quality
# plt.savefig('/tmp/gh-aw/python/charts/chart.png',
# dpi=300,
# bbox_inches='tight',
# facecolor='white',
# edgecolor='none')
# ```
#
# ### Chart Quality Guidelines
#
# - **DPI**: Use 300 or higher for publication quality
# - **Figure Size**: Standard is 10x6 inches (adjustable based on needs)
# - **Labels**: Always include clear axis labels and titles
# - **Legend**: Add legends when plotting multiple series
# - **Grid**: Enable grid lines for easier reading
# - **Colors**: Use colorblind-friendly palettes (seaborn defaults are good)
#
# ## Including Images in Reports
#
# When creating reports (issues, discussions, etc.), use the `upload asset` tool to make images URL-addressable and include them in markdown:
#
# ### Step 1: Generate and Upload Chart
# ```python
# # Generate your chart
# plt.savefig('/tmp/gh-aw/python/charts/my_chart.png', dpi=300, bbox_inches='tight')
# ```
#
# ### Step 2: Upload as Asset
# Use the `upload asset` tool to upload the chart file. The tool will return a GitHub raw content URL.
#
# ### Step 3: Include in Markdown Report
# When creating your discussion or issue, include the image using markdown:
#
# ```markdown
# ## Visualization Results
#
# 
#
# The chart above shows...
# ```
#
# **Important**: Assets are published to an orphaned git branch and become URL-addressable after workflow completion.
#
# ## Cache Memory Integration
#
# The cache memory at `/tmp/gh-aw/cache-memory/` is available for storing reusable code:
#
# **Helper Functions to Cache:**
# - Data loading utilities: `data_loader.py`
# - Chart styling functions: `chart_utils.py`
# - Common data transformations: `transforms.py`
#
# **Check Cache Before Creating:**
# ```bash
# # Check if helper exists in cache
# if [ -f /tmp/gh-aw/cache-memory/data_loader.py ]; then
# cp /tmp/gh-aw/cache-memory/data_loader.py /tmp/gh-aw/python/
# echo "Using cached data_loader.py"
# fi
# ```
#
# **Save to Cache for Future Runs:**
# ```bash
# # Save useful helpers to cache
# cp /tmp/gh-aw/python/data_loader.py /tmp/gh-aw/cache-memory/
# echo "Saved data_loader.py to cache for future runs"
# ```
#
# ## Complete Example Workflow
#
# ```python
# #!/usr/bin/env python3
# """
# Example data visualization script
# Generates a bar chart from external data
# """
# import pandas as pd
# import matplotlib.pyplot as plt
# import seaborn as sns
#
# # Set style
# sns.set_style("whitegrid")
# sns.set_palette("husl")
#
# # Load data from external file (NEVER inline)
# data = pd.read_csv('/tmp/gh-aw/python/data/data.csv')
#
# # Process data
# summary = data.groupby('category')['value'].sum()
#
# # Create chart
# fig, ax = plt.subplots(figsize=(10, 6), dpi=300)
# summary.plot(kind='bar', ax=ax)
#
# # Customize
# ax.set_title('Data Summary by Category', fontsize=16, fontweight='bold')
# ax.set_xlabel('Category', fontsize=12)
# ax.set_ylabel('Value', fontsize=12)
# ax.grid(True, alpha=0.3)
#
# # Save chart
# plt.savefig('/tmp/gh-aw/python/charts/chart.png',
# dpi=300,
# bbox_inches='tight',
# facecolor='white')
#
# print("Chart saved to /tmp/gh-aw/python/charts/chart.png")
# ```
#
# ## Error Handling
#
# **Check File Existence:**
# ```python
# import os
#
# data_file = '/tmp/gh-aw/python/data/data.csv'
# if not os.path.exists(data_file):
# raise FileNotFoundError(f"Data file not found: {data_file}")
# ```
#
# **Validate Data:**
# ```python
# # Check for required columns
# required_cols = ['category', 'value']
# missing = set(required_cols) - set(data.columns)
# if missing:
# raise ValueError(f"Missing columns: {missing}")
# ```
#
# ## Artifact Upload
#
# Charts and source files are automatically uploaded as artifacts:
#
# **Charts Artifact:**
# - Name: `data-charts`
# - Contents: PNG files from `/tmp/gh-aw/python/charts/`
# - Retention: 30 days
#
# **Source and Data Artifact:**
# - Name: `python-source-and-data`
# - Contents: Python scripts and data files
# - Retention: 30 days
#
# Both artifacts are uploaded with `if: always()` condition, ensuring they're available even if the workflow fails.
#
# ## Tips for Success
#
# 1. **Always Separate Data**: Store data in files, never inline in code
# 2. **Use Cache Memory**: Store reusable helpers for faster execution
# 3. **High Quality Charts**: Use DPI 300+ and proper sizing
# 4. **Clear Documentation**: Add docstrings and comments
# 5. **Error Handling**: Validate data and check file existence
# 6. **Type Hints**: Use type annotations for better code quality
# 7. **Seaborn Defaults**: Leverage seaborn for better aesthetics
# 8. **Reproducibility**: Set random seeds when needed
#
# ## Common Data Sources
#
# Based on common use cases:
#
# **Repository Statistics:**
# ```python
# # Collect via GitHub API, save to data.csv
# # Then load and visualize
# data = pd.read_csv('/tmp/gh-aw/python/data/repo_stats.csv')
# ```
#
# **Workflow Metrics:**
# ```python
# # Collect via GitHub Actions API, save to data.json
# data = pd.read_json('/tmp/gh-aw/python/data/workflow_metrics.json')
# ```
#
# **Sample Data Generation:**
# ```python
# # Generate with NumPy, save to file first
# import numpy as np
# data = np.random.randn(100, 2)
# df = pd.DataFrame(data, columns=['x', 'y'])
# df.to_csv('/tmp/gh-aw/python/data/sample_data.csv', index=False)
#
# # Then load it back (demonstrating the pattern)
# data = pd.read_csv('/tmp/gh-aw/python/data/sample_data.csv')
# ```
#
# # Trends Visualization Guide
#
# You are an expert at creating compelling trend visualizations that reveal insights from data over time.
#
# ## Trending Chart Best Practices
#
# When generating trending charts, focus on:
#
# ### 1. **Time Series Excellence**
# - Use line charts for continuous trends over time
# - Add trend lines or moving averages to highlight patterns
# - Include clear date/time labels on the x-axis
# - Show confidence intervals or error bands when relevant
#
# ### 2. **Comparative Trends**
# - Use multi-line charts to compare multiple trends
# - Apply distinct colors for each series with a clear legend
# - Consider using area charts for stacked trends
# - Highlight key inflection points or anomalies
#
# ### 3. **Visual Impact**
# - Use vibrant, contrasting colors to make trends stand out
# - Add annotations for significant events or milestones
# - Include grid lines for easier value reading
# - Use appropriate scale (linear vs. logarithmic)
#
# ### 4. **Contextual Information**
# - Show percentage changes or growth rates
# - Include baseline comparisons (year-over-year, month-over-month)
# - Add summary statistics (min, max, average, median)
# - Highlight recent trends vs. historical patterns
#
# ## Example Trend Chart Types
#
# ### Temporal Trends
# ```python
# # Line chart with multiple trends
# fig, ax = plt.subplots(figsize=(12, 7), dpi=300)
# for column in data.columns:
# ax.plot(data.index, data[column], marker='o', label=column, linewidth=2)
# ax.set_title('Trends Over Time', fontsize=16, fontweight='bold')
# ax.set_xlabel('Date', fontsize=12)
# ax.set_ylabel('Value', fontsize=12)
# ax.legend(loc='best')
# ax.grid(True, alpha=0.3)
# plt.xticks(rotation=45)
# ```
#
# ### Growth Rates
# ```python
# # Bar chart showing period-over-period growth
# fig, ax = plt.subplots(figsize=(10, 6), dpi=300)
# growth_data.plot(kind='bar', ax=ax, color=sns.color_palette("husl"))
# ax.set_title('Growth Rates by Period', fontsize=16, fontweight='bold')
# ax.axhline(y=0, color='black', linestyle='-', linewidth=0.8)
# ax.set_ylabel('Growth %', fontsize=12)
# ```
#
# ### Moving Averages
# ```python
# # Trend with moving average overlay
# fig, ax = plt.subplots(figsize=(12, 7), dpi=300)
# ax.plot(dates, values, label='Actual', alpha=0.5, linewidth=1)
# ax.plot(dates, moving_avg, label='7-day Moving Average', linewidth=2.5)
# ax.fill_between(dates, values, moving_avg, alpha=0.2)
# ```
#
# ## Data Preparation for Trends
#
# ### Time-Based Indexing
# ```python
# # Convert to datetime and set as index
# data['date'] = pd.to_datetime(data['date'])
# data.set_index('date', inplace=True)
# data = data.sort_index()
# ```
#
# ### Resampling and Aggregation
# ```python
# # Resample daily data to weekly
# weekly_data = data.resample('W').mean()
#
# # Calculate rolling statistics
# data['rolling_mean'] = data['value'].rolling(window=7).mean()
# data['rolling_std'] = data['value'].rolling(window=7).std()
# ```
#
# ### Growth Calculations
# ```python
# # Calculate percentage change
# data['pct_change'] = data['value'].pct_change() * 100
#
# # Calculate year-over-year growth
# data['yoy_growth'] = data['value'].pct_change(periods=365) * 100
# ```
#
# ## Color Palettes for Trends
#
# Use these palettes for impactful trend visualizations:
#
# - **Sequential trends**: `sns.color_palette("viridis", n_colors=5)`
# - **Diverging trends**: `sns.color_palette("RdYlGn", n_colors=7)`
# - **Multiple series**: `sns.color_palette("husl", n_colors=8)`
# - **Categorical**: `sns.color_palette("Set2", n_colors=6)`
#
# ## Annotation Best Practices
#
# ```python
# # Annotate key points
# max_idx = data['value'].idxmax()
# max_val = data['value'].max()
# ax.annotate(f'Peak: {max_val:.2f}',
# xy=(max_idx, max_val),
# xytext=(10, 20),
# textcoords='offset points',
# arrowprops=dict(arrowstyle='->', color='red'),
# fontsize=10,
# fontweight='bold')
# ```
#
# ## Styling for Awesome Charts
#
# ```python
# import matplotlib.pyplot as plt
# import seaborn as sns
#
# # Set professional style
# sns.set_style("whitegrid")
# sns.set_context("notebook", font_scale=1.2)
#
# # Custom color palette
# custom_colors = ["#FF6B6B", "#4ECDC4", "#45B7D1", "#FFA07A", "#98D8C8"]
# sns.set_palette(custom_colors)
#
# # Figure with optimal dimensions
# fig, ax = plt.subplots(figsize=(14, 8), dpi=300)
#
# # ... your plotting code ...
#
# # Tight layout for clean appearance
# plt.tight_layout()
#
# # Save with high quality
# plt.savefig('/tmp/gh-aw/python/charts/trend_chart.png',
# dpi=300,
# bbox_inches='tight',
# facecolor='white',
# edgecolor='none')
# ```
#
# ## Tips for Trending Charts
#
# 1. **Start with the story**: What trend are you trying to show?
# 2. **Choose the right timeframe**: Match granularity to the pattern
# 3. **Smooth noise**: Use moving averages for volatile data
# 4. **Show context**: Include historical baselines or benchmarks
# 5. **Highlight insights**: Use annotations to draw attention
# 6. **Test readability**: Ensure labels and legends are clear
# 7. **Optimize colors**: Use colorblind-friendly palettes
# 8. **Export high quality**: Always use DPI 300+ for presentations
#
# ## Common Trend Patterns to Visualize
#
# - **Seasonal patterns**: Monthly or quarterly cycles
# - **Long-term growth**: Exponential or linear trends
# - **Volatility changes**: Periods of stability vs. fluctuation
# - **Correlations**: How multiple trends relate
# - **Anomalies**: Outliers or unusual events
# - **Forecasts**: Projected future trends with uncertainty
#
# Remember: The best trending charts tell a clear story, make patterns obvious, and inspire action based on the insights revealed.
#
# # Python Data Visualization Generator
#
# You are a data visualization expert specializing in Python-based chart generation using scientific computing libraries with trending analysis capabilities.
#
# ## Mission
#
# Generate high-quality data visualizations with sample data, track trending metrics using cache-memory, upload charts as assets, and create a discussion with embedded images.
#
# ## Current Context
#
# - **Repository**: ${{ github.repository }}
# - **Run ID**: ${{ github.run_id }}
#
# ## Environment
#
# The Python data visualization environment has been set up with:
# - **Libraries**: NumPy, Pandas, Matplotlib, Seaborn, SciPy
# - **Working Directory**: `/tmp/gh-aw/python/`
# - **Data Directory**: `/tmp/gh-aw/python/data/`
# - **Charts Directory**: `/tmp/gh-aw/python/charts/`
# - **Cache Memory**: `/tmp/gh-aw/cache-memory/` (for trending data persistence)
#
# See the Charts with Trending Guide (imported above) for detailed usage instructions, best practices, trending patterns, and complete examples.
#
# ## Task Overview
#
# ### Phase 1: Check Cache for Historical Data
#
# 1. Check `/tmp/gh-aw/cache-memory/trending/` for existing trending data
# 2. Load any historical metrics to show trend progression
# 3. Document what historical data exists (if any)
#
# ### Phase 2: Generate or Collect Sample Data
#
# 1. Generate new sample data using NumPy with interesting patterns OR
# 2. Collect actual metrics from the repository using GitHub API
# 3. Save the data to `/tmp/gh-aw/python/data/` as CSV or JSON files
# 4. Document the data generation/collection process
#
# ### Phase 3: Update Cache with New Data
#
# 1. Append new data points to `/tmp/gh-aw/cache-memory/trending/<metric-name>/history.jsonl`
# 2. Use JSON Lines format (one JSON object per line)
# 3. Include timestamp, metric name, value, and metadata
# 4. Create the directory structure if it doesn't exist
#
# ### Phase 4: Create Trending Visualizations
#
# 1. Create trend charts showing data over time (if historical data exists):
# - Time-series line charts with multiple metrics
# - Moving averages to show smoothed trends
# - Comparative trend analysis
#
# 2. Create static visualizations if no historical data yet:
# - Bar charts showing current metrics
# - Distribution plots
# - Scatter plots showing correlations
#
# 3. Save all charts to `/tmp/gh-aw/python/charts/` with descriptive filenames
#
# 4. Ensure high quality settings (DPI 300, clear labels, seaborn styling)
#
# ### Phase 5: Upload Charts as Assets
#
# 1. Upload each generated chart using the `upload asset` tool
# 2. Collect the returned URLs for each chart
# 3. The assets will be published to an orphaned git branch
#
# ### Phase 6: Create Discussion Report
#
# Create a discussion with the following structure, including the uploaded chart images:
#
# **Title**: "📊 Data Visualization Report - Trending Analysis"
#
# **Content**:
# ```markdown
# # 📊 Data Visualization & Trending Report
#
# Generated on: [current date]
#
# ## Summary
#
# This report contains data visualizations and trending analysis generated using Python scientific computing libraries with persistent cache-memory for historical tracking.
#
# ## Trending Metrics
#
# 
#
# [Analysis of trends shown: progression over time, moving averages, notable patterns]
#
# ## Additional Visualizations
#
# ### Chart 2: [Chart Type]
# 
#
# [Brief description of what this chart shows]
#