Update app.py
Browse files12342 unmodified lines7891011121314151617181920212223242526272829303118 unmodified lines5051525354555688 unmodified lines14514614714814915043 unmodified lines1941951961971981992002012022032042053 unmodified lines2092102112122132142152162172182192202212222232242252262 unmodified lines2292302312322332342352362372382392402412422432443 unmodified lines2482492502512522532542552562572582592602613 unmodified lines26526626726826927027127227327427527627727827928028128228328428528612 unmodified lines2993003013023033043053062 unmodified lines3093103113123133143156 unmodified lines3223233243253263273283293303313323333343351 unmodified line337338339340341342343344345346347348349350351352353354355356357358359360# HF Spaces / Gradio app: Vochi CRM call logs + Gemini analysis# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# How to deploy (short):# 1) Create a new Space (Python + Gradio).2 unmodified lines# 4) In the Space β Settings β Repository secrets, add:# - VOCHI_BASE_URL (e.g. https://crm.vochi.by/api)# - VOCHI_CLIENT_ID (client id string)# - GOOGLE_API_KEY (Gemini API key)# 5) Tokens/keys are NEVER accepted via UI; the app reads ONLY from Space Secrets.## requirements.txt (copy these lines into a separate file):# -----------------------------------------------------------------------------# gradio>=4.40.0# requests>=2.31.0# pandas>=2.2.2# numpy>=1.26.4# soundfile>=0.12.1# google-genai>=0.6.0# -----------------------------------------------------------------------------## Notes:# - Audio playback & download are handled inside the app; the MP3 is saved under /tmp.# - Gemini accepts MP3 uploads directly, so WAV conversion is not strictly required.# - If your Vochi instance needs auth, set an Authorization header below.## UI language: Belarusian.from __future__ import annotationsimport os18 unmodified lines# Config# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββBASE_URL = os.environ.get("VOCHI_BASE_URL", "https://crm.vochi.by/api")CLIENT_ID = os.environ.get("VOCHI_CLIENT_ID", "elq3tE3JhZWuKi8HsGI6PkipkYiUbjJN")# If your API needs auth, fill it here (or via VOCHI_BEARER in Secrets)_AUTH_TOKEN = os.environ.get("VOCHI_BEARER", "").strip()88 unmodified lines# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# Utilities# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββdef label_row(row: dict) -> str:start = row.get("Start", "")src = row.get("CallerId", "")43 unmodified lines# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# Gradio handlers# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββdef ui_fetch_calls(date_str: str):try:items = fetch_calllogs(date_str.strip())df = pd.DataFrame(items)opts = [(label_row(r), i) for i, r in df.iterrows()]msg = f"ΠΠ½ΠΎΠΉΠ΄Π·Π΅Π½Π° Π·Π²Π°Π½ΠΊΠΎΡ: {len(df)}"# Update dropdown choices and default valuedd = gr.update(choices=[(lbl, idx) for lbl, idx in opts], value=(opts[0][1] if opts else None))return df, dd, msg3 unmodified linesbody = e.response.text[:800]except Exception:passreturn pd.DataFrame(), gr.update(choices=[], value=None), f"HTTP ΠΏΠ°ΠΌΡΠ»ΠΊΠ°: {e}\n{body}"except Exception as e:return pd.DataFrame(), gr.update(choices=[], value=None), f"ΠΠ°ΠΌΡΠ»ΠΊΠ° Π·Π°Π³ΡΡΠ·ΠΊΡ: {e}"def ui_play_audio(selected_idx: Optional[int], df: pd.DataFrame):if selected_idx is None or df is None or df.empty:return "<em>Π‘ΠΏΠ°ΡΠ°ΡΠΊΡ Π°ΡΡΡΠΌΠ°ΡΡ ΡΠΏΡΡ Ρ Π²ΡΠ±ΡΠ°ΡΡ ΡΠ°Π΄ΠΎΠΊ.</em>", None, None, ""try:row = df.iloc[int(selected_idx)]except Exception:return "<em>ΠΠ΅ΠΊΠ°ΡΡΠΊΡΠ½Ρ Π²ΡΠ±Π°Ρ ΡΠ°Π΄ΠΊΠ°.</em>", None, None, ""unique_id = str(row.get("UniqueId"))try:fpath = f"/tmp/call_{unique_id}.mp3"2 unmodified linesif not os.path.exists(fpath) or os.path.getsize(fpath) == 0:fpath, url_used = fetch_mp3_by_unique_id(unique_id)html = f'URL: <a href="{url_used}" target="_blank">{url_used}</a>'return html, fpath, fpath, "ΠΠ°ΡΠΎΠ²Π° β "except requests.HTTPError as e:body = ""try:body = e.response.text[:800]except Exception:passreturn f"HTTP ΠΏΠ°ΠΌΡΠ»ΠΊΠ°: {e}<br><pre>{body}</pre>", None, None, ""except Exception as e:return f"ΠΠ΅ Π°ΡΡΡΠΌΠ°Π»Π°ΡΡ ΠΏΡΠ°ΠΉΠ³ΡΠ°ΡΡ: {e}", None, None, ""def ui_toggle_custom_prompt(template_key: str):3 unmodified linesdef ui_analyze(selected_idx: Optional[int], df: pd.DataFrame,template_key: str, custom_prompt: str, lang_code: str, model_pref: str):if df is None or df.empty or selected_idx is None:return "Π‘ΠΏΠ°ΡΠ°ΡΠΊΡ Π°ΡΡΡΠΌΠ°ΡΡ ΡΠΏΡΡ, Π²ΡΠ±ΡΠ°ΡΡ Π·Π²Π°Π½ΠΎΠΊ Ρ (ΠΏΡΡ ΠΏΠ°ΡΡΡΠ±Π΅) Π½Π°ΡΡΡΠ½ΡΡΡ βπ§ ΠΡΠ°ΠΉΠ³ΡΠ°ΡΡβ."if not _HAS_GENAI:return "β ΠΡΠ±Π»ΡΡΡΡΠΊΠ° google-genai Π½Π΅ Π·Π½ΠΎΠΉΠ΄Π·Π΅Π½Π°. Π£ΠΏΡΡΠ½ΡΡΠ΅ΡΡ, ΡΡΠΎ ΡΠ½Π° Ρ requirements.txt."try:row = df.iloc[int(selected_idx)]except Exception:return "ΠΠ΅ΠΊΠ°ΡΡΠΊΡΠ½Ρ Π²ΡΠ±Π°Ρ ΡΠ°Π΄ΠΊΠ°."unique_id = str(row.get("UniqueId"))mp3_path = f"/tmp/call_{unique_id}.mp3"3 unmodified linesif 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:return f"ΠΠ΅ Π°ΡΡΡΠΌΠ°Π»Π°ΡΡ Π°ΡΡΡΠΌΠ°ΡΡ Π°ΡΠ΄ΡΡ Π΄Π»Ρ Π°Π½Π°Π»ΡΠ·Ρ: {e}"api_key = os.environ.get("GOOGLE_API_KEY", "").strip()if not api_key:return "GOOGLE_API_KEY Π½Π΅ Π·Π°Π΄Π°Π΄Π·Π΅Π½Ρ Ρ Secrets Space. ΠΠ°Π΄Π°ΠΉ ΡΠ³ΠΎ Ρ Settings β Secrets Ρ ΠΏΠ΅ΡΠ°Π·Π°ΠΏΡΡΡΡ Space."try:client = genai.Client(api_key=api_key)except Exception as e:return f"ΠΠ΅ Π°ΡΡΡΠΌΠ°Π»Π°ΡΡ ΡΠ½ΡΡΡΡΠ»ΡΠ·Π°Π²Π°ΡΡ ΠΊΠ»ΡΠ΅Π½Ρ Gemini: {e}"# Upload filetry:uploaded_file = client.files.upload(file=mp3_path)except Exception as e:return f"ΠΠ°ΠΌΡΠ»ΠΊΠ° Π·Π°Π³ΡΡΠ·ΠΊΡ ΡΠ°ΠΉΠ»Π° Ρ Gemini: {e}"# Prepare promptif template_key == "custom":12 unmodified linesresp = client.models.generate_content(model=model_name, contents=[uploaded_file, merged])text = getattr(resp, "text", None)if not text:return "ΠΠ½Π°Π»ΡΠ· Π·Π°Π²Π΅ΡΡΠ°Π½Ρ Π±Π΅Π· ΡΡΠΊΡΡΠ°Π²Π°Π³Π° Π°Π΄ΠΊΠ°Π·Ρ. ΠΡΠ°Π²Π΅ΡΡΠ΅ Π½Π°Π»Π°Π΄Ρ ΠΌΠ°Π΄ΡΠ»Ρ Ρ ΡΠ°ΡΠΌΠ°Ρ ΡΠ°ΠΉΠ»Π°."return f"### ΠΡΠ½ΡΠΊ Π°Π½Π°Π»ΡΠ·Ρ\n\n{text}"except Exception as e:# Try to attach more error detailsmsg = str(e)2 unmodified linesmsg = msg + "\n\n" + str(e.args[0])except Exception:passreturn f"ΠΠ°ΠΌΡΠ»ΠΊΠ° ΠΏΠ°Π΄ΡΠ°Ρ Π²ΡΠΊΠ»ΡΠΊΡ ΠΌΠ°Π΄ΡΠ»Ρ: {msg}"finally:# Best-effort cleanup of remote filetry:6 unmodified lines# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# Build Gradio UI# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββdef _today_str():return _dt.date.today().strftime("%Y-%m-%d")with gr.Blocks(title="Vochi CRM + Gemini (Gradio)") as demo:gr.Markdown("""# Vochi CRM β MP3 β Gemini Π°Π½οΏ½οΏ½Π»ΡΠ·*ΠΡΡΡΠΌΠ°ΡΡ Π·Π²Π°Π½ΠΊΡ Π·Π° Π΄Π·Π΅Π½Ρ, ΠΏΡΠ°ΠΉΠ³ΡΠ°ΡΡ/ΡΠΊΠ°ΡΠ°ΡΡ MP3 Ρ ΠΏΡΠ°Π°Π½Π°Π»ΡΠ·Π°Π²Π°ΡΡ Π·Π²Π°Π½ΠΎΠΊ ΠΌΠ°Π΄ΡΠ»Π»Ρ GoogleΒ Gemini.*""")1 unmodified linewith gr.Tabs():with gr.Tab("Vochi CRM"):with gr.Row():date_inp = gr.Textbox(label="ΠΠ°ΡΠ°", value=_today_str(), scale=1)fetch_btn = gr.Button("ΠΡΡΡΠΌΠ°ΡΡ ΡΠΏΡΡ", variant="primary", scale=0)calls_df = gr.Dataframe(value=pd.DataFrame(), label="Π‘ΠΏΡΡ Π·Π²Π°Π½ΠΊΠΎΡ", interactive=False)row_dd = gr.Dropdown(choices=[], label="ΠΠ²Π°Π½ΠΎΠΊ", info="ΠΠ±ΡΡΡΡΠ΅ ΡΠ°Π΄ΠΎΠΊ Π΄Π»Ρ ΠΏΡΠ°ΠΉΠ³ΡΠ°Π²Π°Π½Π½Ρ/Π°Π½Π°Π»ΡΠ·Ρ")with gr.Row():play_btn = gr.Button("π§ ΠΡΠ°ΠΉΠ³ΡΠ°ΡΡ")url_html = gr.HTML()audio_out = gr.Audio(label="ΠΡΠ΄ΡΡ", type="filepath")file_out = gr.File(label="MP3 Π΄Π»Ρ ΡΡΡΠ³Π²Π°Π½Π½Ρ")status_fetch = gr.Markdown()with gr.Tab("AI Analysis (Gemini)"):with gr.Row():tpl_dd = gr.Dropdown(choices=TPL_OPTIONS, value="simple", label="Π¨Π°Π±Π»ΠΎΠ½")lang_dd = gr.Dropdown(choices=LANG_OPTIONS, value="default", label="ΠΠΎΠ²Π°")model_dd = gr.Dropdown(choices=MODEL_OPTIONS, value="models/gemini-2.5-flash", label="ΠΠ°Π΄ΡΠ»Ρ")custom_prompt_tb = gr.Textbox(label="Custom prompt", lines=8, visible=False)analyze_btn = gr.Button("π§ ΠΠ½Π°Π»ΡΠ·", variant="primary")analysis_md = gr.Markdown()# Wire events12342 unmodified lines789101112131415161718 unmodified lines3637383940414288 unmodified lines13113213313413513613743 unmodified lines1811821831841851861871881891901911921933 unmodified lines1971981992002012022032042052062072082092102112122132142 unmodified lines2172182192202212222232242252262272282292302312323 unmodified lines2362372382392402412422432442452462472482493 unmodified lines25325425525625725825926026126226326426526626726826927027127227327412 unmodified lines2872882892902912922932942 unmodified lines2972982993003013023036 unmodified lines3103113123133143153163173183193203213223233241 unmodified line326327328329330331332333334335336337338339340341342343344345346347348349# HF Spaces / Gradio app: Vochi CRM call logs + AI analysis# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# How to deploy (short):# 1) Create a new Space (Python + Gradio).2 unmodified lines# 4) In the Space β Settings β Repository secrets, add:# - VOCHI_BASE_URL (e.g. https://crm.vochi.by/api)# - VOCHI_CLIENT_ID (client id string)# - GOOGLE_API_KEY (API key)## UI language: English.from __future__ import annotationsimport os18 unmodified lines# Config# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββBASE_URL = os.environ.get("VOCHI_BASE_URL", "https://crm.vochi.by/api")CLIENT_ID = os.environ.get("VOCHI_CLIENT_ID")# If your API needs auth, fill it here (or via VOCHI_BEARER in Secrets)_AUTH_TOKEN = os.environ.get("VOCHI_BEARER", "").strip()88 unmodified lines# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# Utilities# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββdef label_row(row: dict) -> str:start = row.get("Start", "")src = row.get("CallerId", "")43 unmodified lines# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# Gradio handlers# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββdef ui_fetch_calls(date_str: str):try:items = fetch_calllogs(date_str.strip())df = pd.DataFrame(items)opts = [(label_row(r), i) for i, r in df.iterrows()]msg = f"Calls found: {len(df)}"# Update dropdown choices and default valuedd = gr.update(choices=[(lbl, idx) for lbl, idx in opts], value=(opts[0][1] if opts else None))return df, dd, msg3 unmodified linesbody = e.response.text[:800]except Exception:passreturn pd.DataFrame(), gr.update(choices=[], value=None), f"HTTP error: {e}\n{body}"except Exception as e:return pd.DataFrame(), gr.update(choices=[], value=None), f"Load error: {e}"def ui_play_audio(selected_idx: Optional[int], df: pd.DataFrame):if selected_idx is None or df is None or df.empty:return "<em>First fetch the list and select a row.</em>", None, None, ""try:row = df.iloc[int(selected_idx)]except Exception:return "<em>Invalid row selection.</em>", None, None, ""unique_id = str(row.get("UniqueId"))try:fpath = f"/tmp/call_{unique_id}.mp3"2 unmodified linesif not os.path.exists(fpath) or os.path.getsize(fpath) == 0:fpath, url_used = fetch_mp3_by_unique_id(unique_id)html = f'URL: <a href="{url_used}" target="_blank">{url_used}</a>'return html, fpath, fpath, "Ready β "except requests.HTTPError as e:body = ""try:body = e.response.text[:800]except Exception:passreturn f"HTTP error: {e}<br><pre>{body}</pre>", None, None, ""except Exception as e:return f"Playback failed: {e}", None, None, ""def ui_toggle_custom_prompt(template_key: str):3 unmodified linesdef ui_analyze(selected_idx: Optional[int], df: pd.DataFrame,template_key: str, custom_prompt: str, lang_code: str, model_pref: str):if df is None or df.empty or selected_idx is None:return "First fetch the list, choose a call, and (optionally) click βπ§ Playβ."if not _HAS_GENAI:return "β google-genai library not found. Make sure it's in requirements.txt."try:row = df.iloc[int(selected_idx)]except Exception:return "Invalid row selection."unique_id = str(row.get("UniqueId"))mp3_path = f"/tmp/call_{unique_id}.mp3"3 unmodified linesif 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:return f"Failed to obtain audio for analysis: {e}"api_key = os.environ.get("GOOGLE_API_KEY", "").strip()if not api_key:return "GOOGLE_API_KEY is not set in Space Secrets. Add it in Settings β Secrets and restart the Space."try:client = genai.Client(api_key=api_key)except Exception as e:return f"Failed to initialize the client: {e}"# Upload filetry:uploaded_file = client.files.upload(file=mp3_path)except Exception as e:return f"File upload error: {e}"# Prepare promptif template_key == "custom":12 unmodified linesresp = client.models.generate_content(model=model_name, contents=[uploaded_file, merged])text = getattr(resp, "text", None)if not text:return "Analysis finished but returned no text. Check model settings and file format."return f"### Analysis result\n\n{text}"except Exception as e:# Try to attach more error detailsmsg = str(e)2 unmodified linesmsg = msg + "\n\n" + str(e.args[0])except Exception:passreturn f"Error during model call: {msg}"finally:# Best-effort cleanup of remote filetry:6 unmodified lines# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# Build Gradio UI# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββdef _today_str():return _dt.date.today().strftime("%Y-%m-%d")with gr.Blocks(title="Vochi CRM Call Logs (Gradio)") as demo:gr.Markdown("""# Vochi CRM β MP3 β AI analysis*Fetch daily calls, play/download MP3, and analyze the call with an AI model.*""")1 unmodified linewith gr.Tabs():with gr.Tab("Vochi CRM"):with gr.Row():date_inp = gr.Textbox(label="Date", value=_today_str(), scale=1)fetch_btn = gr.Button("Fetch list", variant="primary", scale=0)calls_df = gr.Dataframe(value=pd.DataFrame(), label="Call list", interactive=False)row_dd = gr.Dropdown(choices=[], label="Call", info="Select a row for playback/analysis")with gr.Row():play_btn = gr.Button("π§ Play")url_html = gr.HTML()audio_out = gr.Audio(label="Audio", type="filepath")file_out = gr.File(label="MP3 download")status_fetch = gr.Markdown()with gr.Tab("AI Analysis"):with gr.Row():tpl_dd = gr.Dropdown(choices=TPL_OPTIONS, value="simple", label="Template")lang_dd = gr.Dropdown(choices=LANG_OPTIONS, value="default", label="Language")model_dd = gr.Dropdown(choices=MODEL_OPTIONS, value="models/gemini-2.5-flash", label="Model")custom_prompt_tb = gr.Textbox(label="Custom prompt", lines=8, visible=False)analyze_btn = gr.Button("π§ Analyze", variant="primary")analysis_md = gr.Markdown()# Wire events
app.py+42-53