Spaces:
Sleeping
Sleeping
293droid commited on
Commit ·
e77b219
1
Parent(s): 2e4f4be
fix: clean app with Nebius provider for Qwen2.5-0.5B
Browse files12345678910111213141516171819202122232425262728298 unmodified lines383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182832 unmodified lines86878889909192939495969798991001011021031041051061071081091101111 unmodified line1131141151161171181191201211221231241251261271281291301311321331341351361371381391401415 unmodified lines1471481491501511521531541551561571 unmodified line15916016116216316416516 unmodified lines1821831841851861871881891901911921931941951961971981992002012022032042052062072082093 unmodified lines2132142152162172182199 unmodified lines22923023123223323423513 unmodified lines24925025125225325425510 unmodified lines2662672682692702712722731 unmodified line27527627727827928028128228328428528628719 unmodified lines30730830931031131231331431530 unmodified lines34634734834935035135215 unmodified lines36836937037137237337437537637737837938038117 unmodified lines399400401402"""Soap Lab — Main Gradio AppRuns locally with Ollama (llama3.2) for dev.On HF Space: swap model to HF Inference API (see bottom of file)."""import reimport gradio as grfrom chemistry import (calculate_lye, score_recipe, find_substitutes,cure_timeline, profile_summary, list_oils, OILS)import osfrom huggingface_hub import InferenceClientclient = InferenceClient("microsoft/Phi-3.5-mini-instruct",token=os.environ.get("HF_TOKEN"))# ---------------------------------------------------------------------------# Config — change MODEL to "Qwen/Qwen2.5-7B-Instruct" on HF Space# ---------------------------------------------------------------------------MODEL = "smollm2:1.7b" # local dev — Tiny Titan eligibleUSE_OLLAMA = True # set False on HF Space, use HF Inference API insteadSYSTEM_PROMPT = """You are Soap Lab, a friendly expert assistant for home soap makers.You help hobbyists understand soap chemistry in plain English — no jargon without explanation.8 unmodified lines# ---------------------------------------------------------------------------# Parser — extract oils and weights from plain English# ---------------------------------------------------------------------------def parse_recipe(text: str) -> dict[str, float]:"""Extract oil names and weights from plain English.Handles: "300g coconut oil", "150 grams olive oil", "50% castor"Returns {oil_key: weight_grams} or empty dict if nothing found."""text_lower = text.lower()recipe = {}# Try to find weight + oil name patterns# Pattern: number (g/grams/gram/%) then oil namepattern = r'(\d+(?:\.\d+)?)\s*(?:g|grams?|gram|%)?\s+([a-z\s,()]+?)(?=\d|$|,|and\b|with\b|\n)'matches = re.findall(pattern, text_lower)for weight_str, oil_fragment in matches:weight = float(weight_str)oil_fragment = oil_fragment.strip().rstrip(',').strip()# Try to match to known oilmatched_key = Nonefor key in OILS:# Check if oil key words appear in fragmentkey_words = key.replace('(', '').replace(')', '').split()if any(word in oil_fragment for word in key_words if len(word) > 3):matched_key = keybreakif matched_key and weight > 0:recipe[matched_key] = recipe.get(matched_key, 0) + weightreturn recipedef detect_mode(text: str) -> str:"""Detect which mode the user is requesting."""text_lower = text.lower()if any(w in text_lower for w in ["only have", "i have", "in my cupboard", "at home", "pantry"]):return "pantry"if any(w in text_lower for w in ["failed", "wrong", "greasy", "soft", "sticky", "didn't work", "bad batch"]):2 unmodified linesreturn "substitute"if any(w in text_lower for w in ["sensitive", "dry skin", "oily skin", "eczema", "baby", "hard bar", "gentle", "want a"]):return "goal"return "recipe" # default: treat as recipe input# ---------------------------------------------------------------------------# AI call# ---------------------------------------------------------------------------def ask_model(prompt: str, context: str) -> str:full_prompt = f"{context}\n\nUser asked: {prompt}"try:response = client.chat_completion(messages=[{"role": "system", "content": SYSTEM_PROMPT},{"role": "user", "content": full_prompt}],max_tokens=500,)return response.choices[0].message.contentexcept Exception as e:return f"Model error: {str(e)}"# ---------------------------------------------------------------------------1 unmodified line# ---------------------------------------------------------------------------def handle_recipe(user_input: str, vegan_only: bool) -> tuple[str, str, str]:"""Standard recipe mode: parse oils, calculate lye, score, explain.Returns: (lye_result, quality_scores, ai_explanation)"""recipe = parse_recipe(user_input)if not recipe:return ("⚠️ Couldn't find any oils and weights in your input.","","Try something like: '300g coconut oil, 200g olive oil, 100g shea butter'")# Run chemistrylye = calculate_lye(recipe, superfat=5, water_ratio=0.38)if "error" in lye:return f"⚠️ {lye['error']}", "", ""scores = score_recipe(recipe)profile = profile_summary(recipe)cure = cure_timeline(recipe)# Format lye resultlye_text = f"""**Lye Calculation** *(from verified SAP values — not AI-generated)*🧪 Total oil weight: {lye['total_oil_weight_g']}g5 unmodified lines"""for oil in lye["oil_details"]:lye_text += f"• {oil['name']}: {oil['weight_g']}g → {oil['naoh_needed_g']}g NaOH (SAP: {oil['naoh_sap']})\n"if not profile["is_vegan"]:lye_text += f"\n⚠️ Non-vegan oils: {', '.join(profile['non_vegan_oils'])}"# Format quality scoresstatus_emoji = {"ok": "✅", "low": "⬇️", "high": "⬆️"}scores_text = "**Soap Quality Scores** *(target ranges shown)*\n\n"for key, s in scores.items():1 unmodified linescores_text += f"{emoji} {s['label']}: **{s['value']}** (target: {s['target_low']}–{s['target_high']})\n"scores_text += f"\n⏱️ Recommended cure time: **{cure['recommended_cure_weeks']} weeks**"# Build AI contextcontext = f"""The user has a soap recipe with these results:Oils: {', '.join(f"{v}g {k}" for k, v in recipe.items())}16 unmodified linesdef handle_substitute(user_input: str, vegan_only: bool) -> tuple[str, str, str]:"""Find substitutes for an oil the user can't find."""text_lower = user_input.lower()# Replace the target_key matching loop with this:target_key = None# Try exact match firstfor key in OILS:if key in text_lower:target_key = keybreak# Fall back to partial match if nothing foundif not target_key:for key in OILS:key_words = [w for w in key.split() if len(w) > 3 and w not in ["oil", "butter", "fat"]]if any(w in text_lower for w in key_words):target_key = keybreaksubs = find_substitutes(target_key, n=3, vegan_only=vegan_only)oil = OILS[target_key]subs_text = f"**Substitutes for {oil.name}**\n*(ranked by fatty acid similarity)*\n\n"for i, sub in enumerate(subs, 1):vegan_flag = "" if sub["vegan"] else " 🐄"3 unmodified lines{oil.name} fatty acid profile:- Lauric: {oil.lauric}%, Myristic: {oil.myristic}%- Palmitic: {oil.palmitic}%, Stearic: {oil.stearic}%- Oleic: {oil.oleic}%, Linoleic: {oil.linoleic}%- Ricinoleic: {oil.ricinoleic}%9 unmodified linesdef handle_goal(user_input: str, vegan_only: bool) -> tuple[str, str, str]:"""Suggest a recipe based on the user's skin goal."""context = f"""A home soap maker has described what they want: "{user_input}"Based on their goal, suggest a simple beginner recipe using common oils.13 unmodified linesdef handle_diagnose(user_input: str, vegan_only: bool) -> tuple[str, str, str]:"""Diagnose a failed batch."""context = f"""A home soap maker had a batch problem: "{user_input}"Diagnose the most likely causes based on their description.10 unmodified linesdef handle_pantry(user_input: str, vegan_only: bool) -> tuple[str, str, str]:"""Build a recipe from whatever oils the user has."""# Extract oils mentionedrecipe_oils = []for key in OILS:if vegan_only and not OILS[key].vegan:1 unmodified linekey_words = [w for w in key.split() if len(w) > 3 and w not in ["oil", "butter", "fat"]]if any(w in user_input.lower() for w in key_words):recipe_oils.append(OILS[key].name)if not recipe_oils:return ("⚠️ Couldn't spot any oils in your message.","","Try: 'I have coconut oil, olive oil and shea butter — what can I make?'")context = f"""A soap maker only has these oils available: {', '.join(recipe_oils)}{"They want a vegan recipe." if vegan_only else ""}19 unmodified linesdef run_soap_lab(user_input: str, vegan_only: bool) -> tuple[str, str, str]:if not user_input.strip():return "", "", "Type your question or recipe above and hit Submit!"mode = detect_mode(user_input)if mode == "substitute":return handle_substitute(user_input, vegan_only)elif mode == "goal":30 unmodified lines"""with gr.Blocks(css=CSS, title="🧼 Soap Lab") as demo:gr.HTML("<h1 id='title'>🧼 Soap Lab</h1>")gr.HTML("<p id='subtitle'>Plain English soap chemistry — recipes, substitutions, troubleshooting</p>")15 unmodified linesgr.Examples(examples=EXAMPLES, inputs=[user_input, vegan_toggle], label="Try an example")with gr.Row(visible=True):with gr.Column():lye_output = gr.Markdown(label="", elem_classes=["lye-box"])with gr.Column():scores_output = gr.Markdown(label="", elem_classes=["scores-box"])explanation_output = gr.Markdown(label="",elem_classes=["explain-box"],value="*Your explanation will appear here...*")17 unmodified lines)if __name__ == "__main__":demo.launch()123456789101112131415161718192021222324252627288 unmodified lines37383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485862 unmodified lines899091929394951 unmodified line9798991001011021031041051061071081091101111121131141151165 unmodified lines1221231241251261271281291301 unmodified line13213313413513613716 unmodified lines1541551561571581591601611621631641651661671681691701711721731741751763 unmodified lines1801811821831841851869 unmodified lines19619719819920020113 unmodified lines21521621721821922010 unmodified lines2312322332342352361 unmodified line23823924024124224324424519 unmodified lines26526626726826927027130 unmodified lines30230330430530630715 unmodified lines32332432532632732832933033133233333433517 unmodified lines353354355356"""Soap Lab — Main Gradio AppUses HF Inference API with Qwen2.5-0.5B — free, no billing required.Tiny Titan eligible (0.5B parameters)."""import osimport reimport gradio as grfrom huggingface_hub import InferenceClientfrom chemistry import (calculate_lye, score_recipe, find_substitutes,cure_timeline, profile_summary, OILS)# ---------------------------------------------------------------------------# Model config — Qwen2.5-0.5B is free on HF Inference API# ---------------------------------------------------------------------------client = InferenceClient(provider="nebius",api_key=os.environ.get("HF_TOKEN"),)MODEL = "Qwen/Qwen2.5-0.5B-Instruct"SYSTEM_PROMPT = """You are Soap Lab, a friendly expert assistant for home soap makers.You help hobbyists understand soap chemistry in plain English — no jargon without explanation.8 unmodified lines# ---------------------------------------------------------------------------# AI call# ---------------------------------------------------------------------------def ask_model(prompt: str, context: str) -> str:full_prompt = f"{context}\n\nUser asked: {prompt}"try:response = client.chat_completion(model=MODEL,messages=[{"role": "system", "content": SYSTEM_PROMPT},{"role": "user", "content": full_prompt}],max_tokens=500,)return response.choices[0].message.contentexcept Exception as e:return f"Model error: {str(e)}"# ---------------------------------------------------------------------------# Parser# ---------------------------------------------------------------------------def parse_recipe(text: str) -> dict[str, float]:text_lower = text.lower()recipe = {}pattern = r'(\d+(?:\.\d+)?)\s*(?:g|grams?|gram|%)?\s+([a-z\s,()]+?)(?=\d|$|,|and\b|with\b|\n)'matches = re.findall(pattern, text_lower)for weight_str, oil_fragment in matches:weight = float(weight_str)oil_fragment = oil_fragment.strip().rstrip(',').strip()matched_key = Nonefor key in OILS:key_words = key.replace('(', '').replace(')', '').split()if any(word in oil_fragment for word in key_words if len(word) > 3):matched_key = keybreakif matched_key and weight > 0:recipe[matched_key] = recipe.get(matched_key, 0) + weightreturn recipedef detect_mode(text: str) -> str:text_lower = text.lower()if any(w in text_lower for w in ["only have", "i have", "in my cupboard", "at home", "pantry"]):return "pantry"if any(w in text_lower for w in ["failed", "wrong", "greasy", "soft", "sticky", "didn't work", "bad batch"]):2 unmodified linesreturn "substitute"if any(w in text_lower for w in ["sensitive", "dry skin", "oily skin", "eczema", "baby", "hard bar", "gentle", "want a"]):return "goal"return "recipe"# ---------------------------------------------------------------------------1 unmodified line# ---------------------------------------------------------------------------def handle_recipe(user_input: str, vegan_only: bool) -> tuple[str, str, str]:recipe = parse_recipe(user_input)if not recipe:return ("⚠️ Couldn't find any oils and weights in your input.","","Try something like: '300g coconut oil, 200g olive oil, 100g shea butter'")lye = calculate_lye(recipe, superfat=5, water_ratio=0.38)if "error" in lye:return f"⚠️ {lye['error']}", "", ""scores = score_recipe(recipe)profile = profile_summary(recipe)cure = cure_timeline(recipe)lye_text = f"""**Lye Calculation** *(from verified SAP values — not AI-generated)*🧪 Total oil weight: {lye['total_oil_weight_g']}g5 unmodified lines"""for oil in lye["oil_details"]:lye_text += f"• {oil['name']}: {oil['weight_g']}g → {oil['naoh_needed_g']}g NaOH (SAP: {oil['naoh_sap']})\n"if not profile["is_vegan"]:lye_text += f"\n⚠️ Non-vegan oils: {', '.join(profile['non_vegan_oils'])}"status_emoji = {"ok": "✅", "low": "⬇️", "high": "⬆️"}scores_text = "**Soap Quality Scores** *(target ranges shown)*\n\n"for key, s in scores.items():1 unmodified linescores_text += f"{emoji} {s['label']}: **{s['value']}** (target: {s['target_low']}–{s['target_high']})\n"scores_text += f"\n⏱️ Recommended cure time: **{cure['recommended_cure_weeks']} weeks**"context = f"""The user has a soap recipe with these results:Oils: {', '.join(f"{v}g {k}" for k, v in recipe.items())}16 unmodified linesdef handle_substitute(user_input: str, vegan_only: bool) -> tuple[str, str, str]:text_lower = user_input.lower()target_key = Nonefor key in OILS:if key in text_lower:target_key = keybreakif not target_key:for key in OILS:key_words = [w for w in key.split() if len(w) > 3 and w not in ["oil", "butter", "fat"]]if any(w in text_lower for w in key_words):target_key = keybreakif not target_key:return "⚠️ Couldn't identify which oil you want to substitute.", "", "Try: 'I can't find palm oil, what can I use instead?'"subs = find_substitutes(target_key, n=3, vegan_only=vegan_only)oil = OILS[target_key]subs_text = f"**Substitutes for {oil.name}**\n*(ranked by fatty acid similarity)*\n\n"for i, sub in enumerate(subs, 1):vegan_flag = "" if sub["vegan"] else " 🐄"3 unmodified lines{oil.name} fatty acid profile:- Lauric: {oil.lauric}%, Myristic: {oil.myristic}%- Palmitic: {oil.palmitic}%, Stearic: {oil.stearic}%- Oleic: {oil.oleic}%, Linoleic: {oil.linoleic}%- Ricinoleic: {oil.ricinoleic}%9 unmodified linesdef handle_goal(user_input: str, vegan_only: bool) -> tuple[str, str, str]:context = f"""A home soap maker has described what they want: "{user_input}"Based on their goal, suggest a simple beginner recipe using common oils.13 unmodified linesdef handle_diagnose(user_input: str, vegan_only: bool) -> tuple[str, str, str]:context = f"""A home soap maker had a batch problem: "{user_input}"Diagnose the most likely causes based on their description.10 unmodified linesdef handle_pantry(user_input: str, vegan_only: bool) -> tuple[str, str, str]:recipe_oils = []for key in OILS:if vegan_only and not OILS[key].vegan:1 unmodified linekey_words = [w for w in key.split() if len(w) > 3 and w not in ["oil", "butter", "fat"]]if any(w in user_input.lower() for w in key_words):recipe_oils.append(OILS[key].name)if not recipe_oils:return "⚠️ Couldn't spot any oils in your message.", "", "Try: 'I have coconut oil, olive oil and shea butter — what can I make?'"context = f"""A soap maker only has these oils available: {', '.join(recipe_oils)}{"They want a vegan recipe." if vegan_only else ""}19 unmodified linesdef run_soap_lab(user_input: str, vegan_only: bool) -> tuple[str, str, str]:if not user_input.strip():return "", "", "Type your question or recipe above and hit Submit!"mode = detect_mode(user_input)if mode == "substitute":return handle_substitute(user_input, vegan_only)elif mode == "goal":30 unmodified lines"""with gr.Blocks(css=CSS, title="🧼 Soap Lab") as demo:gr.HTML("<h1 id='title'>🧼 Soap Lab</h1>")gr.HTML("<p id='subtitle'>Plain English soap chemistry — recipes, substitutions, troubleshooting</p>")15 unmodified linesgr.Examples(examples=EXAMPLES, inputs=[user_input, vegan_toggle], label="Try an example")with gr.Row():with gr.Column():lye_output = gr.Markdown(elem_classes=["lye-box"])with gr.Column():scores_output = gr.Markdown(elem_classes=["scores-box"])explanation_output = gr.Markdown(elem_classes=["explain-box"],value="*Your explanation will appear here...*")17 unmodified lines)if __name__ == "__main__":demo.launch()
app.py+42-88