fix: Update gemini_transcribe.py to use Service Account auth and SOCKS5 proxy

This commit is contained in:
Admin 2026-07-05 22:10:52 +04:00
parent 6374a50717
commit 3a050af68a

View file

@ -2,11 +2,26 @@
import os import os
import sys import sys
import time import time
from google.oauth2 import service_account
import google.generativeai as genai import google.generativeai as genai
# Config API key # Setup proxies for Google API routing through SOCKS5 proxy (RKN bypass)
API_KEY = os.getenv("GOOGLE_API_KEY", "AIzaSyD09NxPpyTk4RZLGqE6dFzJwNxhawRAegc") os.environ["https_proxy"] = "socks5h://127.0.0.1:10808"
genai.configure(api_key=API_KEY) os.environ["http_proxy"] = "socks5h://127.0.0.1:10808"
os.environ["all_proxy"] = "socks5h://127.0.0.1:10808"
# Auth using Service Account (avoids invalid GCP API key errors)
SERVICE_ACCOUNT_FILE = "/home/matrixhasyou/domovoy_google_creds.json"
try:
creds = service_account.Credentials.from_service_account_file(
SERVICE_ACCOUNT_FILE,
scopes=["https://www.googleapis.com/auth/generative-language", "https://www.googleapis.com/auth/drive"]
)
genai.configure(credentials=creds)
print("Authenticated successfully using Google Service Account.", flush=True)
except Exception as e:
print(f"Authentication failed: {e}", flush=True)
sys.exit(1)
BOT_TOKEN = "8725618164:AAH1tGalq-pw1l0t4P5c0sdLkCVJdh7IE7M" BOT_TOKEN = "8725618164:AAH1tGalq-pw1l0t4P5c0sdLkCVJdh7IE7M"
CHAT_ID = "197957361" CHAT_ID = "197957361"
@ -16,31 +31,33 @@ def send_tg(msg):
import urllib.request import urllib.request
try: try:
url = f"https://api.telegram.org/bot{BOT_TOKEN}/sendMessage" url = f"https://api.telegram.org/bot{BOT_TOKEN}/sendMessage"
data = urllib.parse.urlencode({"chat_id": CHAT_ID, "text": msg, "parse_mode": "markdown"}).encode("utf-8") # Split message if it's too long for TG limit (4096 chars)
for chunk in [msg[i:i+4000] for i in range(0, len(msg), 4000)]:
data = urllib.parse.urlencode({"chat_id": CHAT_ID, "text": chunk, "parse_mode": "markdown"}).encode("utf-8")
req = urllib.request.Request(url, data=data) req = urllib.request.Request(url, data=data)
urllib.request.urlopen(req, timeout=15) urllib.request.urlopen(req, timeout=15)
except Exception as e: except Exception as e:
print(f"Failed to send Telegram message: {e}") print(f"Failed to send Telegram message: {e}", flush=True)
def transcribe_audio(audio_path, output_prefix, model_name="gemini-1.5-pro"): def transcribe_audio(audio_path, output_prefix, model_name="gemini-1.5-pro"):
if not os.path.exists(audio_path): if not os.path.exists(audio_path):
print(f"Error: File not found: {audio_path}") print(f"Error: File not found: {audio_path}", flush=True)
sys.exit(1) sys.exit(1)
size_mb = os.path.getsize(audio_path) / (1024 * 1024) size_mb = os.path.getsize(audio_path) / (1024 * 1024)
print(f"File size: {size_mb:.2f} MB") print(f"File size: {size_mb:.2f} MB", flush=True)
send_tg(f"🎙 **Транскрибация аудио через Gemini:**\nФайл: `{os.path.basename(audio_path)}` ({size_mb:.1f} MB)\nМодель: `{model_name}`\n\n*Запуск выгрузки в Google API...*") send_tg(f"🎙 **Транскрибация аудио через Gemini:**\nФайл: `{os.path.basename(audio_path)}` ({size_mb:.1f} MB)\nМодель: `{model_name}`\n\n*Запуск выгрузки в Google API...*")
# 1. Upload file # 1. Upload file
print(f"Uploading {audio_path} to Google Gemini File API...") print(f"Uploading {audio_path} to Google Gemini File API...", flush=True)
audio_file = genai.upload_file(path=audio_path) audio_file = genai.upload_file(path=audio_path)
print(f"File uploaded successfully! API Name: {audio_file.name}") print(f"File uploaded successfully! API Name: {audio_file.name}", flush=True)
# 2. Wait for processing # 2. Wait for processing
start_time = time.time() start_time = time.time()
while audio_file.state.name == "PROCESSING": while audio_file.state.name == "PROCESSING":
print("File is processing on Google servers... waiting 10s") print("File is processing on Google servers... waiting 10s", flush=True)
time.sleep(10) time.sleep(10)
audio_file = genai.get_file(name=audio_file.name) audio_file = genai.get_file(name=audio_file.name)
@ -48,8 +65,8 @@ def transcribe_audio(audio_path, output_prefix, model_name="gemini-1.5-pro"):
send_tg("❌ **Ошибка**: Обработка аудиофайла на сервере Google завершилась неудачей.") send_tg("❌ **Ошибка**: Обработка аудиофайла на сервере Google завершилась неудачей.")
raise ValueError("Audio processing failed on Google servers.") raise ValueError("Audio processing failed on Google servers.")
print("Audio file is active and ready!") print("Audio file is active and ready!", flush=True)
send_tg("⚡️ **Аудиофайл готов к обработке.** Запускаю генерацию текста в Gemini (это может занять до 2-3 минут)...") send_tg("⚡️ **Аудиофайл готов.** Запускаю расшифровку речи в Gemini (это может занять до 2-3 минут)...")
# 3. Transcribe with model # 3. Transcribe with model
model = genai.GenerativeModel(model_name) model = genai.GenerativeModel(model_name)
@ -75,19 +92,20 @@ def transcribe_audio(audio_path, output_prefix, model_name="gemini-1.5-pro"):
f.write(transcript_text) f.write(transcript_text)
elapsed = time.time() - start_time elapsed = time.time() - start_time
print(f"Success! Unpacked in {elapsed:.1f}s") print(f"Success! Unpacked in {elapsed:.1f}s", flush=True)
send_tg(f"✅ **Расшифровка завершена!**\nПродолжительность операции: {elapsed/60:.1f} мин\n\nРезультаты сохранены в:\n- `{md_file}`\n- `{txt_file}`") # Send transcript to Telegram
send_tg(f"✅ **Расшифровка завершена!** ({elapsed/60:.1f} мин)\nРезультаты сохранены в:\n- `{md_file}`\n- `{txt_file}`\n\n📝 **Текст расшифровки:**\n\n{transcript_text}")
except Exception as e: except Exception as e:
print(f"Error during transcription generation: {e}") print(f"Error during transcription generation: {e}", flush=True)
send_tg(f"❌ **Ошибка во время генерации текста:**\n`{e}`") send_tg(f"❌ **Ошибка во время генерации текста:**\n`{e}`")
finally: finally:
# Delete remote file from Google storage # Delete remote file from Google storage
print("Cleaning up file from Google storage...") print("Cleaning up file from Google storage...", flush=True)
genai.delete_file(name=audio_file.name) genai.delete_file(name=audio_file.name)
print("Cleanup done.") print("Cleanup done.", flush=True)
if __name__ == "__main__": if __name__ == "__main__":
if len(sys.argv) < 3: if len(sys.argv) < 3: