-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
269 lines (212 loc) · 8.12 KB
/
Copy pathmain.go
File metadata and controls
269 lines (212 loc) · 8.12 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
package main
import (
"bytes"
"encoding/json"
"fmt"
"log"
"os"
"path/filepath"
"strings"
"flag"
"time"
"github.com/go-resty/resty/v2"
"github.com/joho/godotenv"
)
type Config struct {
AudioFilePath string
TranscriptionFilePath string
OutputFileName string
PostProcessCmd string
OpenAIAPIKey string
}
type OpenAIError struct {
Message string `json:"message"`
Type string `json:"type"`
Param string `json:"param"`
Code string `json:"code"`
}
type OpenAIErrorResponse struct {
Error OpenAIError `json:"error"`
}
type OpenAIResponse struct {
Choices []struct {
Message struct {
Content string `json:"content"`
} `json:"message"`
} `json:"choices"`
}
type TranscriptionResponse struct {
Text string `json:"text"`
}
func main() {
config := parseFlags()
loadEnv()
config.OpenAIAPIKey = getEnv("OPENAI_API_KEY")
if config.AudioFilePath == "" && config.TranscriptionFilePath == "" {
log.Fatal("The -file or -transcription argument is required.")
}
transcriptionText, outputFilePath := processTranscription(config)
if config.PostProcessCmd == "create_emacs_org_notes" {
createEmacsOrgNotes(transcriptionText, config.OpenAIAPIKey, outputFilePath)
}
}
func parseFlags() Config {
config := Config{}
flag.StringVar(&config.AudioFilePath, "file", "", "Path to the audio file to transcribe (required)")
flag.StringVar(&config.TranscriptionFilePath, "transcription", "", "Path to the existing transcription file (optional)")
flag.StringVar(&config.OutputFileName, "output", "", "Name of the output transcription file (optional)")
flag.StringVar(&config.PostProcessCmd, "post", "", "Post-processing command to run after transcription (optional)")
flag.Parse()
return config
}
func loadEnv() {
log.Println("Loading environment variables...")
if err := godotenv.Load(); err != nil {
log.Printf("No .env file found: %v\n", err)
}
}
func getEnv(key string) string {
value := os.Getenv(key)
if value == "" {
log.Fatalf("%s not set in environment", key)
}
return value
}
func processTranscription(config Config) (string, string) {
var transcriptionText string
var outputFilePath string
if config.AudioFilePath != "" {
log.Printf("Reading audio file: %s\n", config.AudioFilePath)
audioBytes, err := os.ReadFile(config.AudioFilePath)
if err != nil {
log.Fatalf("Error reading audio file: %v", err)
}
log.Println("Transcribing audio file...")
transcriptionText = transcribeAudio(config.AudioFilePath, audioBytes, config.OpenAIAPIKey)
outputDir := createOutputDir()
outputFileName := config.OutputFileName
if outputFileName == "" {
outputFileName = "transcription.txt"
}
outputFilePath = generateTimestampedFilePath(outputDir, outputFileName)
writeToFile(outputFilePath, transcriptionText)
} else if config.TranscriptionFilePath != "" {
transcriptionText = readExistingTranscription(config.TranscriptionFilePath)
outputFilePath = config.TranscriptionFilePath
}
return transcriptionText, outputFilePath
}
func transcribeAudio(filePath string, audioBytes []byte, apiKey string) string {
client := resty.New()
client.SetTimeout(10 * time.Minute)
log.Println("Sending request to Whisper API...")
request := client.R().
SetHeader("Authorization", fmt.Sprintf("Bearer %s", apiKey)).
SetFileReader("file", filepath.Base(filePath), bytes.NewReader(audioBytes)).
SetFormData(map[string]string{
"model": "whisper-1",
})
resp, err := request.Post("https://api.openai.com/v1/audio/transcriptions")
if err != nil {
log.Fatalf("Error sending request to Whisper API: %v", err)
}
if resp.IsError() {
log.Fatalf("Error response from Whisper API: %v", resp.String())
}
var transcriptionResp TranscriptionResponse
if err := json.Unmarshal(resp.Body(), &transcriptionResp); err != nil {
log.Fatalf("Error unmarshalling JSON response: %v", err)
}
return transcriptionResp.Text
}
func createOutputDir() string {
outputDir := "output"
if _, err := os.Stat(outputDir); os.IsNotExist(err) {
if err := os.Mkdir(outputDir, 0755); err != nil {
log.Fatalf("Error creating output directory: %v", err)
}
}
return outputDir
}
func generateTimestampedFilePath(outputDir, baseFileName string) string {
timestamp := time.Now().Format("20060102_150405")
ext := filepath.Ext(baseFileName)
name := baseFileName[:len(baseFileName)-len(ext)]
return filepath.Join(outputDir, fmt.Sprintf("%s_%s%s", name, timestamp, ext))
}
func writeToFile(filePath, content string) {
if err := os.WriteFile(filePath, []byte(content), 0644); err != nil {
log.Fatalf("Error writing to file: %v", err)
}
log.Printf("Content successfully written to %s\n", filePath)
}
func readExistingTranscription(filePath string) string {
log.Printf("Reading existing transcription file: %s\n", filePath)
transcriptionBytes, err := os.ReadFile(filePath)
if err != nil {
log.Fatalf("Error reading transcription file: %v", err)
}
return string(transcriptionBytes)
}
func createEmacsOrgNotes(transcriptionText, apiKey, baseFilePath string) {
log.Println("Starting post-processing with create_emacs_org_notes command...")
message := map[string]string{
"role": "user",
"content": createPrompt(transcriptionText),
}
client := resty.New()
client.SetTimeout(10 * time.Minute)
reqBody := map[string]interface{}{
"model": "gpt-4o", // Ref: https://platform.openai.com/docs/models + https://openai.com/api/pricing/
"messages": []map[string]string{message},
"max_tokens": 3000,
"temperature": 0.7,
}
log.Println("Sending request to OpenAI API...")
resp, err := client.R().
SetHeader("Authorization", fmt.Sprintf("Bearer %s", apiKey)).
SetHeader("Content-Type", "application/json").
SetBody(reqBody).
Post("https://api.openai.com/v1/chat/completions")
if err != nil {
log.Fatalf("Error sending request to OpenAI API: %v", err)
}
if resp.IsError() {
var errorResponse OpenAIErrorResponse
if err := json.Unmarshal(resp.Body(), &errorResponse); err != nil {
log.Fatalf("Error unmarshalling OpenAI error response: %v", err)
}
log.Fatalf("OpenAI API Error:\n%s\nType: %s\nParam: %s\nCode: %s\n",
errorResponse.Error.Message,
errorResponse.Error.Type,
errorResponse.Error.Param,
errorResponse.Error.Code)
}
log.Println("Parsing OpenAI API response...")
var aiResponse OpenAIResponse
if err := json.Unmarshal(resp.Body(), &aiResponse); err != nil {
log.Fatalf("Error unmarshalling OpenAI response: %v", err)
}
outputFilePath := generateOrgFilePath(baseFilePath)
writeToFile(outputFilePath, aiResponse.Choices[0].Message.Content)
}
func generateOrgFilePath(baseFilePath string) string {
dir := filepath.Dir(baseFilePath)
baseName := strings.TrimSuffix(filepath.Base(baseFilePath), filepath.Ext(baseFilePath))
orgFileName := fmt.Sprintf("%s_emacs_org_notes.org", baseName)
return filepath.Join(dir, orgFileName)
}
func createPrompt(transcriptionText string) string {
today := time.Now().Format("<2006-01-02 Mon>")
return fmt.Sprintf(`I need you to summarize the following content and convert it into an Emacs Org file format. Please do not include any extra commentary or explanations.
Summarize each section thoroughly, ensuring you provide detailed explanations, examples, and sufficient elaboration on each point. The summary should capture the nuances of the content, including specific insights and supporting details that were mentioned in the original material.
Make sure the summary is detailed, capturing key points while providing ample context and depth. Avoid being too brief or overly terse, and ensure that the elaboration provides useful, actionable insights in every section.
The response should only contain the Emacs Org formatted output.
Use the following structure:
1. The file should have a #+title: and #+author: and #+date: header with the #+date: header as %s
2. Include a "Summary" section that gives a brief overview of the key points, with detailed elaboration.
3. Include a "Notes" section, with **subsections** that organize the content logically. For each note, please ensure that detailed explanations, examples, and any relevant insights are included.
Here is the content to summarize:
%s
Please format the response as a valid Emacs Org file.`, today, transcriptionText)
}