Spaces:
Sleeping
Sleeping
@panditu1 commited on
Commit Β·
85aa305
1
Parent(s): d51c46d
working model
Browse filesFiles changed (2)
- .gradio/certificate.pemAdded+31
- app.py+37-50
12345678910111213141516171819202122232425262728293031-----BEGIN CERTIFICATE-----MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAwTzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2VhcmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJuZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBYMTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygch77ct984kIxuPOZXoHj3dcKi/vVqbvYATyjb3miGbESTtrFj/RQSa78f0uoxmyF+0TM8ukj13Xnfs7j/EvEhmkvBioZxaUpmZmyPfjxwv60pIgbz5MDmgK7iS4+3mX6UA5/TR5d8mUgjU+g4rk8Kb4Mu0UlXjIB0ttov0DiNewNwIRt18jA8+o+u3dpjq+sWT8KOEUt+zwvo/7V3LvSye0rgTBIlDHCNAymg4VMk7BPZ7hm/ELNKjD+Jo2FR3qyHB5T0Y3HsLuJvW5iB4YlcNHlsdu87kGJ55tukmi8mxdAQ4Q7e2RCOFvu396j3x+UCB5iPNgiV5+I3lg02dZ77DnKxHZu8A/lJBdiB3QW0KtZB6awBdpUKD9jf1b0SHzUvKBds0pjBqAlkd25HN7rOrFleaJ1/ctaJxQZBKT5ZPt0m9STJEadao0xAH0ahmbWnOlFuhjuefXKnEgV4We0+UXgVCwOPjdAvBbI+e0ocS3MFEvzG6uBQE3xDk3SzynTnjh8BCNAw1FtxNrQHusEwMFxIt4I7mKZ9YIqioymCzLq9gwQbooMDQaHWBfEbwrbwqHyGO0aoSCqI3Haadr8faqU9GY/rOPNk3sgrDQoo//fb4hVC1CLQJ13hef4Y53CIrU7m2Ys6xt0nUW7/vGT1M0NPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBR5tFnme7bl5AFzgAiIyBpY9umbbjANBgkqhkiG9w0BAQsFAAOCAgEAVR9YqbyyqFDQDLHYGmkgJykIrGF1XIpu+ILlaS/V9lZLubhzEFnTIZd+50xx+7LSYK05qAvqFyFWhfFQDlnrzuBZ6brJFe+GnY+EgPbk6ZGQ3BebYhtF8GaV0nxvwuo77x/Py9auJ/GpsMiu/X1+mvoiBOv/2X/qkSsisRcOj/KKNFtY2PwByVS5uCbMiogziUwthDyC3+6WVwW6LLv3xLfHTjuCvjHIInNzktHCgKQ5ORAzI4JMPJ+GslWYHb4phowim57iaztXOoJwTdwJx4nLCgdNbOhdjsnvzqvHu7UrTkXWStAmzOVyyghqpZXjFaH3pO3JLF+l+/+sKAIuvtd7u+Nxe5AW0wdeRlN8NwdCjNPElpzVmbUq4JUagEiuTDkHzsxHpFKVK7q4+63SM1N95R1NbdWhscdCb+ZAJzVcoyi3B43njTOQ5yOf+1CceWxG1bQVs5ZufpsMljq4Ui0/1lvh+wjChP4kqKOJ2qxq4RgqsahDYVvTH9w7jXbyLeiNdd8XM2w9U/t7y0Ff/9yi0GE44Za4rF2LN9d11TPAmRGunUHBcnWEvgJBQl9nJEiU0Zsnvgc/ubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57demyPxgcYxn/eR44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc=-----END CERTIFICATE-----2 unmodified lines34567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980813 unmodified lines858687888990917 unmodified lines991001011021031041051061071081091101111121131141151161171181191202 unmodified linesfrom huggingface_hub import InferenceClientimport timeimport os# --- Configuration --- ## Model for the LOCAL tab (must be small enough to run on CPU)LOCAL_MODEL_NAME = "distilbert-base-uncased-finetuned-sst-2-english"# Model for the API tab (Changed to reliable GPT2)API_MODEL_NAME = "openai-community/gpt2"# --- Function for the LOCAL model (Tab 1) --- #print("π Loading the local sentiment model... This might take a minute.")try:# This pipeline will run locally on the Space's CPUlocal_sentiment_pipeline = pipeline("sentiment-analysis",model=LOCAL_MODEL_NAME)print("β Local model loaded successfully!")except Exception as e:print(f"β Failed to load local model: {e}")# If loading fails, create a dummy function that returns an error messagelocal_sentiment_pipeline = Nonedef analyze_sentiment(text):"""Runs the sentiment analysis model locally on the CPU."""if not text.strip():return "Please enter some text to analyze."if local_sentiment_pipeline is None:return "Error: Local model failed to load. Check the logs."try:start_time = time.time()# Get the prediction from the local modelresult = local_sentiment_pipeline(text)[0]end_time = time.time()response_time = round(end_time - start_time, 2)# Format the result nicelyreturn f"Label: {result['label']}\nConfidence: {round(result['score'] * 100, 2)}%\n(Processed locally in {response_time}s)"except Exception as e:return f"An error occurred during analysis: {str(e)}"# --- Function for the API model (Tab 2) --- ## Initialize the client for the API-based model.# We are not loading the model here, just setting up a client to call Hugging Face's API.api_client = InferenceClient(model=API_MODEL_NAME)def generate_positive_thought():"""Uses the Hugging Face Inference API to generate a positive message."""# Simple prompt for GPT2prompt = "Generate a short positive and motivational message:"try:start_time = time.time()# Call the hosted model via APIresponse = api_client.text_generation(prompt=prompt,max_new_tokens=50,do_sample=True,temperature=0.9,top_p=0.9)end_time = time.time()response_time = round(end_time - start_time, 2)# Clean up the response - sometimes GPT2 repeats the promptcleaned_response = response.replace(prompt, '').strip()return f"{cleaned_response}\n\n(Generated via GPT2 API in {response_time}s)"except Exception as e:return f"An error occurred calling the API: {str(e)}"# --- Gradio Interface --- #with gr.Blocks(title="Dual-Mode Mood App", theme=gr.themes.Soft()) as demo:3 unmodified lines""")with gr.Tab("π Analyze Sentiment (Local Model)"):gr.Markdown("This tab uses a small model (**DistilBERT - 66M parameters**) running **locally** on this server's CPU.")with gr.Row():with gr.Column():input_text = gr.Textbox(label="How are you feeling?", placeholder="Type a sentence here...", lines=3)7 unmodified linesanalyze_btn.click(fn=analyze_sentiment, inputs=input_text, outputs=output_sentiment)with gr.Tab("π‘ Generate Positive Thought (API Model)"):gr.Markdown("This tab uses a larger model (**GPT2 - 124M parameters**) called **remotely** via Hugging Face's Inference API.")with gr.Row():with gr.Column():gr.Markdown("Click the button to generate an uplifting message using a cloud-based model that's 2x larger than the local one.")gen_btn = gr.Button("Generate Positivity!", variant="primary")with gr.Column():output_text = gr.Textbox(label="Generated Message", interactive=False, lines=5)gen_btn.click(fn=generate_positive_thought, inputs=None, outputs=output_text)gr.Markdown("---")gr.Markdown("""**MLOps Case Study Demo** |**Local Model:** {LOCAL_MODEL_NAME} |**API Model:** {API_MODEL_NAME}""".format(LOCAL_MODEL_NAME=LOCAL_MODEL_NAME, API_MODEL_NAME=API_MODEL_NAME))# Launch the appif __name__ == "__main__":demo.launch(share=False)2 unmodified lines345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667683 unmodified lines727374757677787 unmodified lines86878889909192939495969798991001011021031041051061072 unmodified linesfrom huggingface_hub import InferenceClientimport timeimport osimport traceback# --- Token Check --- #HF_TOKEN = os.getenv("HF_TOKEN")print("π HF_TOKEN available?", "Yes β " if HF_TOKEN else "No β")if not HF_TOKEN:raise ValueError("HF_TOKEN not set. Please set it in your environment.")# --- Configuration --- #LOCAL_MODEL_NAME = "distilbert-base-uncased-finetuned-sst-2-english"API_MODEL_NAME = "HuggingFaceTB/SmolLM3-3B"# --- Local Model Setup --- #print("π Loading the local sentiment model... This might take a minute.")try:local_sentiment_pipeline = pipeline("sentiment-analysis", model=LOCAL_MODEL_NAME)print("β Local model loaded successfully!")except Exception as e:print(f"β Failed to load local model: {e}")local_sentiment_pipeline = Nonedef analyze_sentiment(text):if not text.strip():return "Please enter some text to analyze."if local_sentiment_pipeline is None:return "Error: Local model failed to load. Check the logs."try:start_time = time.time()result = local_sentiment_pipeline(text)[0]end_time = time.time()response_time = round(end_time - start_time, 2)return f"Label: {result['label']}\nConfidence: {round(result['score']*100, 2)}%\n(Processed locally in {response_time}s)"except Exception as e:traceback.print_exc()return f"β An error occurred during analysis:\n{str(e)}"# --- API Client Setup --- #api_client = InferenceClient(provider="hf-inference",api_key=HF_TOKEN)def generate_positive_thought():prompt = "Generate a short positive and motivational message."try:start_time = time.time()completion = api_client.chat.completions.create(model=API_MODEL_NAME,messages=[{"role": "system", "content": "You are a friendly assistant that writes positive motivational messages."},{"role": "user", "content": prompt}])end_time = time.time()response_time = round(end_time - start_time, 2)message = completion.choices[0].message["content"].strip()return f"{message}\n\n(Generated via {API_MODEL_NAME} in {response_time}s)"except Exception as e:traceback.print_exc()return f"β API Call Failed:\n{type(e).__name__}: {str(e)}"# --- Gradio Interface --- #with gr.Blocks(title="Dual-Mode Mood App", theme=gr.themes.Soft()) as demo:3 unmodified lines""")with gr.Tab("π Analyze Sentiment (Local Model)"):gr.Markdown("This tab uses a small model (**DistilBERT - 66M parameters**) running **locally** on CPU.")with gr.Row():with gr.Column():input_text = gr.Textbox(label="How are you feeling?", placeholder="Type a sentence here...", lines=3)7 unmodified linesanalyze_btn.click(fn=analyze_sentiment, inputs=input_text, outputs=output_sentiment)with gr.Tab("π‘ Generate Positive Thought (API Model)"):gr.Markdown(f"This tab uses **{API_MODEL_NAME}**, called **remotely** via Hugging Face's free Inference API.")with gr.Row():with gr.Column():gr.Markdown("Click the button to generate an uplifting message using a cloud-based model.")gen_btn = gr.Button("Generate Positivity!", variant="primary")with gr.Column():output_text = gr.Textbox(label="Generated Message", interactive=False, lines=5)gen_btn.click(fn=generate_positive_thought, inputs=None, outputs=output_text)gr.Markdown("---")gr.Markdown(f"""**MLOps Case Study Demo** |**Local Model:** {LOCAL_MODEL_NAME} |**API Model:** {API_MODEL_NAME}""")# Launch the appif __name__ == "__main__":demo.launch(share=True)
.gradio/certificate.pemAdded+31
app.py+37-50