Spaces:
Sleeping
Sleeping
Update app.py
Browse files4 unmodified lines567891011121314151617181920212223244 unmodified lines293031323334351 unmodified line3738394041424313 unmodified lines5758596061626364656626 unmodified lines939495969798991001011021031041059 unmodified lines1151161171181191201216 unmodified lines12812913013113213313413513613749 unmodified lines1871881891901911921931941951961971988 unmodified lines2072082092102112122135 unmodified lines2192202212222232242252262272282292302312322332342352362375 unmodified lines2432442452462472481 unmodified line2502512522532542552562572582592602612622632642652662672682692702714 unmodified lines27627727827928028128228328428528613 unmodified lines3003013023033043053064 unmodified lines3113123133143153163173183193203213223233243253263273 unmodified lines3313323333343353363373 unmodified lines3413423433443453463474 unmodified lines35235335435535635735835936036136236336449 unmodified lines4144154164174184194202 unmodified lines4234244254264274284294304314321 unmodified line4344354364374384394406 unmodified lines4474484494504514524534546 unmodified lines4614624634644654664674684694704714 unmodified lines4764774784794804814828 unmodified lines4914924934944954964977 unmodified lines5055065075085095105115 unmodified lines5175185195205215225235 unmodified lines5295305315325335345355365375385395405415425435445455465474 unmodified linesimport torchimport osimport timefrom typing import List, Dict, Generator, Tuple, Optionalimport loggingfrom collections import defaultdict# Set up logginglogging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')logger = logging.getLogger(__name__)# --- Best Free Models for Council ---MODELS = [("mistralai/Mistral-7B-Instruct-v0.2", "Mistral 7B Instruct"), # Good default choice("HuggingFaceH4/zephyr-7b-beta", "Zephyr 7B Beta"), # Smaller alternative("NousResearch/Hermes-2-Pro-Mistral-7B", "Hermes 2 Pro"), # Good for debate("cognitivecomputations/dolphin-2.6-mistral-7b", "Dolphin Mistral"), # Uncensored]# Define council member personas4 unmodified lines"traits": "analytical, skeptical, evidence-focused","style": "formal, precise, methodical","emoji": "🔬","preferred_models": ["Mistral 7B Instruct", "Zephyr 7B Beta"] # More factual models},{"name": "Professor Marcus Chen",1 unmodified line"traits": "philosophical, visionary, empathetic","style": "eloquent, metaphorical, conceptual","emoji": "🧠","preferred_models": ["Hermes 2 Pro", "Dolphin Mistral"] # More creative models},{"name": "Sarah Johnson",13 unmodified lines}]# Cache for models to avoid reloadingmodel_cache = {}model_loading_lock = threading.Lock()active_sessions = defaultdict(dict)stop_signal = threading.Event()def get_device_preference():26 unmodified lines"torch_dtype": torch.float16 if device == "cuda" else torch.float32}# More efficient loading for low-memory systemsif device == "cpu":model_kwargs["low_cpu_mem_usage"] = Truemodel = AutoModelForCausalLM.from_pretrained(model_id, **model_kwargs)if device != "cuda": # For CPU/MPS, manually move to devicemodel = model.to(device)pipe = pipeline(9 unmodified linesexcept Exception as e:logger.error(f"Failed to load model {model_id}: {str(e)}")# Try with smaller precision if failedif "out of memory" in str(e).lower() and device == "cuda":logger.info("Attempting to load with float16 to save memory")try:6 unmodified lineslogger.error(f"Still failed to load model: {str(e2)}")raisedef create_debate_prompt(user_prompt: str,persona: Dict,debate_style: str = "Balanced",previous_responses: Optional[List[str]] = None) -> str:"""Enhanced prompt engineering for better debates"""persona_desc = (f"Roleplay as {persona['name']}, {persona['description']}\n"49 unmodified linesFacilitator:"""def stream_model_response(pipe: pipeline,tokenizer: AutoTokenizer,prompt: str,speaker_name: str = None,temperature: float = 0.7,max_tokens: int = 512) -> Generator[str, None, None]:"""Robust streaming with better formatting and stop handling"""try:if stop_signal.is_set():8 unmodified linesstreamer=streamer,max_new_tokens=max_tokens,do_sample=True,temperature=min(max(temperature, 0.1), 1.0), # Clamped to reasonable rangetop_p=0.95,repetition_penalty=1.1,eos_token_id=tokenizer.eos_token_id,5 unmodified linesbuffer = ""for new_text in streamer:if stop_signal.is_set():pipe.model.config.use_cache = False # Try to stop generationthread.join(timeout=1)breakbuffer += new_text# Only yield when we have a complete word to avoid mid-word breaksif " " in new_text or "\n" in new_text:if speaker_name:yield f"**{speaker_name}:** {buffer.strip()}"else:yield buffer.strip()# Yield any remaining contentif buffer.strip():if speaker_name:yield f"**{speaker_name}:** {buffer.strip()}"5 unmodified linesexcept Exception as e:logger.error(f"Error in streaming: {str(e)}")yield "[Error in generation]" if not speaker_name else f"**{speaker_name}:** [Error in generation]"def select_models_for_personas(personas: List[Dict], models: List[Tuple[str, str]]) -> List[Tuple[str, str]]:"""Match models to personas based on preferences"""1 unmodified linemodel_names = [m[1] for m in models]for persona in personas:# Try to match preferred models firstfor pref in persona.get("preferred_models", []):if pref in model_names:selected.append(models[model_names.index(pref)])breakelse:# Fallback to random selectionselected.append(random.choice(models))return selecteddef council_chat_stream(user_prompt: str,num_members: int = 3,debate_style: str = "Balanced",temperature: float = 0.7,session_id: str = None) -> Generator[str, None, None]:"""Enhanced debate generation with better state management"""stop_signal.clear()4 unmodified linesstart_time = time.time()try:# Select personas and modelsselected_personas = random.sample(PERSONAS, min(num_members, len(PERSONAS)))selected_models = select_models_for_personas(selected_personas, MODELS)# Load all models first with progress updatesloaded_models = []for i, (model_id, model_name) in enumerate(selected_models):if stop_signal.is_set():13 unmodified linesyield "❌ Error: No models could be loaded. Please try again later."return# Conduct the debateresponses = []formatted_responses = []persona_responses = []4 unmodified linesreturndisplay_name = f"{persona['emoji']} {persona['name']} ({model_name})"prompt = create_debate_prompt( user_prompt, persona, debate_style, persona_responses)# Stream and collect responseresponse_text = ""for partial in stream_model_response(pipe,tokenizer,prompt,display_name,temperature):if stop_signal.is_set():breakyield partial3 unmodified linesyield "[Debate stopped during responses]"return# Store response dataresponse_data = {"name": persona['name'],"model": model_name,3 unmodified linespersona_responses.append(response_data)formatted_responses.append(partial)# Facilitator synthesisif not stop_signal.is_set():yield "\n\n**✨ Council is now synthesizing the discussion...**\n"synthesis_model = random.choice(loaded_models)4 unmodified linessynthesis_model[1],synthesis_prompt,"✨ Facilitator's Synthesis",temperature*0.8 # Slightly lower temp for synthesis):if stop_signal.is_set():breakyield partial# Final outputelapsed_time = time.time() - start_timeif not stop_signal.is_set():transcript = (49 unmodified lines"""with gr.Blocks(theme=gr.themes.Soft(), css=custom_css) as demo:# Header sectionwith gr.Row():gr.Markdown("""<div class="council-header">2 unmodified lines</div>""")# Main controlswith gr.Row():with gr.Column(scale=2):# Input sectioninp = gr.Textbox(label="Debate Topic",placeholder="Enter a topic or question for the council to debate...",1 unmodified linemax_lines=6)# Debate controlswith gr.Group(elem_classes="debate-controls"):with gr.Row():btn = gr.Button("Start Debate", variant="primary")6 unmodified linesminimum=2,maximum=4,step=1,value=3,info="Number of AI participants")debate_style = gr.Dropdown(label="Debate Style",6 unmodified linesminimum=0.1,maximum=1.0,step=0.1,value=0.7,info="Higher = more creative/random")# Persona informationwith gr.Accordion("Meet the Council Members", open=False):for persona in PERSONAS:with gr.Group(elem_classes="persona-card"):4 unmodified lines**Preferred Models:** {', '.join(persona.get('preferred_models', ['Any']))}""")# Output sectionwith gr.Column(scale=3):out = gr.Markdown(label="Live Debate Transcript",8 unmodified lines- Debate memory and context tracking""")# Example promptswith gr.Accordion("Example Debate Topics", open=False):examples = gr.Examples(examples=[7 unmodified lineslabel="Click to try these examples")# Event handlersbtn.click(fn=council_chat_stream,inputs=[inp, num_members, debate_style, temperature],5 unmodified linesqueue=False)# Footergr.Markdown("""---**About This System:**5 unmodified linesreturn demo# Main applicationif __name__ == "__main__":# Check system resourcesdevice = get_device_preference()logger.info(f"Running on device: {device}")if device == "cpu":logger.warning("Running on CPU - performance will be significantly slower than GPU")# Launch interfacedemo = build_gradio_interface()demo.queue(concurrency_count=1).launch(server_name="0.0.0.0",server_port=7860,share=False)4 unmodified lines56789101112131415161718192021222324252627282930313233343536374 unmodified lines424344454647481 unmodified line5051525354555613 unmodified lines70717273747576777826 unmodified lines1051061071081091101111121131141151161171181199 unmodified lines1291301311321331346 unmodified lines14114214314414514614749 unmodified lines1971981992002012022038 unmodified lines2122132142152162172185 unmodified lines2242252262272282292302312322332342352362372382392405 unmodified lines2462472482492502512522532541 unmodified line2562572582592602612622632642652662672682692702714 unmodified lines27627727827928028128228328413 unmodified lines2982993003013023034 unmodified lines3083093103113123133143153163173 unmodified lines3213223233243253263 unmodified lines3303313323333343354 unmodified lines34034134234334434534634734834935035149 unmodified lines4014024034044054062 unmodified lines4094104114124134144154161 unmodified line4184194204214224236 unmodified lines4304314324334344354366 unmodified lines4434444454464474484494504514 unmodified lines4564574584594604618 unmodified lines4704714724734744757 unmodified lines4834844854864874885 unmodified lines4944954964974984995 unmodified lines5055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395404 unmodified linesimport torchimport osimport timeimport sysimport loggingfrom typing import List, Dict, Generator, Tuple, Optionalfrom collections import defaultdictimport gc# Configure Torch for CPU optimizationtorch.set_num_threads(os.cpu_count() or 1)torch.backends.quantized.engine = 'qnnpack' if torch.backends.quantized.supported_engines else None# Set up logginglogging.basicConfig(level=logging.INFO,format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',handlers=[logging.FileHandler('council_debate.log'),logging.StreamHandler()])logger = logging.getLogger(__name__)# --- Best Free Models for Council ---MODELS = [("mistralai/Mistral-7B-Instruct-v0.2", "Mistral 7B Instruct"),("HuggingFaceH4/zephyr-7b-beta", "Zephyr 7B Beta"),("NousResearch/Hermes-2-Pro-Mistral-7B", "Hermes 2 Pro"),("cognitivecomputations/dolphin-2.6-mistral-7b", "Dolphin Mistral"),]# Define council member personas4 unmodified lines"traits": "analytical, skeptical, evidence-focused","style": "formal, precise, methodical","emoji": "🔬","preferred_models": ["Mistral 7B Instruct", "Zephyr 7B Beta"]},{"name": "Professor Marcus Chen",1 unmodified line"traits": "philosophical, visionary, empathetic","style": "eloquent, metaphorical, conceptual","emoji": "🧠","preferred_models": ["Hermes 2 Pro", "Dolphin Mistral"]},{"name": "Sarah Johnson",13 unmodified lines}]# Cache for modelsmodel_cache = {}model_loading_lock = threading.Lock()stop_signal = threading.Event()def get_device_preference():26 unmodified lines"torch_dtype": torch.float16 if device == "cuda" else torch.float32}if device == "cpu":model_kwargs.update({"low_cpu_mem_usage": True,"torch_dtype": torch.float32,})model = AutoModelForCausalLM.from_pretrained(model_id, **model_kwargs)if device != "cuda":model = model.to(device)pipe = pipeline(9 unmodified linesexcept Exception as e:logger.error(f"Failed to load model {model_id}: {str(e)}")if "out of memory" in str(e).lower() and device == "cuda":logger.info("Attempting to load with float16 to save memory")try:6 unmodified lineslogger.error(f"Still failed to load model: {str(e2)}")raisedef create_debate_prompt(user_prompt: str, persona: Dict, debate_style: str = "Balanced", previous_responses: Optional[List[Dict]] = None) -> str:"""Enhanced prompt engineering for better debates"""persona_desc = (f"Roleplay as {persona['name']}, {persona['description']}\n"49 unmodified linesFacilitator:"""def stream_model_response(pipe: pipeline, tokenizer: AutoTokenizer, prompt: str, speaker_name: str = None, temperature: float = 0.7, max_tokens: int = 512) -> Generator[str, None, None]:"""Robust streaming with better formatting and stop handling"""try:if stop_signal.is_set():8 unmodified linesstreamer=streamer,max_new_tokens=max_tokens,do_sample=True,temperature=min(max(temperature, 0.1), 1.0),top_p=0.95,repetition_penalty=1.1,eos_token_id=tokenizer.eos_token_id,5 unmodified linesbuffer = ""for new_text in streamer:if stop_signal.is_set():pipe.model.config.use_cache = Falsethread.join(timeout=1)breakbuffer += new_textif " " in new_text or "\n" in new_text:if speaker_name:yield f"**{speaker_name}:** {buffer.strip()}"else:yield buffer.strip()if buffer.strip():if speaker_name:yield f"**{speaker_name}:** {buffer.strip()}"5 unmodified linesexcept Exception as e:logger.error(f"Error in streaming: {str(e)}")yield "[Error in generation]" if not speaker_name else f"**{speaker_name}:** [Error in generation]"finally:gc.collect()torch.cuda.empty_cache() if torch.cuda.is_available() else Nonedef select_models_for_personas(personas: List[Dict], models: List[Tuple[str, str]]) -> List[Tuple[str, str]]:"""Match models to personas based on preferences"""1 unmodified linemodel_names = [m[1] for m in models]for persona in personas:for pref in persona.get("preferred_models", []):if pref in model_names:selected.append(models[model_names.index(pref)])breakelse:selected.append(random.choice(models))return selecteddef council_chat_stream(user_prompt: str, num_members: int = 3, debate_style: str = "Balanced", temperature: float = 0.7) -> Generator[str, None, None]:"""Enhanced debate generation with better state management"""stop_signal.clear()4 unmodified linesstart_time = time.time()try:selected_personas = random.sample(PERSONAS, min(num_members, len(PERSONAS)))selected_models = select_models_for_personas(selected_personas, MODELS)loaded_models = []for i, (model_id, model_name) in enumerate(selected_models):if stop_signal.is_set():13 unmodified linesyield "❌ Error: No models could be loaded. Please try again later."returnresponses = []formatted_responses = []persona_responses = []4 unmodified linesreturndisplay_name = f"{persona['emoji']} {persona['name']} ({model_name})"prompt = create_debate_prompt(user_prompt, persona, debate_style, persona_responses)response_text = ""for partial in stream_model_response(pipe, tokenizer, prompt, display_name, temperature):if stop_signal.is_set():breakyield partial3 unmodified linesyield "[Debate stopped during responses]"returnresponse_data = {"name": persona['name'],"model": model_name,3 unmodified linespersona_responses.append(response_data)formatted_responses.append(partial)if not stop_signal.is_set():yield "\n\n**✨ Council is now synthesizing the discussion...**\n"synthesis_model = random.choice(loaded_models)4 unmodified linessynthesis_model[1],synthesis_prompt,"✨ Facilitator's Synthesis",temperature*0.8):if stop_signal.is_set():breakyield partialelapsed_time = time.time() - start_timeif not stop_signal.is_set():transcript = (49 unmodified lines"""with gr.Blocks(theme=gr.themes.Soft(), css=custom_css) as demo:with gr.Row():gr.Markdown("""<div class="council-header">2 unmodified lines</div>""")with gr.Row():with gr.Column(scale=2):inp = gr.Textbox(label="Debate Topic",placeholder="Enter a topic or question for the council to debate...",1 unmodified linemax_lines=6)with gr.Group(elem_classes="debate-controls"):with gr.Row():btn = gr.Button("Start Debate", variant="primary")6 unmodified linesminimum=2,maximum=4,step=1,value=3)debate_style = gr.Dropdown(label="Debate Style",6 unmodified linesminimum=0.1,maximum=1.0,step=0.1,value=0.7)with gr.Accordion("Meet the Council Members", open=False):for persona in PERSONAS:with gr.Group(elem_classes="persona-card"):4 unmodified lines**Preferred Models:** {', '.join(persona.get('preferred_models', ['Any']))}""")with gr.Column(scale=3):out = gr.Markdown(label="Live Debate Transcript",8 unmodified lines- Debate memory and context tracking""")with gr.Accordion("Example Debate Topics", open=False):examples = gr.Examples(examples=[7 unmodified lineslabel="Click to try these examples")btn.click(fn=council_chat_stream,inputs=[inp, num_members, debate_style, temperature],5 unmodified linesqueue=False)gr.Markdown("""---**About This System:**5 unmodified linesreturn demoif __name__ == "__main__":# System checksdevice = get_device_preference()print(f"\n{'='*40}")print(f"Starting AI Council Debate on {device.upper()}")print(f"Python: {sys.version.split()[0]}")print(f"PyTorch: {torch.__version__}")print(f"Gradio: {gr.__version__}")print(f"{'='*40}\n")if device == "cpu":print("WARNING: Running on CPU - expect slower performance")print("Recommendations:")print("- Close other memory-intensive applications")print("- Reduce number of council members (2-3)")print("- Be patient with response times (30-90 sec per response)\n")try:demo = build_gradio_interface()demo.launch(server_name="0.0.0.0",server_port=7860,share=False,show_error=True)except Exception as e:print(f"\nERROR: {str(e)}")print("\nTroubleshooting steps:")print("1. Check internet connection (required for model download)")print("2. Verify Hugging Face token is set if using Llama models")print("3. Try reducing number of council members")print("4. Restart the application\n")raise
app.py+68-75