Repository navigation
Expand file tree
/
Copy pathmain.py
More file actions
704 lines (565 loc) · 26.9 KB
/
Copy pathmain.py
File metadata and controls
704 lines (565 loc) · 26.9 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
#!/usr/bin/env python3
"""
Recording to Tasks - Trasforma registrazioni audio/video in trascrizioni e to-do list
Utilizza OpenAI Whisper per la trascrizione e GPT per l'analisi e generazione di task.
"""
import os
import sys
import argparse
import subprocess
import time
import math
import concurrent.futures
import re
import json
from pathlib import Path
from typing import List, Tuple, Optional, Dict, Any
# Third-party imports
from openai import OpenAI
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
# Configuration
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
OPENAI_ORG_ID = os.getenv("OPENAI_ORG_ID")
TRANSCRIPTION_MODEL = os.getenv("TRANSCRIPTION_MODEL", "gpt-4o-transcribe")
ANALYSIS_MODEL = os.getenv("ANALYSIS_MODEL", "gpt-5-mini")
LANGUAGE = os.getenv("LANGUAGE", "it")
ENABLE_DIARIZATION = os.getenv("ENABLE_DIARIZATION", "false").lower() == "true"
NUM_SPEAKERS = int(os.getenv("NUM_SPEAKERS", "2"))
MAX_RETRIES = int(os.getenv("MAX_RETRIES", "3"))
MAX_PARALLEL_TASKS = int(os.getenv("MAX_PARALLEL_TASKS", "3"))
SIZE_LIMIT_MB = int(os.getenv("SIZE_LIMIT_MB", "20"))
# Derived constants
SIZE_LIMIT = SIZE_LIMIT_MB * 1024 * 1024 # Convert to bytes
TEMP_DIR = "temp"
OUTPUT_DIR = "output"
# Supported file formats
AUDIO_FORMATS = {'.wav', '.mp3', '.m4a', '.flac', '.aac', '.ogg', '.wma'}
VIDEO_FORMATS = {'.mp4', '.mov', '.avi', '.mkv', '.wmv', '.flv', '.webm', '.m4v'}
SUPPORTED_FORMATS = AUDIO_FORMATS | VIDEO_FORMATS
# Initialize OpenAI client
if not OPENAI_API_KEY:
print("❌ Error: OPENAI_API_KEY not found in environment variables.")
print("Please create a .env file with your OpenAI API key.")
sys.exit(1)
client = OpenAI(
api_key=OPENAI_API_KEY,
organization=OPENAI_ORG_ID if OPENAI_ORG_ID else None
)
# Create necessary directories
os.makedirs(TEMP_DIR, exist_ok=True)
os.makedirs(OUTPUT_DIR, exist_ok=True)
def log_info(message: str):
"""Log info message with timestamp."""
print(f"ℹ️ {message}")
def log_success(message: str):
"""Log success message."""
print(f"✅ {message}")
def log_warning(message: str):
"""Log warning message."""
print(f"⚠️ {message}")
def log_error(message: str):
"""Log error message."""
print(f"❌ {message}")
def log_section(message: str):
"""Log section header."""
print(f"\n🔄 {message}")
print("=" * (len(message) + 3))
def clean_filename(filepath: str) -> str:
"""Clean filename for safe file operations."""
filename = Path(filepath).stem
# Remove special characters and spaces
clean_name = re.sub(r'[^\w\-_]', '_', filename)
# Remove consecutive underscores
clean_name = re.sub(r'_+', '_', clean_name)
# Remove leading/trailing underscores
clean_name = clean_name.strip('_')
return clean_name
def check_dependencies():
"""Check if required external dependencies are installed."""
try:
subprocess.run(["ffmpeg", "-version"],
capture_output=True, check=True)
log_success("ffmpeg is installed")
except (subprocess.CalledProcessError, FileNotFoundError):
log_error("ffmpeg is not installed or not in PATH")
log_info("Please install ffmpeg:")
log_info(" macOS: brew install ffmpeg")
log_info(" Ubuntu: sudo apt install ffmpeg")
log_info(" Windows: Download from https://ffmpeg.org/download.html")
sys.exit(1)
def extract_audio_from_video(video_path: str) -> str:
"""Extract audio from video file."""
clean_name = clean_filename(video_path)
audio_path = f"{TEMP_DIR}/{clean_name}_extracted.wav"
log_info(f"Extracting audio: {video_path} → {audio_path}")
try:
subprocess.run([
"ffmpeg", "-i", video_path,
"-vn", # No video
"-acodec", "pcm_s16le", # Audio codec
"-ar", "44100", # Sample rate
"-ac", "2", # Stereo
audio_path
], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
log_success("Audio extraction successful!")
return audio_path
except subprocess.CalledProcessError as e:
log_error(f"Error extracting audio from {video_path}: {e}")
return None
def convert_to_wav(audio_path: str) -> str:
"""Convert audio file to WAV format."""
# If already extracted, return as-is
if audio_path.endswith("_extracted.wav"):
return audio_path
clean_name = clean_filename(audio_path)
wav_path = f"{TEMP_DIR}/{clean_name}.wav"
log_info(f"Converting: {audio_path} → {wav_path}")
try:
subprocess.run([
"ffmpeg", "-i", audio_path,
"-ar", "44100", wav_path
], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
log_success("Conversion successful!")
return wav_path
except subprocess.CalledProcessError as e:
log_error(f"Error converting {audio_path}: {e}")
return None
def get_audio_duration(wav_path: str) -> float:
"""Get the duration of an audio file."""
duration_cmd = [
"ffprobe", "-i", wav_path,
"-show_entries", "format=duration",
"-v", "quiet", "-of", "csv=p=0"
]
duration_output = subprocess.run(duration_cmd, capture_output=True, text=True)
try:
duration = float(duration_output.stdout.strip())
log_info(f"Audio duration: {duration:.2f} seconds ({duration/60:.1f} minutes)")
return duration
except ValueError:
log_error(f"Could not determine duration of {wav_path}")
return None
def create_chunks(wav_path: str, duration: float) -> List[Tuple[float, float, str]]:
"""Split audio file into chunks if needed."""
file_size = os.path.getsize(wav_path)
clean_name = clean_filename(wav_path)
# If file is already small enough, no need to chunk
if file_size <= SIZE_LIMIT:
log_info(f"File size ({file_size/1024/1024:.2f}MB) within limit. No need to chunk.")
return [(0, duration, wav_path)]
# Calculate number of chunks needed
num_chunks = math.ceil(file_size / (SIZE_LIMIT * 0.9)) # 10% buffer
chunk_duration = duration / num_chunks
# Create chunks
log_info(f"File size ({file_size/1024/1024:.2f}MB) exceeds limit. Splitting into {num_chunks} chunks.")
chunks = []
for i in range(num_chunks):
start_time = i * chunk_duration
end_time = min((i + 1) * chunk_duration, duration)
chunk_path = f"{TEMP_DIR}/{clean_name}_chunk{i+1}.wav"
# Use ffmpeg to extract the chunk
subprocess.run([
"ffmpeg", "-i", wav_path,
"-ss", str(start_time),
"-to", str(end_time),
"-c", "copy", chunk_path
], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
chunks.append((start_time, end_time, chunk_path))
log_success(f"Created chunk {i+1}/{num_chunks}: {start_time:.2f}s to {end_time:.2f}s")
return chunks
def transcribe_chunk(chunk_data: Tuple[float, float, str]) -> Tuple[str, str]:
"""Transcribe audio chunk using OpenAI API with retry logic."""
start_time, end_time, chunk_path = chunk_data
retries = 0
while retries < MAX_RETRIES:
try:
with open(chunk_path, "rb") as audio_file:
transcription = client.audio.transcriptions.create(
model=TRANSCRIPTION_MODEL,
file=audio_file,
language=LANGUAGE # Improves accuracy and latency
)
# Add timestamp prefix to the transcription
timestamp = f"[{int(start_time//3600):02d}:{int((start_time%3600)//60):02d}:{int(start_time%60):02d}]"
return timestamp, f"{timestamp} {transcription.text}"
except Exception as e:
retries += 1
error_message = str(e)
log_warning(f"Error transcribing chunk {chunk_path} (attempt {retries}/{MAX_RETRIES}): {error_message}")
# Progressively longer wait between retries
wait_time = 2 ** retries # Exponential backoff
if wait_time > 60:
wait_time = 60 # Cap at 60 seconds
log_info(f"Waiting {wait_time}s before retry...")
time.sleep(wait_time)
# If this was the last retry, return an error message
if retries >= MAX_RETRIES:
log_error(f"Failed to transcribe chunk {chunk_path} after {MAX_RETRIES} attempts: {error_message}")
timestamp = f"[{int(start_time//3600):02d}:{int((start_time%3600)//60):02d}:{int(start_time%60):02d}]"
return timestamp, f"{timestamp} [ERROR] Failed to transcribe after {MAX_RETRIES} attempts: {error_message}"
def generate_summary_and_tasks(transcription_text: str, original_filename: str) -> str:
"""Generate summary and tasks from transcription using GPT with structured JSON output."""
log_section("Generating summary and tasks")
prompt = f"""Analizza questa trascrizione di una call tra 2 persone (in italiano) ed estrai SOLO task concrete e actionable.
REGOLE DI FILTRAGGIO RIGIDE:
- Includi SOLO compiti concreti con azioni specifiche da fare
- Ignora completamente: saluti, chiacchiere casuali, discussioni generiche senza conclusione
- Cerca frasi con commitment: "devo fare", "dobbiamo", "ti occupi tu", "entro [data]", "faccio io"
- Escludi discussioni vaghe: "dovremmo pensare a", "sarebbe bello se", "magari un giorno", "potremmo"
- Se una discussione non porta a una decisione concreta, NON creare un task
FORMATO OUTPUT - Rispondi SOLO con JSON valido (no markdown, no code block):
{{
"riassunto": "Breve sintesi in 2-3 frasi di cosa si è deciso concretamente",
"task": [
{{
"titolo": "Titolo breve e chiaro del task",
"descrizione": "Descrizione dettagliata di cosa fare, come farlo e perché",
"responsabile": "Nome della persona o TBD se non specificato",
"scadenza": "Data/periodo specifico o TBD",
"priorita": "alta|media|bassa",
"categoria": "sviluppo|testing|documentazione|meeting|infrastruttura|altro",
"contesto": "Breve contesto della discussione che ha generato questo task"
}}
],
"decisioni": [
"Decisione concreta 1 presa durante la call",
"Decisione concreta 2 presa durante la call"
],
"prossimi_passi": [
"Prossimo passo 1",
"Prossimo passo 2"
],
"note": "Informazioni tecniche importanti, link, riferimenti menzionati"
}}
ESEMPI DI FILTRAGGIO:
✅ INCLUDI: "Ok perfetto, quindi tu fai il refactoring del modulo utenti entro venerdì"
→ Task: Refactoring modulo gestione utenti
✅ INCLUDI: "Devo sistemare quel bug dell'autenticazione prima del deploy"
→ Task: Fix bug autenticazione
❌ ESCLUDI: "Eh sì, sarebbe carino se un giorno rifacessimo quella parte"
→ Troppo vago, nessun commitment
❌ ESCLUDI: "Ciao come stai?" "Bene e tu?" "Tutto ok"
→ Chiacchiere casuali
TRASCRIZIONE:
{transcription_text}
Rispondi SOLO con il JSON, senza altri commenti o formattazione markdown."""
# Estimate token usage before API call
input_tokens_estimate = len(prompt) // 4 # Rough estimate: 1 token ≈ 4 chars
log_info(f"Estimated input tokens: {input_tokens_estimate:,}")
if input_tokens_estimate > 100000:
log_warning(f"Large input detected ({input_tokens_estimate:,} tokens). This may take longer to process.")
retries = 0
while retries < MAX_RETRIES:
try:
response = client.chat.completions.create(
model=ANALYSIS_MODEL,
messages=[
{"role": "system", "content": "Sei un assistente esperto nell'analisi di riunioni di sviluppo software. Estrai solo task concrete e actionable, ignorando discussioni vaghe. Rispondi SEMPRE e SOLO in formato JSON valido, in italiano."},
{"role": "user", "content": prompt}
],
max_completion_tokens=8000, # Increased for long transcriptions (was 3000)
# temperature parameter removed - GPT-5 models only support default value (1)
response_format={"type": "json_object"} # Ensure JSON output
)
json_response = response.choices[0].message.content
finish_reason = response.choices[0].finish_reason
# CRITICAL: Validate response before parsing
if finish_reason != "stop":
error_msg = f"Response incomplete: finish_reason={finish_reason}"
if finish_reason == "length":
error_msg += " (Token limit exceeded - response was truncated)"
log_warning(error_msg)
log_warning(f"Input length: {len(transcription_text)} chars (~{len(transcription_text)//4} tokens)")
raise Exception(error_msg)
if not json_response or not json_response.strip():
log_warning("Empty response from API")
log_warning(f"Response object finish_reason: {finish_reason}")
raise Exception("API returned empty content")
# Parse JSON response
try:
data = json.loads(json_response)
markdown_output = convert_json_to_markdown(data, original_filename)
log_success("Summary and tasks generated successfully!")
return markdown_output
except json.JSONDecodeError as json_err:
log_warning(f"Failed to parse JSON response: {json_err}")
log_warning(f"Raw response: {json_response[:200]}...")
# Fallback to raw response if JSON parsing fails
return f"# Analisi - {original_filename}\n\n{json_response}"
except Exception as e:
retries += 1
error_message = str(e)
log_warning(f"Error generating summary (attempt {retries}/{MAX_RETRIES}): {error_message}")
# Enhanced diagnostic logging
log_warning(f"Input length: {len(transcription_text)} chars (~{len(transcription_text)//4} estimated tokens)")
if hasattr(e, 'response'):
log_warning(f"API response details: {e.response}")
if retries < MAX_RETRIES:
wait_time = 2 ** retries
log_info(f"Waiting {wait_time}s before retry...")
time.sleep(wait_time)
else:
log_error(f"Failed to generate summary after {MAX_RETRIES} attempts")
return f"# Errore nella generazione del riassunto\n\nNon è stato possibile generare il riassunto per il file {original_filename}.\nErrore: {error_message}\n\n## Trascrizione originale\n\n{transcription_text}"
def convert_json_to_markdown(data: Dict[str, Any], filename: str) -> str:
"""Convert structured JSON data to formatted Markdown."""
md = []
# Riassunto Esecutivo
if data.get("riassunto"):
md.append("## 📋 Riassunto Esecutivo\n")
md.append(f"{data['riassunto']}\n")
# Task - Ordinati per priorità
if data.get("task") and len(data["task"]) > 0:
md.append("## ✅ Action Items / To-Do List\n")
# Raggruppa per categoria
tasks_by_category = {}
for task in data["task"]:
category = task.get("categoria", "altro")
if category not in tasks_by_category:
tasks_by_category[category] = []
tasks_by_category[category].append(task)
# Ordine priorità categorie sviluppo > testing > altro
category_order = ["sviluppo", "testing", "documentazione", "infrastruttura", "meeting", "altro"]
for category in category_order:
if category in tasks_by_category:
md.append(f"### {category.capitalize()}\n")
# Ordina per priorità: alta > media > bassa
priority_order = {"alta": 0, "media": 1, "bassa": 2}
sorted_tasks = sorted(
tasks_by_category[category],
key=lambda t: priority_order.get(t.get("priorita", "media"), 1)
)
for task in sorted_tasks:
priority_emoji = {"alta": "🔴", "media": "🟡", "bassa": "🟢"}.get(task.get("priorita", "media"), "⚪")
titolo = task.get("titolo", "Task senza titolo")
responsabile = task.get("responsabile", "TBD")
scadenza = task.get("scadenza", "TBD")
md.append(f"- [ ] {priority_emoji} **{titolo}**\n")
if task.get("descrizione"):
md.append(f" - *Descrizione*: {task['descrizione']}\n")
md.append(f" - *Responsabile*: {responsabile}\n")
md.append(f" - *Scadenza*: {scadenza}\n")
if task.get("contesto"):
md.append(f" - *Contesto*: {task['contesto']}\n")
md.append("\n")
# Decisioni
if data.get("decisioni") and len(data["decisioni"]) > 0:
md.append("## 🎯 Decisioni Prese\n")
for i, decisione in enumerate(data["decisioni"], 1):
md.append(f"{i}. {decisione}\n")
md.append("\n")
# Prossimi Passi
if data.get("prossimi_passi") and len(data["prossimi_passi"]) > 0:
md.append("## 🚀 Prossimi Passi\n")
for passo in data["prossimi_passi"]:
md.append(f"- {passo}\n")
md.append("\n")
# Note Aggiuntive
if data.get("note") and data["note"].strip():
md.append("## 📝 Note Aggiuntive\n")
md.append(f"{data['note']}\n")
return "".join(md)
def process_file(file_path: str, is_transcription_file: bool = False) -> bool:
"""
Process a single audio/video file or transcription file.
Args:
file_path: Path to the file to process
is_transcription_file: If True, treats the file as an existing transcription (.txt)
and skips audio processing, going directly to task analysis
"""
log_section(f"Processing {os.path.basename(file_path)}")
# Check if file exists
if not os.path.exists(file_path):
log_error(f"File not found: {file_path}")
return False
file_ext = Path(file_path).suffix.lower()
# Handle transcription file mode
if is_transcription_file:
if file_ext != '.txt':
log_error(f"With --transcription flag, only .txt files are supported. Got: {file_ext}")
return False
log_info("Loading existing transcription file...")
# Load transcription from file
try:
with open(file_path, "r", encoding="utf-8") as f:
full_transcription = f.read()
# Remove any header/metadata if present (lines starting with # or **)
lines = full_transcription.split('\n')
content_lines = []
skip_header = True
for line in lines:
if skip_header:
# Skip header lines (markdown headers, metadata, separators)
if line.strip().startswith('#') or line.strip().startswith('**') or line.strip() == '---':
continue
elif line.strip(): # Found first content line
skip_header = False
content_lines.append(line)
else:
content_lines.append(line)
full_transcription = '\n'.join(content_lines).strip()
if not full_transcription:
log_error("Transcription file is empty or contains only headers")
return False
log_success(f"Loaded transcription: {len(full_transcription)} characters")
except Exception as e:
log_error(f"Failed to read transcription file: {str(e)}")
return False
# Create output filename for tasks only
clean_name = clean_filename(file_path)
tasks_filename = f"{OUTPUT_DIR}/{clean_name}_tasks.md"
# Generate and save summary/tasks
log_section("Generating summary and tasks")
summary = generate_summary_and_tasks(full_transcription, os.path.basename(file_path))
with open(tasks_filename, "w", encoding="utf-8") as f:
f.write(f"# Analisi e Task - {os.path.basename(file_path)}\n\n")
f.write(f"**File trascrizione:** {file_path}\n")
f.write(f"**Elaborato il:** {time.strftime('%Y-%m-%d %H:%M:%S')}\n\n")
f.write("---\n\n")
f.write(summary)
log_success(f"Tasks and summary saved to: {tasks_filename}")
return True
# Normal audio/video processing flow
# Check file format
if file_ext not in SUPPORTED_FORMATS:
log_error(f"Unsupported file format: {file_ext}")
log_info(f"Supported formats: {', '.join(sorted(SUPPORTED_FORMATS))}")
return False
# Extract audio from video if needed
if file_ext in VIDEO_FORMATS:
audio_path = extract_audio_from_video(file_path)
if not audio_path:
return False
else:
audio_path = file_path
# Convert audio to WAV
wav_path = convert_to_wav(audio_path)
if not wav_path:
return False
# Get audio duration
duration = get_audio_duration(wav_path)
if not duration:
return False
# Create chunks if needed
chunks = create_chunks(wav_path, duration)
# Transcribe each chunk in parallel
log_section(f"Transcribing {len(chunks)} chunks in parallel (max {MAX_PARALLEL_TASKS} workers)")
all_transcriptions = []
with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_PARALLEL_TASKS) as executor:
# Submit all transcription tasks
future_to_chunk = {executor.submit(transcribe_chunk, chunk): idx for idx, chunk in enumerate(chunks)}
# Process as they complete
completed = 0
for future in concurrent.futures.as_completed(future_to_chunk):
chunk_idx = future_to_chunk[future]
try:
timestamp, transcription = future.result()
all_transcriptions.append((timestamp, transcription))
completed += 1
log_success(f"Completed transcription {completed}/{len(chunks)} ({timestamp})")
except Exception as e:
log_error(f"Error in chunk {chunk_idx+1}: {str(e)}")
# Sort transcriptions by timestamp
all_transcriptions.sort()
sorted_transcriptions = [t[1] for t in all_transcriptions]
full_transcription = "\n\n".join(sorted_transcriptions)
# Create output filenames
clean_name = clean_filename(file_path)
transcription_filename = f"{OUTPUT_DIR}/{clean_name}_transcription.txt"
tasks_filename = f"{OUTPUT_DIR}/{clean_name}_tasks.md"
# Save transcription
with open(transcription_filename, "w", encoding="utf-8") as f:
f.write(f"# Trascrizione di {os.path.basename(file_path)}\n\n")
f.write(f"**File originale:** {file_path}\n")
f.write(f"**Durata:** {duration:.2f} secondi ({duration/60:.1f} minuti)\n")
f.write(f"**Elaborato il:** {time.strftime('%Y-%m-%d %H:%M:%S')}\n\n")
f.write("---\n\n")
f.write(full_transcription)
log_success(f"Transcription saved to: {transcription_filename}")
# Generate and save summary/tasks
summary = generate_summary_and_tasks(full_transcription, os.path.basename(file_path))
with open(tasks_filename, "w", encoding="utf-8") as f:
f.write(f"# Analisi e Task - {os.path.basename(file_path)}\n\n")
f.write(f"**File originale:** {file_path}\n")
f.write(f"**Durata:** {duration:.2f} secondi ({duration/60:.1f} minuti)\n")
f.write(f"**Elaborato il:** {time.strftime('%Y-%m-%d %H:%M:%S')}\n\n")
f.write("---\n\n")
f.write(summary)
log_success(f"Tasks and summary saved to: {tasks_filename}")
# Cleanup temporary files
for _, _, chunk_path in chunks:
if chunk_path != wav_path: # Don't delete the main wav file if it's the only chunk
try:
os.remove(chunk_path)
except:
pass
# Remove temporary wav file if it was created from video
if file_ext in VIDEO_FORMATS and wav_path.endswith("_extracted.wav"):
try:
os.remove(wav_path)
except:
pass
elif wav_path != audio_path: # Remove converted wav if different from original
try:
os.remove(wav_path)
except:
pass
return True
def main():
"""Main function."""
parser = argparse.ArgumentParser(
description="Recording to Tasks - Trasforma registrazioni in trascrizioni e to-do list",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Esempi:
# Processa file audio/video (trascrizione + analisi)
python main.py meeting.mp4
python main.py call.wav
python main.py file1.mp4 file2.wav file3.m4a
# Usa trascrizione esistente (solo analisi task, RISPARMIA COSTI!)
python main.py -t output/meeting_transcription.txt
python main.py --transcription trascrizione.txt
Formati supportati:
Audio: .wav, .mp3, .m4a, .flac, .aac, .ogg, .wma
Video: .mp4, .mov, .avi, .mkv, .wmv, .flv, .webm, .m4v
Trascrizioni: .txt (con flag -t/--transcription)
"""
)
parser.add_argument(
"files",
nargs="+",
help="Uno o più file audio/video da processare (o file .txt se --transcription è usato)"
)
parser.add_argument(
"-t", "--transcription",
action="store_true",
help="Indica che i file sono già trascrizioni (.txt). Salta la trascrizione audio e processa solo l'analisi task."
)
parser.add_argument(
"--version",
action="version",
version="Recording to Tasks 1.0.0"
)
args = parser.parse_args()
# Check dependencies
check_dependencies()
# Process each file
successful = 0
total = len(args.files)
for file_path in args.files:
if process_file(file_path, is_transcription_file=args.transcription):
successful += 1
print() # Add spacing between files
# Final summary
log_section("Processing Complete")
log_success(f"Successfully processed {successful}/{total} files")
if successful > 0:
log_info(f"Output files saved in: {OUTPUT_DIR}/")
log_info("Files generated:")
log_info(" - *_transcription.txt (trascrizione completa)")
log_info(" - *_tasks.md (riassunto e to-do list)")
return 0 if successful == total else 1
if __name__ == "__main__":
sys.exit(main())