Spaces:
Sleeping
Sleeping
Update app.py
Browse files8 unmodified lines910111213141694 unmodified lines17091710171117121713171417151 unmodified line171717181719172017211722172317241725172617271728766 unmodified lines249524962497249824992500250125022503250425052506250725085 unmodified lines2514251525162517251825192520252125222523252425257 unmodified lines25332534253525362537253825392540254125422543254425452546254725482549255025512552711 unmodified lines326432653266326732683269327032713272327332743275327665 unmodified lines33423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723 unmodified lines33763377337833793380338133828 unmodified linesimport jsonimport timeimport refrom supabase import create_client, Client# ── Helper: build query from terms and operators ──────────────1694 unmodified linesif not AUTH_USER or not AUTH_PASS:_admin_active = Falseyield (gr.Column(visible=True), gr.Column(visible=False), "Configuration Error: Secrets missing.", BLANK_TEMPLATE_DF, gr.Column(visible=True), gr.Column(visible=False), gr.HTML(value=generate_editor_html()), False, gr.Column(visible=False), gr.Column(visible=False), get_reviewed_table_df(), get_pubcrawler_terms_df(), gr.TabItem(visible=False))returnif username == AUTH_USER and password == AUTH_PASS:1 unmodified lineif session_hash:_admin_sessions[session_hash] = time.time()yield (gr.Column(visible=False), gr.Column(visible=True), "Authenticated. Loading data...", BLANK_TEMPLATE_DF, gr.Column(visible=False), gr.Column(visible=True), gr.HTML(value=generate_editor_html()), True, gr.Column(visible=True), gr.Column(visible=True), get_reviewed_table_df(), get_pubcrawler_terms_df(), gr.TabItem(visible=True))entire_table_df = load_entire_table()yield (gr.Column(visible=False), gr.Column(visible=True), "Admin Dashboard Ready.", entire_table_df, gr.Column(visible=False), gr.Column(visible=True), gr.HTML(value=generate_editor_html()), True, gr.Column(visible=True), gr.Column(visible=True), get_reviewed_table_df(), get_pubcrawler_terms_df(), gr.TabItem(visible=True))else:_admin_active = Falseyield (gr.Column(visible=True), gr.Column(visible=False), "Invalid credentials. Access denied.", BLANK_TEMPLATE_DF, gr.Column(visible=True), gr.Column(visible=False), gr.HTML(value=generate_view_html()), False, gr.Column(visible=False), gr.Column(visible=False), get_reviewed_table_df(), get_pubcrawler_terms_df(), gr.TabItem(visible=False))def upload_data_to_supabase(file_obj, species, tissue, dataset_type):766 unmodified linesdef save_pubcrawler_term(term, request: gr.Request):"""Insert a crawler term for an authenticated admin."""if not _pubcrawler_admin_ok(request):return '⚠ Admin login required. Please log in first.', get_pubcrawler_terms_df(), ''term = ' '.join(str(term or '').split())if not term:return '⚠ Enter a term before saving.', get_pubcrawler_terms_df(), ''if not supabase:return '⚠ Supabase connection is unavailable.', get_pubcrawler_terms_df(), ''try:# Prevent accidental duplicate terms without requiring a unique DB constraint.5 unmodified lines.execute())if existing.data:return 'ℹ️ That term is already in PubCrawler.', get_pubcrawler_terms_df(), termsupabase.table('pubcrawler').insert({'term': term}).execute()return f'✅ Saved PubCrawler term: **{term}**', get_pubcrawler_terms_df(), ''except Exception as e:return f'⚠ Could not save term: {e}', get_pubcrawler_terms_df(), termdef pubcrawler_row_selection(evt: gr.SelectData, current_df):7 unmodified linesreturn '', f'Selection error: {e}'def delete_pubcrawler_term(selected_id, request: gr.Request):"""Delete a selected PubCrawler term for an authenticated admin."""if not _pubcrawler_admin_ok(request):return '⚠ Admin login required. Please log in first.', get_pubcrawler_terms_df(), ''if not selected_id:return '⚠ Select a term first.', get_pubcrawler_terms_df(), ''if not supabase:return '⚠ Supabase connection is unavailable.', get_pubcrawler_terms_df(), ''try:supabase.table('pubcrawler').delete().eq('id', int(selected_id)).execute()return '🗑️ PubCrawler term removed.', get_pubcrawler_terms_df(), ''except Exception as e:return f'⚠ Could not remove term: {e}', get_pubcrawler_terms_df(), str(selected_id)# ── Layout ────────────────────────────────────────────────────────────────────711 unmodified linesdatatype=['number', 'str'],interactive=False,wrap=True,max_height=360,)selected_pubcrawler_id = gr.State("")with gr.Row():pubcrawler_delete_btn = gr.Button("Remove Selected Term", variant="stop")pubcrawler_selection_status = gr.Markdown("")# ── TAB 6: Administrative Portal ───────────────────────────────────────with gr.TabItem("Administrative Portal"):with gr.Column(visible=True) as login_panel:65 unmodified linesinputs=[user_box, pass_box],outputs=[login_panel, upload_panel, status_output, admin_table_view,home_locked_panel, home_editor_panel, home_editor_component, is_authenticated,pm_doi_col, ls_doi_col, reviewed_table_view, pubcrawler_table, pubcrawler_tab])pass_box.submit(fn=check_upload_credentials_generator,inputs=[user_box, pass_box],outputs=[login_panel, upload_panel, status_output, admin_table_view,home_locked_panel, home_editor_panel, home_editor_component, is_authenticated,pm_doi_col, ls_doi_col, reviewed_table_view, pubcrawler_table, pubcrawler_tab])# ── PubCrawler event wiring ───────────────────────────────────pubcrawler_save_btn.click(fn=save_pubcrawler_term,inputs=[pubcrawler_term_input],outputs=[pubcrawler_status, pubcrawler_table, pubcrawler_term_input])pubcrawler_refresh_btn.click(fn=lambda: get_pubcrawler_terms_df(),inputs=[],outputs=[pubcrawler_table])pubcrawler_term_input.submit(fn=save_pubcrawler_term,inputs=[pubcrawler_term_input],outputs=[pubcrawler_status, pubcrawler_table, pubcrawler_term_input])pubcrawler_table.select(fn=pubcrawler_row_selection,3 unmodified linespubcrawler_delete_btn.click(fn=delete_pubcrawler_term,inputs=[selected_pubcrawler_id],outputs=[pubcrawler_status, pubcrawler_table, selected_pubcrawler_id])save_home_btn.click(8 unmodified lines91011121314151694 unmodified lines17101711171217131714171517161 unmodified line171817191720172117221723172417251726172717281729766 unmodified lines249624972498249925002501250225032504250525062507250825095 unmodified lines2515251625172518251925202521252225232524252525267 unmodified lines25342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691711 unmodified lines34033404340534063407340834093410341134123413341434153416341734183419342034213422342365 unmodified lines34893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193 unmodified lines35233524352535263527352835293530353135323533353435358 unmodified linesimport jsonimport timeimport reimport html as html_libfrom supabase import create_client, Client# ── Helper: build query from terms and operators ──────────────1694 unmodified linesif not AUTH_USER or not AUTH_PASS:_admin_active = Falseyield (gr.Column(visible=True), gr.Column(visible=False), "Configuration Error: Secrets missing.", BLANK_TEMPLATE_DF, gr.Column(visible=True), gr.Column(visible=False), gr.HTML(value=generate_editor_html()), False, gr.Column(visible=False), gr.Column(visible=False), get_reviewed_table_df(), get_pubcrawler_terms_df(), get_pubcrawler_articles_html(request), gr.TabItem(visible=False))returnif username == AUTH_USER and password == AUTH_PASS:1 unmodified lineif session_hash:_admin_sessions[session_hash] = time.time()yield (gr.Column(visible=False), gr.Column(visible=True), "Authenticated. Loading data...", BLANK_TEMPLATE_DF, gr.Column(visible=False), gr.Column(visible=True), gr.HTML(value=generate_editor_html()), True, gr.Column(visible=True), gr.Column(visible=True), get_reviewed_table_df(), get_pubcrawler_terms_df(), get_pubcrawler_articles_html(request), gr.TabItem(visible=True))entire_table_df = load_entire_table()yield (gr.Column(visible=False), gr.Column(visible=True), "Admin Dashboard Ready.", entire_table_df, gr.Column(visible=False), gr.Column(visible=True), gr.HTML(value=generate_editor_html()), True, gr.Column(visible=True), gr.Column(visible=True), get_reviewed_table_df(), get_pubcrawler_terms_df(), get_pubcrawler_articles_html(request), gr.TabItem(visible=True))else:_admin_active = Falseyield (gr.Column(visible=True), gr.Column(visible=False), "Invalid credentials. Access denied.", BLANK_TEMPLATE_DF, gr.Column(visible=True), gr.Column(visible=False), gr.HTML(value=generate_view_html()), False, gr.Column(visible=False), gr.Column(visible=False), get_reviewed_table_df(), get_pubcrawler_terms_df(), get_pubcrawler_articles_html(request), gr.TabItem(visible=False))def upload_data_to_supabase(file_obj, species, tissue, dataset_type):766 unmodified linesdef save_pubcrawler_term(term, request: gr.Request):"""Insert a crawler term for an authenticated admin."""if not _pubcrawler_admin_ok(request):return '⚠ Admin login required. Please log in first.', get_pubcrawler_terms_df(), '', get_pubcrawler_articles_html(request)term = ' '.join(str(term or '').split())if not term:return '⚠ Enter a term before saving.', get_pubcrawler_terms_df(), '', get_pubcrawler_articles_html(request)if not supabase:return '⚠ Supabase connection is unavailable.', get_pubcrawler_terms_df(), '', get_pubcrawler_articles_html(request)try:# Prevent accidental duplicate terms without requiring a unique DB constraint.5 unmodified lines.execute())if existing.data:return 'ℹ️ That term is already in PubCrawler.', get_pubcrawler_terms_df(), term, get_pubcrawler_articles_html(request)supabase.table('pubcrawler').insert({'term': term}).execute()return f'✅ Saved PubCrawler term: **{term}**', get_pubcrawler_terms_df(), '', get_pubcrawler_articles_html(request)except Exception as e:return f'⚠ Could not save term: {e}', get_pubcrawler_terms_df(), term, get_pubcrawler_articles_html(request)def pubcrawler_row_selection(evt: gr.SelectData, current_df):7 unmodified linesreturn '', f'Selection error: {e}'def get_pubcrawler_articles_html(request: gr.Request):"""Search every saved PubCrawler term across the literature sources for the past 30 days."""if not _pubcrawler_admin_ok(request):return "<div style=\"padding:18px;border:1px solid #fecaca;background:#fef2f2;border-radius:8px;color:#b91c1c;font-size:13px;\">⚠ Admin login required. Please log in first.</div>"if not supabase:return "<div style=\"padding:18px;border:1px solid #fecaca;background:#fef2f2;border-radius:8px;color:#b91c1c;font-size:13px;\">⚠ Supabase connection is unavailable.</div>"terms_df = get_pubcrawler_terms_df()terms = []if not terms_df.empty:terms = [str(x).strip() for x in terms_df['Term'].tolist() if str(x).strip()]if not terms:return "<div style=\"padding:28px;border:1px dashed #cbd5e1;background:#ffffff;border-radius:10px;text-align:center;color:#64748b;font-family:system-ui,sans-serif;\">📭 No PubCrawler terms have been saved yet.</div>"since = datetime.date.today() - datetime.timedelta(days=30)since_date = since.strftime('%Y/%m/%d')since_dash = since.strftime('%Y-%m-%d')all_results = []term_logs = []for term in terms:source_map = {'PubMed': lambda t=term: _fetch_pubmed(t, since_date, max_results=200),'Europe PMC': lambda t=term: _fetch_europe_pmc(t, since_dash, max_results=200),'CrossRef': lambda t=term: _fetch_crossref(t, since_dash, max_results=100),'Semantic Scholar': lambda t=term: _fetch_semantic_scholar(t, since_dash, max_results=100),'bioRxiv / medRxiv': lambda t=term: _fetch_biorxiv(t, since_dash, max_results=100),}for source_name, fetch_fn in source_map.items():try:results, log = fetch_fn()for result in results:result = dict(result)result['_crawler_term'] = termall_results.append(result)if results:term_logs.append(f"{term}: {source_name} {len(results)}")except Exception as e:term_logs.append(f"{term}: {source_name} error")if not all_results:return f"""<div style=\"padding:28px;border:1px dashed #cbd5e1;background:#ffffff;border-radius:10px;text-align:center;color:#64748b;font-family:system-ui,sans-serif;\">🔍 No publications matching the saved PubCrawler terms were found in the past 30 days.</div>"""# Deduplicate while retaining all saved terms that matched each article.merged = {}for r in all_results:doi = _extract_doi(r.get('doi', ''))title_key = str(r.get('title', '')).strip().lower()key = ('doi', doi.lower()) if doi else ('title', title_key[:140])if key not in merged:merged[key] = dict(r)merged[key]['_crawler_terms'] = [r.get('_crawler_term', '')]else:hit = r.get('_crawler_term', '')if hit and hit not in merged[key]['_crawler_terms']:merged[key]['_crawler_terms'].append(hit)if not merged[key].get('doi') and doi:merged[key]['doi'] = doiresults = _sort_results(list(merged.values()))reviewed_dois = load_reviewed_dois()source_counts = {}for r in results:src = r.get('source', 'Unknown')source_counts[src] = source_counts.get(src, 0) + 1count_badges = ''.join(f"<span style=\"background:#f1f5f9;color:#475569;padding:3px 9px;border-radius:9999px;font-size:11px;font-weight:600;\">{html_lib.escape(src)}: {cnt}</span>"for src, cnt in source_counts.items())html = f"""<div style=\"font-family:system-ui,sans-serif;\"><div style=\"background:#f8fafc;border:1px solid #e2e8f0;border-radius:10px;padding:14px 18px;margin-bottom:16px;\"><div style=\"display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap;\"><div style=\"font-size:14px;font-weight:700;color:#0f172a;\">📰 {len(results)} unique publications · past 30 days</div><div style=\"display:flex;gap:6px;flex-wrap:wrap;\">{count_badges}</div></div><div style=\"font-size:11px;color:#94a3b8;margin-top:8px;\">Searching {len(terms)} saved PubCrawler term(s); duplicates merged.</div></div>"""for r in results:title = html_lib.escape(str(r.get('title', 'Untitled')))url = html_lib.escape(str(r.get('url', '') or ''))authors = html_lib.escape(str(r.get('authors', 'Unknown Authors')))journal = html_lib.escape(str(r.get('journal', '')))date = html_lib.escape(str(r.get('date', 'N/A')))doi = _extract_doi(r.get('doi', ''))doi_esc = html_lib.escape(doi)src = html_lib.escape(str(r.get('source', 'Unknown')))src_color = r.get('source_color', '#2563eb')src_bg = r.get('source_bg', '#eff6ff')terms_hit = r.get('_crawler_terms', []) or []term_html = ''.join(f"<span style=\"background:#eef2ff;color:#4338ca;padding:2px 7px;border-radius:9999px;font-size:10px;font-weight:600;\">{html_lib.escape(t)}</span>"for t in terms_hit)reviewed_badge = ('<span style=\"background:#dcfce7;color:#15803d;padding:2px 8px;border-radius:9999px;font-size:10px;font-weight:700;\">✅ Read</span>'if doi and doi in reviewed_dois else '')title_html = (f'<a href=\"{url}\" target=\"_blank\" rel=\"noopener noreferrer\" style=\"font-size:14px;font-weight:700;color:#2563eb;text-decoration:none;line-height:1.5;display:block;margin-bottom:8px;\">{title}</a>'if url else f'<div style=\"font-size:14px;font-weight:700;color:#0f172a;line-height:1.5;margin-bottom:8px;\">{title}</div>')html += f"""<div style=\"border:1px solid #e2e8f0;border-radius:10px;padding:14px 16px;margin-bottom:10px;background:#ffffff;\">{title_html}<div style=\"display:flex;flex-wrap:wrap;align-items:center;gap:7px;margin-bottom:7px;\"><span style=\"background:{src_bg};color:{src_color};padding:2px 7px;border-radius:9999px;font-size:10px;font-weight:700;\">{src}</span>{reviewed_badge}{term_html}<span style=\"font-size:11px;color:#64748b;\">📅 {date}</span></div><div style=\"font-size:12px;color:#475569;line-height:1.6;\"><strong>Authors:</strong> {authors}{f' <span style=\"color:#94a3b8;\">•</span> <em>{journal}</em>' if journal else ''}</div>{f'<div style=\"font-size:11px;color:#64748b;margin-top:5px;\">DOI: <a href=\"https://doi.org/{doi_esc}\" target=\"_blank\" rel=\"noopener noreferrer\" style=\"color:#2563eb;text-decoration:none;\">{doi_esc}</a></div>' if doi else ''}</div>"""html += "</div>"return htmldef refresh_pubcrawler_articles(request: gr.Request):"""Refresh the PubCrawler article feed for the authenticated admin."""return get_pubcrawler_articles_html(request)def delete_pubcrawler_term(selected_id, request: gr.Request):"""Delete a selected PubCrawler term for an authenticated admin."""if not _pubcrawler_admin_ok(request):return '⚠ Admin login required. Please log in first.', get_pubcrawler_terms_df(), '', get_pubcrawler_articles_html(request)if not selected_id:return '⚠ Select a term first.', get_pubcrawler_terms_df(), '', get_pubcrawler_articles_html(request)if not supabase:return '⚠ Supabase connection is unavailable.', get_pubcrawler_terms_df(), '', get_pubcrawler_articles_html(request)try:supabase.table('pubcrawler').delete().eq('id', int(selected_id)).execute()return '🗑️ PubCrawler term removed.', get_pubcrawler_terms_df(), '', get_pubcrawler_articles_html(request)except Exception as e:return f'⚠ Could not remove term: {e}', get_pubcrawler_terms_df(), str(selected_id), get_pubcrawler_articles_html(request)# ── Layout ────────────────────────────────────────────────────────────────────711 unmodified linesdatatype=['number', 'str'],interactive=False,wrap=True,max_height=300,)selected_pubcrawler_id = gr.State("")with gr.Row():pubcrawler_delete_btn = gr.Button("Remove Selected Term", variant="stop")pubcrawler_selection_status = gr.Markdown("")gr.Markdown("### Articles Matching Saved Terms — Past 30 Days")with gr.Row():pubcrawler_articles_refresh_btn = gr.Button("Refresh Articles", variant="secondary", scale=1)pubcrawler_articles_status = gr.Markdown("", scale=3)pubcrawler_articles_html = gr.HTML(value="<div style='padding:28px;border:1px dashed #cbd5e1;background:#ffffff;border-radius:10px;text-align:center;color:#64748b;'>Click Refresh Articles to search the past 30 days for every saved PubCrawler term.</div>")# ── TAB 6: Administrative Portal ───────────────────────────────────────with gr.TabItem("Administrative Portal"):with gr.Column(visible=True) as login_panel:65 unmodified linesinputs=[user_box, pass_box],outputs=[login_panel, upload_panel, status_output, admin_table_view,home_locked_panel, home_editor_panel, home_editor_component, is_authenticated,pm_doi_col, ls_doi_col, reviewed_table_view, pubcrawler_table, pubcrawler_articles_html, pubcrawler_tab])pass_box.submit(fn=check_upload_credentials_generator,inputs=[user_box, pass_box],outputs=[login_panel, upload_panel, status_output, admin_table_view,home_locked_panel, home_editor_panel, home_editor_component, is_authenticated,pm_doi_col, ls_doi_col, reviewed_table_view, pubcrawler_table, pubcrawler_articles_html, pubcrawler_tab])# ── PubCrawler event wiring ───────────────────────────────────pubcrawler_save_btn.click(fn=save_pubcrawler_term,inputs=[pubcrawler_term_input],outputs=[pubcrawler_status, pubcrawler_table, pubcrawler_term_input, pubcrawler_articles_html])pubcrawler_refresh_btn.click(fn=lambda request: (get_pubcrawler_terms_df(), get_pubcrawler_articles_html(request)),inputs=[],outputs=[pubcrawler_table, pubcrawler_articles_html])pubcrawler_term_input.submit(fn=save_pubcrawler_term,inputs=[pubcrawler_term_input],outputs=[pubcrawler_status, pubcrawler_table, pubcrawler_term_input, pubcrawler_articles_html])pubcrawler_table.select(fn=pubcrawler_row_selection,3 unmodified linespubcrawler_delete_btn.click(fn=delete_pubcrawler_term,inputs=[selected_pubcrawler_id],outputs=[pubcrawler_status, pubcrawler_table, selected_pubcrawler_id, pubcrawler_articles_html])pubcrawler_articles_refresh_btn.click(fn=refresh_pubcrawler_articles,inputs=[],outputs=[pubcrawler_articles_html])save_home_btn.click(
app.py+176-23