Spaces:
Runtime error
Runtime error
Commit ·
e3a165a
1
Parent(s): 419bca9
Upd dynamic local/cloud mode rotator from ENV
Browse filesFiles changed (4)
- requirements-dev.txt+1
- utils/cloud_llm.py+26-1
- utils/drive_saver.py+47-12
- utils/token.py+53-3
21 unmodified lines22232425262721 unmodified linesscikit-learn>=1.3.0sentencepiecesacremoses# Vietnamese translation (Opus model fallback)# Note: google-genai and google-auth packages are excluded for local mode21 unmodified lines2223242526272821 unmodified linesscikit-learn>=1.3.0sentencepiecesacremosesprotobuf# Vietnamese translation (Opus model fallback)# Note: google-genai and google-auth packages are excluded for local mode
2 unmodified lines345678939 unmodified lines49505152535455562 unmodified linesimport loggingimport requestsfrom typing import Optionalfrom google import genailogger = logging.getLogger("llm")if not logger.handlers:39 unmodified linesdef __init__(self, rotator: KeyRotator, default_model: str):self.rotator = rotatorself.default_model = default_modeldef generate(self, prompt: str, model: Optional[str] = None, temperature: float = 0.2, max_output_tokens: int = 512) -> Optional[str]:key = self.rotator.next_key()if not key:return None2 unmodified lines3456789101112131415161718192021222324252627282939 unmodified lines697071727374757677787980812 unmodified linesimport loggingimport requestsfrom typing import Optional# Dynamic import for Google GenAI (only when not in local mode)def _import_google_genai():"""Dynamically import Google GenAI only when needed"""try:from google import genaireturn genaiexcept ImportError as e:raise ImportError(f"Google GenAI not available: {e}. Make sure IS_LOCAL=false and google-genai is installed.")# Check if we're in local modeIS_LOCAL = os.getenv("IS_LOCAL", "false").lower() == "true"# Only import Google GenAI if not in local modeif not IS_LOCAL:try:genai = _import_google_genai()except ImportError:genai = Noneelse:genai = Nonelogger = logging.getLogger("llm")if not logger.handlers:39 unmodified linesdef __init__(self, rotator: KeyRotator, default_model: str):self.rotator = rotatorself.default_model = default_modelself.available = genai is not None and not IS_LOCALdef generate(self, prompt: str, model: Optional[str] = None, temperature: float = 0.2, max_output_tokens: int = 512) -> Optional[str]:if not self.available:logger.warning("[LLM][Gemini] Google GenAI not available (local mode or import failed)")return Nonekey = self.rotator.next_key()if not key:return None
1 unmodified line2345678910111213141516171819202122232425262728293014 unmodified lines4546474849504 unmodified lines55565758596029 unmodified lines90919293949520 unmodified lines1161171181191201211221 unmodified lineimport os, json, loggingfrom typing import Optional# Conditional imports for Google Drive (only when needed)try:from google.oauth2 import service_accountfrom googleapiclient.discovery import buildfrom googleapiclient.http import MediaFileUploadGOOGLE_DRIVE_AVAILABLE = Trueexcept ImportError:GOOGLE_DRIVE_AVAILABLE = False# Create dummy classes for when Google Drive is not availableclass service_account:class Credentials:@staticmethoddef from_service_account_info(*args, **kwargs):raise ImportError("Google Drive dependencies not available")class build:@staticmethoddef build(*args, **kwargs):raise ImportError("Google Drive dependencies not available")class MediaFileUpload:def __init__(self, *args, **kwargs):raise ImportError("Google Drive dependencies not available")from utils.token import get_credentials14 unmodified linesself.supports_all_drives = os.getenv("GDRIVE_FOLDER_IS_SHARED", "false").lower() in ("1","true","yes")self.allow_sa_fallback = os.getenv("GDRIVE_ALLOW_SA_FALLBACK", "false").lower() in ("1","true","yes")# Check if Google Drive is availableif not GOOGLE_DRIVE_AVAILABLE:logger.warning("⚠️ Google Drive dependencies not available - DriveSaver will be disabled")4 unmodified linesself._initialize_service()def _initialize_service(self):if not GOOGLE_DRIVE_AVAILABLE:logger.warning("⚠️ Google Drive dependencies not available - skipping service initialization")return29 unmodified lineslogger.info("✅ Google Drive service initialized")def upload_file_to_drive(self, file_path: str, folder_id: Optional[str] = None, mimetype: Optional[str] = None) -> bool:if not GOOGLE_DRIVE_AVAILABLE:logger.warning("⚠️ Google Drive dependencies not available - upload skipped")return False20 unmodified linesreturn Falsedef is_service_available(self) -> bool:return GOOGLE_DRIVE_AVAILABLE and self.service is not Nonedef set_folder_id(self, folder_id: str):self.folder_id = folder_id1 unmodified line234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515214 unmodified lines67686970717273747576774 unmodified lines8283848586878889909129 unmodified lines12112212312412512612712812913020 unmodified lines1511521531541551561571 unmodified lineimport os, json, loggingfrom typing import Optional# Check if we're in local modeIS_LOCAL = os.getenv("IS_LOCAL", "false").lower() == "true"# Conditional imports for Google Drive (only when not in local mode)if not IS_LOCAL:try:from google.oauth2 import service_accountfrom googleapiclient.discovery import buildfrom googleapiclient.http import MediaFileUploadGOOGLE_DRIVE_AVAILABLE = Trueexcept ImportError:GOOGLE_DRIVE_AVAILABLE = False# Create dummy classes for when Google Drive is not availableclass service_account:class Credentials:@staticmethoddef from_service_account_info(*args, **kwargs):raise ImportError("Google Drive dependencies not available")class build:@staticmethoddef build(*args, **kwargs):raise ImportError("Google Drive dependencies not available")class MediaFileUpload:def __init__(self, *args, **kwargs):raise ImportError("Google Drive dependencies not available")else:# Local mode: Google Drive is not availableGOOGLE_DRIVE_AVAILABLE = False# Create dummy classes for local modeclass service_account:class Credentials:@staticmethoddef from_service_account_info(*args, **kwargs):raise ImportError("Google Drive not available in local mode")class build:@staticmethoddef build(*args, **kwargs):raise ImportError("Google Drive not available in local mode")class MediaFileUpload:def __init__(self, *args, **kwargs):raise ImportError("Google Drive not available in local mode")from utils.token import get_credentials14 unmodified linesself.supports_all_drives = os.getenv("GDRIVE_FOLDER_IS_SHARED", "false").lower() in ("1","true","yes")self.allow_sa_fallback = os.getenv("GDRIVE_ALLOW_SA_FALLBACK", "false").lower() in ("1","true","yes")# Check if we're in local modeif IS_LOCAL:logger.info("🏠 Local mode: Google Drive integration disabled")return# Check if Google Drive is availableif not GOOGLE_DRIVE_AVAILABLE:logger.warning("⚠️ Google Drive dependencies not available - DriveSaver will be disabled")4 unmodified linesself._initialize_service()def _initialize_service(self):if IS_LOCAL:logger.info("🏠 Local mode: Skipping Google Drive service initialization")returnif not GOOGLE_DRIVE_AVAILABLE:logger.warning("⚠️ Google Drive dependencies not available - skipping service initialization")return29 unmodified lineslogger.info("✅ Google Drive service initialized")def upload_file_to_drive(self, file_path: str, folder_id: Optional[str] = None, mimetype: Optional[str] = None) -> bool:if IS_LOCAL:logger.info("🏠 Local mode: File upload to Google Drive skipped")return Falseif not GOOGLE_DRIVE_AVAILABLE:logger.warning("⚠️ Google Drive dependencies not available - upload skipped")return False20 unmodified linesreturn Falsedef is_service_available(self) -> bool:return not IS_LOCAL and GOOGLE_DRIVE_AVAILABLE and self.service is not Nonedef set_folder_id(self, folder_id: str):self.folder_id = folder_id
12345678921 unmodified lines31323334353631 unmodified lines6869707172736 unmodified lines808182838485# GCS credential token refresherimport os, json, loggingfrom typing import Optionalfrom google.oauth2.credentials import Credentialsfrom google_auth_oauthlib.flow import Flowfrom google.auth.transport.requests import Requestlogger = logging.getLogger("token")if not logger.handlers:21 unmodified linesos.makedirs(base, exist_ok=True)def get_credentials() -> Optional[Credentials]:# 1) Token fileif os.path.exists(TOKEN_FILE):try:31 unmodified linesreturn Nonedef build_auth_url(redirect_uri: str) -> str:web = _load_oauth_client_web()if not web:raise RuntimeError("GDRIVE_CREDENTIALS_JSON missing or invalid ('web' section required)")6 unmodified linesreturn auth_urldef exchange_code(code: str, redirect_uri: str) -> Credentials:web = _load_oauth_client_web()if not web:raise RuntimeError("GDRIVE_CREDENTIALS_JSON missing or invalid ('web' section required)")1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484921 unmodified lines7172737475767778798031 unmodified lines1121131141151161171181191206 unmodified lines127128129130131132133134135# GCS credential token refresherimport os, json, loggingfrom typing import Optional# Dynamic imports for Google OAuth (only when not in local mode)def _import_google_oauth():"""Dynamically import Google OAuth libraries only when needed"""try:from google.oauth2.credentials import Credentialsfrom google_auth_oauthlib.flow import Flowfrom google.auth.transport.requests import Requestreturn Credentials, Flow, Requestexcept ImportError as e:raise ImportError(f"Google OAuth libraries not available: {e}. Make sure IS_LOCAL=false and google-auth packages are installed.")# Check if we're in local modeIS_LOCAL = os.getenv("IS_LOCAL", "false").lower() == "true"# Only import Google OAuth libraries if not in local modeif not IS_LOCAL:try:Credentials, Flow, Request = _import_google_oauth()except ImportError:# Create dummy classes for when Google OAuth is not availableclass Credentials:@staticmethoddef from_authorized_user_info(*args, **kwargs):raise ImportError("Google OAuth not available")class Flow:@staticmethoddef from_client_config(*args, **kwargs):raise ImportError("Google OAuth not available")class Request:passelse:# Create dummy classes for local modeclass Credentials:@staticmethoddef from_authorized_user_info(*args, **kwargs):raise ImportError("Google OAuth not available in local mode")class Flow:@staticmethoddef from_client_config(*args, **kwargs):raise ImportError("Google OAuth not available in local mode")class Request:passlogger = logging.getLogger("token")if not logger.handlers:21 unmodified linesos.makedirs(base, exist_ok=True)def get_credentials() -> Optional[Credentials]:if IS_LOCAL:logger.info("🏠 Local mode: Google OAuth credentials not needed")return None# 1) Token fileif os.path.exists(TOKEN_FILE):try:31 unmodified linesreturn Nonedef build_auth_url(redirect_uri: str) -> str:if IS_LOCAL:raise RuntimeError("Google OAuth not available in local mode")web = _load_oauth_client_web()if not web:raise RuntimeError("GDRIVE_CREDENTIALS_JSON missing or invalid ('web' section required)")6 unmodified linesreturn auth_urldef exchange_code(code: str, redirect_uri: str) -> Credentials:if IS_LOCAL:raise RuntimeError("Google OAuth not available in local mode")web = _load_oauth_client_web()if not web:raise RuntimeError("GDRIVE_CREDENTIALS_JSON missing or invalid ('web' section required)")
requirements-dev.txt+1
utils/cloud_llm.py+26-1
utils/drive_saver.py+47-12
utils/token.py+53-3