Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files187 unmodified lines18818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722819 unmodified lines248249250216251218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259252253254261262263255256257258259268269270271272273274275276277278279280281282260284285286287288289290291292293294295296297298299300301302303304305261262263264285 unmodified lines55055155259755355459960060160260360460555555655755855956060856156261061161261356356456556656756856957057157257361861957457557657757857962462558062758158258358458558682 unmodified lines669670671716672673674675676187 unmodified lines """ import zipfile
def _read_single(path: str, max_chars: int) -> str: f_ext = os.path.splitext(path)[1].lower() if f_ext in {".xlsx", ".xls"}: sheets = pd.read_excel(path, sheet_name=None) if not sheets: return "Empty Excel workbook." text = "\n\n".join( f"=== Sheet: {s_name} ===\n{df.to_csv(index=False)}" for s_name, df in sheets.items() ) elif f_ext == ".pdf": try: from pypdf import PdfReader
reader = PdfReader(path) pages = [ f"=== Page {i + 1} ===\n{(p.extract_text() or '').strip()}" for i, p in enumerate(reader.pages) ] text = "\n\n".join(p for p in pages if p.strip()) or "Empty PDF text." except Exception as pdf_exc: return f"Error reading PDF '{path}': {str(pdf_exc)}" elif f_ext in {".png", ".jpg", ".jpeg", ".webp", ".gif"}: return f"Binary image file '{path}'. Use inspect_image(image_path='{path}', question=...)." elif f_ext in {".mp3", ".wav", ".m4a", ".ogg", ".flac"}: return f"Binary audio file '{path}'. Use transcribe_audio(audio_path='{path}', question=...)." else: with open(path, "r", encoding="utf-8", errors="replace") as f: text = f.read()
if len(text) <= max_chars: return text half = max_chars // 2 return text[:half] + "\n...\n" + text[-half:]
try: if not os.path.isfile(file_path): return f"File not found: '{file_path}'"19 unmodified lines os.makedirs(os.path.dirname(target_path), exist_ok=True) with zf.open(member, "r") as src, open(target_path, "wb") as dst: dst.write(src.read()) m_ext = os.path.splitext(member)[1].lower() try: if m_ext in {".xlsx", ".xls"}: sheets = pd.read_excel(target_path, sheet_name=None) sheet_parts = [ f"-- Sheet {s_name} --\n{df.to_csv(index=False)}" for s_name, df in sheets.items() ] sections.append( f"=== {member} (extracted to {target_path}) ===\n" + "\n".join(sheet_parts) ) elif m_ext == ".pdf": try: from pypdf import PdfReader
reader = PdfReader(target_path) p_texts = [ f"-- Page {i + 1} --\n{(p.extract_text() or '').strip()}" for i, p in enumerate(reader.pages) ] sections.append( f"=== {member} (extracted to {target_path}) ===\n" + "\n".join(p_texts) ) except Exception as p_exc: sections.append( f"=== {member} (extracted to {target_path}) ===\nPDF error: {p_exc}" ) elif m_ext in {".png", ".jpg", ".jpeg", ".webp", ".gif"}: sections.append( f"=== {member} (extracted to {target_path}) ===\n" f"Binary image file. Use inspect_image(image_path='{target_path}', question=...)." ) elif m_ext in {".mp3", ".wav", ".m4a", ".ogg", ".flac"}: sections.append( f"=== {member} (extracted to {target_path}) ===\n" f"Binary audio file. Use transcribe_audio(audio_path='{target_path}', question=...)." ) else: with open(target_path, "r", encoding="utf-8", errors="replace") as mf: sections.append( f"=== {member} (extracted to {target_path}) ===\n" + mf.read() ) content_str = _read_single(target_path, max_chars=24000) sections.append(f"=== {member} (extracted to {target_path}) ===\n{content_str}") except Exception as m_exc: sections.append( f"=== {member} (extracted to {target_path}) ===\nRead error: {m_exc}" ) sections.append(f"=== {member} (extracted to {target_path}) ===\nRead error: {m_exc}") joined_zip = "\n\n".join(sections) if len(joined_zip) <= 48000: return joined_zip return joined_zip[:24000] + "\n...\n" + joined_zip[-24000:] if ext in {".xlsx", ".xls"}: sheets = pd.read_excel(file_path, sheet_name=None) if not sheets: return "Empty Excel workbook." parts = [ f"=== Sheet: {sheet_name} ===\n{df.to_csv(index=False)}" for sheet_name, df in sheets.items() ] joined_xls = "\n\n".join(parts) if len(joined_xls) <= 48000: return joined_xls return joined_xls[:24000] + "\n...\n" + joined_xls[-24000:] if ext == ".pdf": try: from pypdf import PdfReader
reader = PdfReader(file_path) pages_text = [ f"=== Page {i + 1} ===\n{(page.extract_text() or '').strip()}" for i, page in enumerate(reader.pages) ] joined = "\n\n".join(p for p in pages_text if p.strip()) if not joined: return "Empty PDF text." if len(joined) <= 48000: return joined return joined[:24000] + "\n...\n" + joined[-24000:] except Exception as pdf_exc: return f"Error reading PDF '{file_path}': {str(pdf_exc)}" if ext in {".png", ".jpg", ".jpeg", ".webp", ".gif"}: return f"Binary image file '{file_path}'. Use inspect_image(image_path='{file_path}', question=...)." if ext in {".mp3", ".wav", ".m4a", ".ogg", ".flac"}: return f"Binary audio file '{file_path}'. Use transcribe_audio(audio_path='{file_path}', question=...)." with open(file_path, "r", encoding="utf-8", errors="replace") as f: content = f.read() if len(content) <= 48000: return content return content[:24000] + "\n...\n" + content[-24000:] return _read_single(file_path, max_chars=48000) except Exception as e: return f"Error reading file '{file_path}': {str(e)}"
285 unmodified lines
candidate_models = []
if self.provider_keys.get("openrouter"): if self.provider_keys.get("groq"): candidate_models.extend([ "openrouter/meta-llama/llama-3.3-70b-instruct:free", "openrouter/moonshotai/kimi-k2:free", "openrouter/qwen/qwen-2.5-72b-instruct:free", "openrouter/google/gemma-3-27b-it:free", "openrouter/meta-llama/llama-3.3-70b-instruct", "openrouter/moonshotai/kimi-k2", "openrouter/qwen/qwen-2.5-72b-instruct", "groq/openai/gpt-oss-120b", "groq/qwen/qwen3.8-27b", "groq/openai/gpt-oss-20b", "groq/llama-3.1-8b-instant", ])
if self.provider_keys.get("groq"): if self.provider_keys.get("openrouter"): candidate_models.extend([ "groq/llama-3.3-70b-versatile", "groq/moonshotai/kimi-k2-instruct", "groq/qwen-qwq-32b", "groq/llama-3.1-8b-instant", "openrouter/google/gemma-4-31b-it:free", "openrouter/google/gemma-4-26b-a4b-it:free", "openrouter/nvidia/nemotron-3-ultra-550b-a55b:free", "openrouter/nvidia/nemotron-3.5-super-vl:free", "openrouter/qwen/qwen3-next-80b-a3b-instruct:free", "openrouter/meta-llama/llama-3.3-70b-instruct:free", "openrouter/free", ])
if self.provider_keys.get("huggingface"): candidate_models.extend([ "huggingface/meta-llama/Llama-3.3-70B-Instruct", "huggingface/Qwen/Qwen2.5-72B-Instruct", "huggingface/Qwen/Qwen3.8-27B", "huggingface/meta-llama/Llama-3.1-8B-Instruct", ])
if self.provider_keys.get("gemini"): gemini_preferred = [ "gemini/gemini-flash-lite-latest", "gemini/gemini-3.1-flash-lite", "gemini/gemini-3.5-flash-lite", "gemini/gemini-flash-latest", "gemini/gemini-3.8-flash", "gemini/gemini-3.5-flash", "gemini/gemini-3.1-flash-lite", ] available_api_models = set() try:82 unmodified lines def _prepare_call_kwargs(self, kwargs: dict) -> dict: key = getattr(self, "_explicit_api_key", None) or kwargs.get("api_key") model_name = str(getattr(self, "model_id", "") or "") kwargs.pop("api_key", None) if key: kwargs["api_key"] = key if model_name.startswith("openrouter/"): os.environ["OPENROUTER_API_KEY"] = key elif model_name.startswith("groq/"):app.py+58-102