Update app.py
Browse files17 unmodified lines18192021222324156 unmodified lines181182183184185186187188189190191123 unmodified lines31531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444576 unmodified lines52252352452552652752852953053153253353453553653753853954054154254354418 unmodified lines56356456556656756856957057157257357457557617 unmodified linesimport jsonimport datetime as _dtfrom typing import List, Tuple, Optionalimport time # ← ДАДАНА
import requestsimport pandas as pd156 unmodified lines return "Reply in English." return "Reply in the caller's language; if unclear, use concise professional English."
# ← ДАДАНА: невялікі хелпер для выбару прамптуdef _prepare_prompt(template_key: str, custom_prompt: str) -> str: if template_key == "custom": return (custom_prompt or "").strip() or PROMPT_TEMPLATES["simple"] return PROMPT_TEMPLATES.get(template_key, PROMPT_TEMPLATES["simple"])
# ─────────────────────────────────────────────────────────────────────────────# Gradio handlers123 unmodified lines except Exception: pass
# ← ДАДАНА: Пакетны аналіз званкоў за дзень/часdef ui_analyze_calls_by_date( authed: bool, date_str: str, template_key: str, custom_prompt: str, lang_code: str, model_pref: str,): """ Fetch calls for the given date and analyze them one-by-one with the same settings/fields as the single-call AI Analysis tab. Save a .txt file and show results on screen. """ # Гейт па паролі if not authed: return ( "🔒 Увядзіце пароль, каб запусціць аналіз.", # results_md None, # file "Доступ закрыты.", # status gr.update(visible=True), # show pwd group )
date_str = (date_str or "").strip() if not date_str: date_str = _today_str()
# 1) Атрымаць спіс званкоў за дату try: calls = fetch_calllogs(date_str) df = pd.DataFrame(calls) except Exception as e: return (f"Не ўдалося загрузіць спіс: {e}", None, "", gr.update())
if df.empty: return ("За гэты дзень званкоў не знойдзена.", None, "", gr.update())
# 2) Падрыхтоўка кліента мадэлі і прампту if not _HAS_GENAI: return ("❌ google-genai library not found.", None, "", gr.update())
api_key = os.environ.get("GOOGLE_API_KEY", "").strip() if not api_key: return ("GOOGLE_API_KEY не зададзены ў Secrets.", None, "", gr.update())
try: client = genai.Client(api_key=api_key) model_name = _resolve_model(client, model_pref) except Exception as e: return (f"Не ўдалося ініцыялізаваць кліента: {e}", None, "", gr.update())
sys_inst = _system_instruction(lang_code) prompt = _prepare_prompt(template_key, custom_prompt)
# 3) Пакетны праход: па адным выкліку results_blocks: List[str] = [] analyzed = 0
for i, row in df.iterrows(): unique_id = str(row.get("UniqueId", "")) if not unique_id: continue
# Скачваем/кэшынгуем mp3 try: mp3_path = f"/tmp/call_{unique_id}.mp3" if not os.path.exists(mp3_path) or os.path.getsize(mp3_path) == 0: mp3_path, _ = fetch_mp3_by_unique_id(unique_id) except Exception as e: results_blocks.append( f"### Call {i+1}\n" f"- UniqueId: {unique_id}\n" f"- Start: {row.get('Start','')}\n" f"- CallerId: {row.get('CallerId','')}\n" f"- Destination: {row.get('Destination','')}\n" f"- Duration: {row.get('Duration','')}\n\n" f"**Памылка загрузкі аўдыё:** {e}\n" "---" ) continue
# Upload + generate try: uploaded_file = client.files.upload(file=mp3_path) merged = f"[SYSTEM INSTRUCTION: {sys_inst}]\n\n{prompt}" resp = client.models.generate_content( model=model_name, contents=[uploaded_file, merged], ) text = getattr(resp, "text", "") or "(пусты адказ)" except Exception as e: text = f"Памылка аналізу: {e}" finally: try: if 'uploaded_file' in locals() and hasattr(uploaded_file, 'name'): client.files.delete(name=uploaded_file.name) except Exception: pass
# Сфармаваць блок выніку для гэтага званка block = ( f"### Call {i+1}\n" f"- UniqueId: {unique_id}\n" f"- Start: {row.get('Start','')}\n" f"- CallerId: {row.get('CallerId','')}\n" f"- Destination: {row.get('Destination','')}\n" f"- Duration: {row.get('Duration','')}\n\n" f"**Analysis:**\n\n{text}\n" "---" ) results_blocks.append(block) analyzed += 1
if analyzed == 0: return ("Не атрымалася прааналізаваць ніводнага званка.", None, "", gr.update())
# 4) Захаваць у .txt і вярнуць results_text = "\n\n".join(results_blocks) fname = f"/tmp/batch_analysis_{date_str}_{int(time.time())}.txt" with open(fname, "w", encoding="utf-8") as f: f.write(results_text)
status = f"Гатова ✅. Прааналізавана званкоў: {analyzed}." return (results_text, fname, status, gr.update(visible=False))
# ─────────────────────────────────────────────────────────────────────────────# Password / gating helpers# ─────────────────────────────────────────────────────────────────────────────76 unmodified lines analyze_btn = gr.Button("🧠 Analyze", variant="primary") analysis_md = gr.Markdown()
# ← ДАДАНА: новая ўкладка пакетнага аналізу with gr.Tab("Аналіз званкоў за дзень/час"): batch_date_inp = gr.Textbox(label="Date", value=_today_str(), scale=1)
with gr.Row(): tpl_batch_dd = gr.Dropdown(choices=TPL_OPTIONS, value="simple", label="Template") lang_batch_dd = gr.Dropdown(choices=LANG_OPTIONS, value="default", label="Language") model_batch_dd = gr.Dropdown(choices=MODEL_OPTIONS, value="models/gemini-2.5-flash", label="Model")
custom_batch_tb = gr.Textbox(label="Custom prompt", lines=8, visible=False)
batch_btn = gr.Button("прааналізаваць", variant="primary")
batch_status_md = gr.Markdown() batch_results_md = gr.Markdown() batch_file_out = gr.File(label="Вынікі (.txt)")
# Wire events # 1) Fetch button: gate by password fetch_btn.click(18 unmodified lines outputs=[analysis_md], )
# ← ДАДАНА: падзеі для новай укладкі tpl_batch_dd.change(ui_toggle_custom_prompt, inputs=[tpl_batch_dd], outputs=[custom_batch_tb]) batch_btn.click( ui_analyze_calls_by_date, inputs=[authed, batch_date_inp, tpl_batch_dd, custom_batch_tb, lang_batch_dd, model_batch_dd], outputs=[batch_results_md, batch_file_out, batch_status_md, pwd_group], )
if __name__ == "__main__": # On HF Spaces, just running this file is enough; launch() is fine for local dev, too.app.py+156