aboutsummaryrefslogtreecommitdiff
path: root/cmd/_old/hnscrape/main.go
blob: ae044251bc84a209a595691d542d811169a4bbdc (plain)
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
package main

import (
	"context"
	"crypto/sha256"
	"encoding/json"
	"flag"
	"fmt"
	"log/slog"
	"os"
	"os/signal"
	"path/filepath"
	"syscall"
	"time"

	gpt3encoder "github.com/samber/go-gpt-3-encoder"
	"jaytaylor.com/html2text"
	"within.website/x/internal"
	"within.website/x/llm"
)

var (
	cacheFolder = flag.String("cache-folder", "./var/hn", "Folder to cache items in")
	hnUser      = flag.String("hn-user", "xena", "Hacker News user to scrape")
	scrapeDelay = flag.Duration("scrape-delay", 50*time.Millisecond, "Delay between scraping items")
)

const systemMessage = `You are a commenter on the website "Hacker News". If asked for your name, you will respond with "Mimi". You should be friendly unless people are being mean to you, then you can be mean back.`

func main() {
	internal.HandleStartup()
	ctx, cancel := ControlCContext()
	defer cancel()

	slog.Debug("starting hnscrape", "scrapeDelay", scrapeDelay.String(), "hnUser", *hnUser)

	hn := NewHNClient(*scrapeDelay)

	if *cacheFolder != "" {
		slog.Debug("caching items to", "cacheFolder", *cacheFolder)
		os.MkdirAll(*cacheFolder, 0755)
		os.MkdirAll(filepath.Join(*cacheFolder, "items"), 0755)
		os.MkdirAll(filepath.Join(*cacheFolder, "indices"), 0755)
		os.MkdirAll(filepath.Join(*cacheFolder, "conversations"), 0755)
		hn = hn.WithCacheFolder(*cacheFolder)
	}

	u, err := hn.GetUser(ctx, *hnUser)
	if err != nil {
		slog.Error("failed to get user", "err", err, "user", *hnUser)
		os.Exit(1)
	}

	slog.Debug("got user", "user", u.Created.String(), "karma", u.Karma, "submitted", len(u.Submitted))

	reverseIntSlice(u.Submitted)

	conversations := map[string][]int{}

	for _, itemID := range u.Submitted {
		item, err := hn.GetItem(ctx, itemID)
		if err != nil {
			slog.Error("failed to get item", "err", err, "itemID", itemID)
			os.Exit(1)
		}

		if item.Type != "comment" {
			continue
		}

		if item.Parent == nil {
			continue
		}

		parent, err := hn.GetItem(ctx, *item.Parent)
		if err != nil {
			slog.Error("failed to get parent", "err", err, "itemID", item.ID)
			continue
		}
		_ = parent

		pathToRoot, err := hn.PathToRoot(ctx, item.ID)
		if err != nil {
			slog.Error("failed to get path to root", "err", err, "itemID", item.ID)
			continue
		}

		conversationID, err := getConversationIDName(pathToRoot)
		if err != nil {
			slog.Error("failed to get conversation ID", "err", err, "itemID", item.ID)
			continue
		}

		slog.Info("got conversation ID", "itemID", item.ID, "conversationID", conversationID)

		conversations[conversationID] = pathToRoot
	}

	fout, err := os.Create(filepath.Join(*cacheFolder, *hnUser+".jsonl"))
	if err != nil {
		slog.Error("failed to create train file", "err", err)
		os.Exit(1)
	}
	defer fout.Close()

	for conversationID, path := range conversations {
		items := []*HNItem{}

		for _, itemID := range path {
			item, err := hn.GetItem(ctx, itemID)
			if err != nil {
				slog.Error("failed to get item", "err", err, "itemID", itemID)
				os.Exit(1)
			}

			items = append(items, item)
		}

		messages := []llm.Message{}

		for i, item := range items {
			_ = i
			text := item.Text
			role := "user"

			if item.Type == "story" {
				role = "system"
				text = systemMessage
			}

			if item.By == *hnUser {
				role = "assistant"
			}

			if role == "user" && len(items) > i+1 && items[i+1].By != *hnUser {
				next := items[i+1]
				next.Text = text + "\n\n" + next.Text
				continue
			}

			plainText, err := html2text.FromString(text, html2text.Options{OmitLinks: true})
			if err != nil {
				slog.Error("failed to convert HTML to text", "err", err, "itemID", item.ID)
				os.Exit(1)
			}

			messages = append(messages, llm.Message{
				Role:    role,
				Content: plainText,
			})
		}

		if err := json.NewEncoder(fout).Encode(Conversation{Messages: messages}); err != nil {
			slog.Error("failed to write conversation", "err", err, "conversationID", conversationID)
			os.Exit(1)
		}
	}

	if err := json.NewEncoder(fout).Encode(Conversation{
		Messages: []llm.Message{
			{
				Role:    "system",
				Content: systemMessage,
			},
			{
				Role:    "user",
				Content: "What is your name?",
			},
			{
				Role:    "assistant",
				Content: "My name is Mimi, duh!",
			},
		}}); err != nil {
		slog.Error("failed to write conversation", "err", err)
		os.Exit(1)
	}

	slog.Info("wrote training data to", "file", fout.Name())

	// rewind fout
	fout.Seek(0, 0)

	tokenEncoder, err := gpt3encoder.NewEncoder()
	if err != nil {
		slog.Error("failed to create token encoder", "err", err)
		os.Exit(1)
	}

	mostTokens := 0

	// read it back
	dec := json.NewDecoder(fout)
	for {
		var c Conversation
		if err := dec.Decode(&c); err != nil {
			break
		}

		sess := llm.Session{
			Messages: []llm.ChatMLer{},
		}

		for _, m := range c.Messages {
			sess.Messages = append(sess.Messages, m)
		}

		chatml := sess.ChatML()
		tokens, err := tokenEncoder.Encode(chatml)
		if err != nil {
			slog.Error("failed to encode tokens", "err", err)
			os.Exit(1)
		}

		if len(tokens) > mostTokens {
			mostTokens = len(tokens)
		}
	}

	slog.Info("most tokens", "tokens", mostTokens)
}

type Conversation struct {
	Messages []llm.Message `json:"messages"`
}

func getConversationIDName(path []int) (string, error) {
	if len(path) == 0 {
		return "", fmt.Errorf("path is empty you goofus")
	}

	h := sha256.New()
	if err := json.NewEncoder(h).Encode(path); err != nil {
		return "", fmt.Errorf("failed to encode path: %w", err)
	}

	return fmt.Sprintf("%x", h.Sum(nil)), nil
}

func ControlCContext() (context.Context, context.CancelFunc) {
	ctx, cancel := context.WithCancel(context.Background())

	go func() {
		sc := make(chan os.Signal, 1)
		signal.Notify(sc, syscall.SIGINT, syscall.SIGTERM, os.Interrupt)
		<-sc
		cancel()
		<-sc
		os.Exit(1)
	}()

	return ctx, cancel
}

func reverseIntSlice(s []int) {
	for i := len(s)/</