Spaces:
Running
Running
Jin Zhu commited on
Commit ·
0fa0487
1
Parent(s): 3ef9054
update
Browse filesFiles changed (4)
- .gitignore+3-1
- src/FineTune/.gitignore-1
- src/app.py+182-84
- src/feedback.py+55-53
1cache/*123cache/*src/feedback_data/*src/__pycache__/*
7 unmodified lines8910111213147 unmodified lines# Distribution / packaging.Pythonckpt/*logs/*/models/*/build/7 unmodified lines89101112137 unmodified lines# Distribution / packaging.Pythonlogs/*/models/*/build/
32 unmodified lines33343536373878 unmodified lines1171181191201211221231241252 unmodified lines12812913013113213313413562 unmodified lines19819920020120220320426 unmodified lines23123223323423523623723823928 unmodified lines2682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503514 unmodified lines35635735835936036132 unmodified linesimport streamlit as stfrom FineTune.model import ComputeStatimport time# -----------------# Page Configuration78 unmodified linesfeedback_manager = FeedbackManager(dataset_repo_id=FEEDBACK_DATASET_ID,hf_token=os.environ.get('HF_TOKEN'),local_backup=True # 保留本地备份)# -----------------# Configuration# -----------------2 unmodified lines'from_pretrained': './src/FineTune/ckpt/','base_model': 'gemma-1b','cache_dir': '../cache',# 'device': 'mps','device': 'cpu',# 'device': 'cuda',}62 unmodified linesheight=200,)detect_clicked = st.button("Detect", type="primary", use_container_width=True)selected_domain = st.selectbox(label="⚙️ Domain (Optional)",26 unmodified linesif not text_input.strip():st.warning("⚠️ Please enter some text before detecting.")else:# ========== Reset feedback state ==========st.session_state.feedback_given = False# ==========================================# Start timing to decide whether to show progress barstart_time = time.time()28 unmodified lines'elapsed_time': elapsed_time}# Update score displayswith col2:statistics_ph.text_input(label="Statistics",value=f"{crit:.6f}",disabled=True,help="Detection statistics will appear here after clicking Detect.",)pvalue_ph.text_input(label="p-value",value=f"{p_value:.6f}",disabled=True,help="p-value will appear here after clicking Detect.",)st.info("""**📊 p-value:**- **Lower p-value** (closer to 0) indicates text is **more likely AI-generated**- **Higher p-value** (closer to 1) indicates text is **more likely human-written**- Generally, p-value < 0.05 suggests the text may be LLM-generated""",icon="💡")# ========== 🆕 Feedback buttons (moved here for better UX) ==========st.markdown("**📝 Result Feedback**: Does this detection result meet your expectations?")current_text = text_inputcurrent_domain = selected_domaincurrent_statistics = critcurrent_pvalue = p_valuefeedback_col1, feedback_col2 = st.columns(2)with feedback_col1:if st.button("✅ Expected", use_container_width=True, type="secondary", key=f"expected_btn_{hash(text_input[:50])}"):try:success, message = feedback_manager.save_feedback(current_text,current_domain,current_statistics,current_pvalue,'expected')if success:st.success("✅ Thank you for your feedback!")st.caption(f"💾 {message}")else:st.error(f"Failed to save feedback: {message}")except Exception as e:st.error(f"Failed to save feedback: {str(e)}")import tracebackst.code(traceback.format_exc())with feedback_col2:if st.button("❌ Unexpected", use_container_width=True, type="secondary", key=f"unexpected_btn_{hash(text_input[:50])}"):try:success, message = feedback_manager.save_feedback(current_text,current_domain,current_statistics,current_pvalue,'unexpected')if success:st.warning("❌ Feedback recorded! This will help us improve.")st.caption(f"💾 {message}")else:st.error(f"Failed to save feedback: {message}")except Exception as e:st.error(f"Failed to save feedback: {str(e)}")import tracebackst.code(traceback.format_exc())if st.session_state.feedback_given:st.success("✅ Feedback submitted successfully!")# ============================================# Show detailed resultswith result_placeholder:4 unmodified linesst.error(f"❌ Error during detection: {str(e)}")st.exception(e)# ========== 🆕 Citation and paper reference section ==========# st.markdown("---")# st.markdown(32 unmodified lines33343536373839404178 unmodified lines1201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062 unmodified lines20921021121221321421562 unmodified lines27827928028128228328428526 unmodified lines31231331431531631731828 unmodified lines3473483493503513523533544 unmodified lines35936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845932 unmodified linesimport streamlit as stfrom FineTune.model import ComputeStatimport time# 🆕 new importsimport jsonimport datetime# -----------------# Page Configuration78 unmodified linesfeedback_manager = FeedbackManager(dataset_repo_id=FEEDBACK_DATASET_ID,hf_token=os.environ.get('HF_TOKEN'),local_backup=False if os.environ.get('SPACE_ID') else True # 保留本地备份)# 🆕 Incremental feedback saver for HF SpacesIS_SPACE = bool(os.environ.get('SPACE_ID'))@st.cache_resourcedef get_feedback_repo(dataset_repo_id: str, hf_token: str):if not IS_SPACE:return Nonetry:from huggingface_hub import login, Repositoryif hf_token:login(token=hf_token)local_dir = Path('/tmp') / ('hf_ds_' + dataset_repo_id.replace('/', '__'))local_dir.mkdir(parents=True, exist_ok=True)repo = Repository(local_dir=str(local_dir),clone_from=dataset_repo_id,repo_type="dataset",token=hf_token,)return repoexcept Exception as e:print(f"[feedback repo] init failed: {e}")return Nonedef save_feedback_incremental(text: str, domain: str, statistics: float, p_value: float, label: str):"""Append a single feedback record to a date-sharded NDJSON file and push.Falls back to FeedbackManager on error or non-space environments."""try:repo = get_feedback_repo(FEEDBACK_DATASET_ID, os.environ.get('HF_TOKEN'))if repo is None:# Fallback (local or repo init failed)return feedback_manager.save_feedback(text, domain, statistics, p_value, label)# Pull latest, append, commit, pushtry:repo.git_pull(rebase=True)except Exception as e:print(f"[feedback repo] pull warning: {e}")now = datetime.datetime.utcnow()date_str = now.strftime("%Y-%m-%d")payload = {"timestamp": now.isoformat(timespec="seconds") + "Z","space_id": os.environ.get('SPACE_ID'),"domain": domain,"label": label,"statistics": statistics,"p_value": p_value,"text": text,"app_version": "adadetectgpt-app-1", # optional tag}feedback_dir = Path(repo.local_dir) / "feedback"feedback_dir.mkdir(parents=True, exist_ok=True)file_path = feedback_dir / f"{date_str}.ndjson"with open(file_path, "a", encoding="utf-8") as f:f.write(json.dumps(payload, ensure_ascii=False) + "\n")# Commit and push only the changed file to minimize trafficrepo.git_add(pattern=str(file_path))try:repo.git_commit(f"feedback: append {file_path.name}")except Exception as e:# allow empty commit errors to pass silently if nothing changedprint(f"[feedback repo] commit info: {e}")repo.git_push()return True, f"Pushed to {FEEDBACK_DATASET_ID}:{file_path.name}"except Exception as e:# Final fallback if anything goes wrongprint(f"[feedback repo] incremental save failed: {e}")try:return feedback_manager.save_feedback(text, domain, statistics, p_value, label)except Exception as e2:return False, f"Fallback failed: {e2}"# -----------------# Configuration# -----------------2 unmodified lines'from_pretrained': './src/FineTune/ckpt/','base_model': 'gemma-1b','cache_dir': '../cache','device': 'cpu' if os.environ.get('SPACE_ID') else 'mps',# 'device': 'cuda',}62 unmodified linesheight=200,)# Add a stable key to the Detect buttondetect_clicked = st.button("Detect", type="primary", use_container_width=True, key="detect_btn")selected_domain = st.selectbox(label="⚙️ Domain (Optional)",26 unmodified linesif not text_input.strip():st.warning("⚠️ Please enter some text before detecting.")else:st.session_state.feedback_given = False# Start timing to decide whether to show progress barstart_time = time.time()28 unmodified lines'elapsed_time': elapsed_time}# NOTE: Do not render results and feedback here; they are rendered below# based on st.session_state.last_detection so buttons persist across reruns.# Show detailed resultswith result_placeholder:4 unmodified linesst.error(f"❌ Error during detection: {str(e)}")st.exception(e)# ================= Result & Feedback rendering (persistent across reruns) =================if st.session_state.last_detection:data = st.session_state.last_detectionwith col2:# Update score displaysstatistics_ph.text_input(label="Statistics",value=f"{data['statistics']:.6f}",disabled=True,help="Detection statistics will appear here after clicking Detect.",)pvalue_ph.text_input(label="p-value",value=f"{data['p_value']:.6f}",disabled=True,help="p-value will appear here after clicking Detect.",)st.info("""**📊 p-value:**- **Lower p-value** (closer to 0) indicates text is **more likely AI-generated**- **Higher p-value** (closer to 1) indicates text is **more likely human-written**- Generally, p-value < 0.05 suggests the text may be LLM-generated""",icon="💡")st.markdown("**📝 Result Feedback**: Does this detection result meet your expectations?")current_text = data['text']current_domain = data['domain']current_statistics = data['statistics']current_pvalue = data['p_value']feedback_col1, feedback_col2 = st.columns(2)with feedback_col1:# Add a stable, unique key so click state is captured on rerunexpected_click = st.button("✅ Expected",use_container_width=True,type="secondary",key=f"expected_btn_{hash(current_text[:50])}")print("--------------------------------------------------")print(f"Expected button clicked: {expected_click}")if expected_click and not st.session_state.feedback_given:try:# 🆕 use incremental saver (auto-fallbacks when needed)success, message = save_feedback_incremental(current_text,current_domain,current_statistics,current_pvalue,'expected')if success:st.success("✅ Thanks for your positive feedback!")st.session_state.feedback_given = Trueelse:st.error(f"Failed to save feedback: {message}")except Exception as e:st.error(f"Failed to save feedback: {str(e)}")import tracebackst.code(traceback.format_exc())with feedback_col2:unexpected_click = st.button("❌ Unexpected",use_container_width=True,type="secondary",key=f"unexpected_btn_{hash(current_text[:50])}")if unexpected_click and not st.session_state.feedback_given:try:# 🆕 use incremental saver (auto-fallbacks when needed)success, message = save_feedback_incremental(current_text,current_domain,current_statistics,current_pvalue,'unexpected')if success:st.warning("Feedback recorded! This will help us improve.")st.session_state.feedback_given = Trueelse:st.error(f"Failed to save feedback: {message}")except Exception as e:st.error(f"Failed to save feedback: {str(e)}")import tracebackst.code(traceback.format_exc())# ========== 🆕 Citation and paper reference section ==========# st.markdown("---")# st.markdown(
5 unmodified lines6789101119 unmodified lines313233343536376 unmodified lines44454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001015 unmodified linesfrom typing import Optionalimport pandas as pdclass FeedbackManager:"""管理用户反馈,支持保存到 Hugging Face 私有数据集"""19 unmodified linesif self.dataset_repo_id and self.hf_token:self.api = HfApi(token=self.hf_token)# 确保数据集存在self._ensure_dataset_exists()else:self.api = Noneprint("⚠️ No HF dataset configured. Will only save locally.")6 unmodified linesself.local_dir.mkdir(exist_ok=True, parents=True)self.local_file = self.local_dir / 'user_feedback.json'def _ensure_dataset_exists(self):"""确保 HF 数据集存在,如果不存在则创建"""try:from huggingface_hub import create_repo# 尝试创建数据集仓库(如果已存在会抛出异常)try:create_repo(repo_id=self.dataset_repo_id,token=self.hf_token,private=True,repo_type="dataset")print(f"✅ Created new private dataset: {self.dataset_repo_id}")# 创建初始的 README.mdreadme_content = f"""---license: mit---# AdaDetectGPT User Feedback DatasetThis dataset contains user feedback from the AdaDetectGPT detection system.## Data FormatEach entry contains:- `timestamp`: When the feedback was submitted- `text`: The text that was analyzed- `domain`: The domain selected for analysis- `statistics`: The computed statistics value- `p_value`: The p-value from the detection- `feedback`: User feedback (expected/unexpected)"""readme_file = self.local_dir / 'README.md'readme_file.write_text(readme_content)upload_file(path_or_fileobj=str(readme_file),path_in_repo="README.md",repo_id=self.dataset_repo_id,repo_type="dataset",token=self.hf_token)except Exception as e:if "already exists" not in str(e):print(f"⚠️ Dataset check: {e}")except Exception as e:print(f"⚠️ Could not verify dataset: {e}")def _load_existing_data(self) -> list:"""从 HF 数据集加载现有数据"""existing_data = []5 unmodified lines6789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646519 unmodified lines8586878889906 unmodified lines9798991001011021035 unmodified linesfrom typing import Optionalimport pandas as pddef save_feedback_incremental(text: str, domain: str, statistics: float, p_value: float, label: str):"""Append a single feedback record to a date-sharded NDJSON file and push.Falls back to FeedbackManager on error or non-space environments."""try:repo = get_feedback_repo(FEEDBACK_DATASET_ID, os.environ.get('HF_TOKEN'))if repo is None:# Fallback (local or repo init failed)return feedback_manager.save_feedback(text, domain, statistics, p_value, label)# Pull latest, append, commit, pushtry:repo.git_pull(rebase=True)except Exception as e:print(f"[feedback repo] pull warning: {e}")now = datetime.datetime.utcnow()date_str = now.strftime("%Y-%m-%d")payload = {"timestamp": now.isoformat(timespec="seconds") + "Z","space_id": os.environ.get('SPACE_ID'),"domain": domain,"label": label,"statistics": statistics,"p_value": p_value,"text": text,"app_version": "adadetectgpt-app-1", # optional tag}feedback_dir = Path(repo.local_dir) / "feedback"feedback_dir.mkdir(parents=True, exist_ok=True)file_path = feedback_dir / f"{date_str}.ndjson"with open(file_path, "a", encoding="utf-8") as f:f.write(json.dumps(payload, ensure_ascii=False) + "\n")# Commit and push only the changed file to minimize trafficrepo.git_add(pattern=str(file_path))try:repo.git_commit(f"feedback: append {file_path.name}")except Exception as e:# allow empty commit errors to pass silently if nothing changedprint(f"[feedback repo] commit info: {e}")repo.git_push()return True, f"Pushed to {FEEDBACK_DATASET_ID}:{file_path.name}"except Exception as e:# Final fallback if anything goes wrongprint(f"[feedback repo] incremental save failed: {e}")try:return feedback_manager.save_feedback(text, domain, statistics, p_value, label)except Exception as e2:return False, f"Fallback failed: {e2}"class FeedbackManager:"""管理用户反馈,支持保存到 Hugging Face 私有数据集"""19 unmodified linesif self.dataset_repo_id and self.hf_token:self.api = HfApi(token=self.hf_token)# 确保数据集存在else:self.api = Noneprint("⚠️ No HF dataset configured. Will only save locally.")6 unmodified linesself.local_dir.mkdir(exist_ok=True, parents=True)self.local_file = self.local_dir / 'user_feedback.json'def _load_existing_data(self) -> list:"""从 HF 数据集加载现有数据"""existing_data = []
.gitignore+3-1
src/FineTune/.gitignore-1
src/app.py+182-84
src/feedback.py+55-53