dahyedahye commited on
Commit
c12e8b3
Β·
1 Parent(s): 905c475
.env ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ SMTP_USER=kyowoon.lee1924@gmail.com
2
+ SMTP_PASSWORD=rhwy amyv hdwq pspa
__pycache__/app.cpython-310.pyc ADDED
Binary file (2.79 kB). View file
 
__pycache__/app.cpython-37.pyc ADDED
Binary file (2.78 kB). View file
 
__pycache__/app.cpython-39.pyc ADDED
Binary file (3.74 kB). View file
 
app.py CHANGED
@@ -1,65 +1,126 @@
1
  import os
2
- import shutil
3
- from fastapi import FastAPI, File, UploadFile, Form
4
- from fastapi.responses import FileResponse, JSONResponse
5
  import whisper
 
 
 
 
 
 
 
6
 
7
- app = FastAPI()
8
 
9
- # Whisper λͺ¨λΈ λ‘œλ“œ (ν•„μš”μ— 따라 λͺ¨λΈ 크기λ₯Ό μ„ νƒν•˜μ„Έμš”)
10
- model = whisper.load_model("tiny") # "tiny", "base", "small", "medium", "large-v2" λ“±
11
 
12
- @app.post("/transcribe/")
13
- def transcribe_video(
14
- file: UploadFile = File(...),
15
- language: str = Form("en") # μ–Έμ–΄ 선택 κ°€λŠ₯ (κΈ°λ³Έκ°’: μ˜μ–΄)
16
- ):
 
 
 
 
 
 
 
 
 
 
 
17
  """
18
- Upload a video/audio file and get the generated SRT file as a response.
19
  """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
  try:
21
- # Create a temporary directory
22
- temp_dir = "temp"
23
- os.makedirs(temp_dir, exist_ok=True)
24
-
25
- # Save the uploaded file temporarily
26
- input_file_path = os.path.join(temp_dir, file.filename)
27
- with open(input_file_path, "wb") as buffer:
28
- shutil.copyfileobj(file.file, buffer)
29
-
30
- # Transcribe the file using Whisper
31
- result = model.transcribe(input_file_path, language=language)
32
-
33
- # SRT 파일 생성
34
- srt_file_path = os.path.join(temp_dir, "output.srt")
35
  with open(srt_file_path, "w") as srt_file:
36
  for i, segment in enumerate(result["segments"]):
37
  start = segment['start']
38
  end = segment['end']
39
- text = segment['text'][1:] # Remove leading space
40
 
41
- # νƒ€μž„μŠ€νƒ¬ν”„ ν˜•μ‹ λ³€ν™˜ (SRT ν˜•μ‹μ— 맞게)
42
  start_time = f"{int(start // 3600):02}:{int((start % 3600) // 60):02}:{int(start % 60):02},{int((start * 1000) % 1000):03}"
43
  end_time = f"{int(end // 3600):02}:{int((end % 3600) // 60):02}:{int(end % 60):02},{int((end * 1000) % 1000):03}"
44
 
45
- # SRT νŒŒμΌμ— 기둝
46
  srt_file.write(f"{i + 1}\n")
47
  srt_file.write(f"{start_time} --> {end_time}\n")
48
  srt_file.write(f"{text}\n\n")
49
-
50
- # Return the SRT file as a response
51
- return FileResponse(
52
- path=srt_file_path,
53
- filename="output.srt",
54
- media_type='application/x-subrip'
55
- )
56
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57
  except Exception as e:
58
- return JSONResponse(status_code=500, content={"message": str(e)})
59
-
60
- finally:
61
- # Clean up temporary files
62
- if os.path.exists(input_file_path):
63
- os.remove(input_file_path)
64
- if os.path.exists(srt_file_path):
65
- os.remove(srt_file_path)
 
1
  import os
2
+ import re
3
+ import uuid
4
+ import gdown
5
  import whisper
6
+ import smtplib
7
+ from email.mime.text import MIMEText
8
+ from email.mime.multipart import MIMEMultipart
9
+ from concurrent.futures import ThreadPoolExecutor
10
+ from fastapi import FastAPI, HTTPException, BackgroundTasks
11
+ from fastapi.responses import JSONResponse
12
+ from dotenv import load_dotenv
13
 
14
+ # ꡬ글 λ“œλΌμ΄λΈŒ 링크, μ–΄λ–€ μ–Έμ–΄, 받을 이메일 μ£Όμ†Œ
15
 
16
+ # .env νŒŒμΌμ—μ„œ μ€‘μš”ν•œ ν™˜κ²½ λ³€μˆ˜ λ‘œλ“œ
17
+ load_dotenv()
18
 
19
+ app = FastAPI(
20
+ version="0.0.1",
21
+ servers=[
22
+ {
23
+ "url": "https://leekwoon-whisper-api.hf.space",
24
+ "description": "video/audio transcription API",
25
+ }
26
+ ],
27
+ )
28
+
29
+ # Whisper λͺ¨λΈ λ‘œλ“œ
30
+ model = whisper.load_model("tiny")
31
+
32
+ executor = ThreadPoolExecutor(max_workers=3) # μ΅œλŒ€ 3개의 μŠ€λ ˆλ“œλ‘œ 비동기 μž‘μ—… 처리
33
+
34
+ def extract_file_id(drive_url: str) -> str:
35
  """
36
+ Google Drive URLμ—μ„œ 파일 IDλ₯Ό μΆ”μΆœν•©λ‹ˆλ‹€.
37
  """
38
+ match = re.search(r'/d/([a-zA-Z0-9_-]+)', drive_url)
39
+ if match:
40
+ return match.group(1)
41
+ match = re.search(r'file/d/([a-zA-Z0-9_-]+)', drive_url)
42
+ if match:
43
+ return match.group(1)
44
+ match = re.search(r'([a-zA-Z0-9_-]{33,})', drive_url)
45
+ if match:
46
+ return match.group(1)
47
+ raise ValueError("Invalid Google Drive URL")
48
+
49
+ def send_email(to_email: str, srt_file_path: str, transcription_time: float):
50
+ smtp_server = "smtp.gmail.com"
51
+ smtp_port = 587
52
+ smtp_user = os.getenv("SMTP_USER")
53
+ smtp_password = os.getenv("SMTP_PASSWORD")
54
+
55
+ subject = "[kyobody - μžλ§‰μƒμ„±] μž‘μ—…μ΄ μ™„λ£Œλ˜μ—ˆμŠ΅λ‹ˆλ‹€."
56
+ body = f"[kyobody - μžλ§‰μƒμ„±] μž‘μ—…μ΄ μ™„λ£Œλ˜μ—ˆμŠ΅λ‹ˆλ‹€. 총 μ†Œμš” μ‹œκ°„: {transcription_time:.2f} 초. SRT νŒŒμΌμ„ μ²¨λΆ€ν•©λ‹ˆλ‹€."
57
+
58
+ msg = MIMEMultipart()
59
+ msg["From"] = smtp_user
60
+ msg["To"] = to_email
61
+ msg["Subject"] = subject
62
+
63
+ msg.attach(MIMEText(body, "plain"))
64
+
65
+ with open(srt_file_path, "r") as file:
66
+ attachment = MIMEText(file.read())
67
+ attachment.add_header("Content-Disposition", "attachment", filename=os.path.basename(srt_file_path))
68
+ msg.attach(attachment)
69
+
70
+ with smtplib.SMTP(smtp_server, smtp_port) as server:
71
+ server.starttls()
72
+ server.login(smtp_user, smtp_password)
73
+ server.sendmail(smtp_user, to_email, msg.as_string())
74
+
75
+ def transcribe_and_send_email(temp_input_file: str, srt_file_path: str, email: str):
76
  try:
77
+ # Transcribe the video/audio file
78
+ import time
79
+ start_time = time.time()
80
+ result = model.transcribe(temp_input_file)
81
+ transcription_time = time.time() - start_time
82
+
83
+ # Save the transcription to an SRT file
 
 
 
 
 
 
 
84
  with open(srt_file_path, "w") as srt_file:
85
  for i, segment in enumerate(result["segments"]):
86
  start = segment['start']
87
  end = segment['end']
88
+ text = segment['text'][1:]
89
 
 
90
  start_time = f"{int(start // 3600):02}:{int((start % 3600) // 60):02}:{int(start % 60):02},{int((start * 1000) % 1000):03}"
91
  end_time = f"{int(end // 3600):02}:{int((end % 3600) // 60):02}:{int(end % 60):02},{int((end * 1000) % 1000):03}"
92
 
 
93
  srt_file.write(f"{i + 1}\n")
94
  srt_file.write(f"{start_time} --> {end_time}\n")
95
  srt_file.write(f"{text}\n\n")
96
+
97
+ # Send the result via email
98
+ send_email(email, srt_file_path, transcription_time)
99
+
100
+ # Clean up the temporary files
101
+ os.remove(temp_input_file)
102
+ os.remove(srt_file_path)
103
+
104
+ except Exception as e:
105
+ print(f"Error in transcription or email sending: {e}")
106
+
107
+ @app.post("/transcribe/")
108
+ def transcribe_video(url: str, email: str, background_tasks: BackgroundTasks):
109
+ try:
110
+ # Extract file ID and download the file
111
+ file_id = extract_file_id(url)
112
+ download_url = f"https://drive.google.com/uc?id={file_id}"
113
+ temp_input_file = f'/tmp/{uuid.uuid4()}.mp4'
114
+ gdown.download(download_url, temp_input_file, quiet=False)
115
+
116
+ # Define SRT file path
117
+ srt_file_path = f'/tmp/{uuid.uuid4()}.srt'
118
+
119
+ # Schedule the transcription and email sending in the background
120
+ background_tasks.add_task(executor.submit, transcribe_and_send_email, temp_input_file, srt_file_path, email)
121
+
122
+ # Respond to the client immediately
123
+ return JSONResponse(status_code=202, content={"message": "Transcription started, you will receive an email when it's done."})
124
+
125
  except Exception as e:
126
+ raise HTTPException(status_code=500, detail=str(e))
 
 
 
 
 
 
 
requirements.txt CHANGED
@@ -3,4 +3,5 @@ openai-whisper # Whisper 라이브러리λ₯Ό μ„€μΉ˜ν•©λ‹ˆλ‹€.
3
 
4
  fastapi # FastAPI ν”„λ ˆμž„μ›Œν¬
5
  uvicorn # FastAPI μ„œλ²„ 싀행을 μœ„ν•œ Uvicorn ASGI μ„œλ²„
6
- python-multipart
 
 
3
 
4
  fastapi # FastAPI ν”„λ ˆμž„μ›Œν¬
5
  uvicorn # FastAPI μ„œλ²„ 싀행을 μœ„ν•œ Uvicorn ASGI μ„œλ²„
6
+ python-dotenv
7
+ gdown