smarttextanalyser / src /streamlit_app.py
Gayukrish02's picture
Update src/streamlit_app.py
2b694d3 verified
import streamlit as st
import requests
import json
# ============================================================
# Smart Text Analyzer - Advanced Prompting Techniques Demo
# Deployed on Hugging Face Spaces
# ============================================================
st.set_page_config(
page_title="Smart Text Analyzer",
page_icon="🧠",
layout="wide"
)
st.title("🧠 Smart Text Analyzer")
st.caption("Demonstrates Advanced Prompting Techniques using Groq (Free AI API)")
# ---- API SETUP ----
GROQ_API_KEY = st.sidebar.text_input("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", type="password")
st.sidebar.markdown("Get free key at [console.groq.com](https://console.groq.com)")
st.sidebar.markdown("---")
# ---- ADVANCED PROMPT TEMPLATES ----
# 1. ZERO-SHOT PROMPT
def zero_shot_prompt(text):
return f"""Analyze the sentiment of the following text and classify it as Positive, Negative, or Neutral.
Text: {text}
Sentiment:"""
# 2. FEW-SHOT PROMPT
def few_shot_prompt(text):
return f"""Classify the sentiment of text. Here are some examples:
Text: "I absolutely love this product! It works perfectly."
Sentiment: Positive
Reason: Uses enthusiastic language and positive words.
Text: "This is the worst experience I have ever had."
Sentiment: Negative
Reason: Strong negative words expressing dissatisfaction.
Text: "The package arrived on time."
Sentiment: Neutral
Reason: Factual statement with no emotional language.
Now classify:
Text: "{text}"
Sentiment:
Reason:"""
# 3. CHAIN-OF-THOUGHT PROMPT
def chain_of_thought_prompt(text):
return f"""Analyze the following text step by step.
Text: "{text}"
Let's think through this carefully:
Step 1 - Identify the main topic of the text.
Step 2 - Identify any emotional words or phrases.
Step 3 - Determine the overall tone (positive/negative/neutral).
Step 4 - Summarize the key message in one sentence.
Step 5 - Give a final sentiment score from 1 (very negative) to 10 (very positive).
Analysis:"""
# 4. ROLE PROMPT
def role_prompt(text):
return f"""You are an expert linguist and psychologist with 20 years of experience
analyzing human communication and emotional patterns.
Analyze the following text from your expert perspective:
Text: "{text}"
Provide:
1. Emotional tone analysis
2. Communication style (formal/informal/aggressive/passive)
3. Hidden emotions or subtext
4. Psychological insight about the writer
5. Recommended response approach"""
# 5. TEMPLATE PROMPT
def template_prompt(text, task):
templates = {
"summarize": f"""
[TASK]: Summarize the following text
[INPUT]: {text}
[FORMAT]:
- One sentence summary
- 3 bullet point key takeaways
- Word count of original vs summary
[OUTPUT]:""",
"translate": f"""
[TASK]: Translate the following text to Tamil and Hindi
[INPUT]: {text}
[FORMAT]:
- Original: (original text)
- Tamil: (tamil translation)
- Hindi: (hindi translation)
- Note any cultural differences
[OUTPUT]:""",
"rewrite": f"""
[TASK]: Rewrite the following text to make it more professional
[INPUT]: {text}
[CONSTRAINTS]:
- Keep the same meaning
- Use formal language
- Maximum 3 sentences
- No slang or casual words
[OUTPUT]:"""
}
return templates.get(task, templates["summarize"])
# ---- CALL GROQ API ----
def call_groq(prompt, api_key):
if not api_key:
return "⚠️ Please enter your Groq API key in the sidebar."
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"
}
body = {
"model": "llama-3.3-70b-versatile",
"messages": [{"role": "user", "content": prompt}],
"max_tokens": 500
}
try:
response = requests.post(
"https://api.groq.com/openai/v1/chat/completions",
headers=headers,
json=body,
timeout=30
)
result = response.json()
if "choices" in result:
return result["choices"][0]["message"]["content"]
elif "error" in result:
return f"❌ Groq API Error: {result['error']['message']}"
else:
return f"❌ Unexpected response: {result}"
except Exception as e:
return f"❌ Error: {str(e)}"
# ---- UI ----
st.subheader("πŸ“ Enter your text")
user_text = st.text_area(
"Type or paste any text here:",
placeholder="e.g. I had an amazing day today! Everything went perfectly.",
height=120
)
st.markdown("---")
# ---- TABS FOR EACH TECHNIQUE ----
tab1, tab2, tab3, tab4, tab5 = st.tabs([
"⚑ Zero-Shot",
"πŸ“š Few-Shot",
"πŸ”— Chain-of-Thought",
"🎭 Role Prompting",
"πŸ“‹ Template Prompting"
])
with tab1:
st.subheader("⚑ Zero-Shot Prompting")
st.info("**What is it?** Give the AI a task with NO examples. Just ask directly.")
if user_text:
prompt = zero_shot_prompt(user_text)
with st.expander("πŸ“„ View Prompt"):
st.code(prompt)
if st.button("πŸš€ Run Zero-Shot", key="zs"):
with st.spinner("Analyzing..."):
result = call_groq(prompt, GROQ_API_KEY)
st.success(result)
else:
st.warning("Enter text above to analyze.")
with tab2:
st.subheader("πŸ“š Few-Shot Prompting")
st.info("**What is it?** Give the AI 2-3 examples before asking it to do the task.")
if user_text:
prompt = few_shot_prompt(user_text)
with st.expander("πŸ“„ View Prompt"):
st.code(prompt)
if st.button("πŸš€ Run Few-Shot", key="fs"):
with st.spinner("Analyzing..."):
result = call_groq(prompt, GROQ_API_KEY)
st.success(result)
else:
st.warning("Enter text above to analyze.")
with tab3:
st.subheader("πŸ”— Chain-of-Thought Prompting")
st.info("**What is it?** Ask the AI to think step by step before giving the answer.")
if user_text:
prompt = chain_of_thought_prompt(user_text)
with st.expander("πŸ“„ View Prompt"):
st.code(prompt)
if st.button("πŸš€ Run Chain-of-Thought", key="cot"):
with st.spinner("Thinking step by step..."):
result = call_groq(prompt, GROQ_API_KEY)
st.success(result)
else:
st.warning("Enter text above to analyze.")
with tab4:
st.subheader("🎭 Role Prompting")
st.info("**What is it?** Assign a specific role/persona to the AI before asking.")
if user_text:
prompt = role_prompt(user_text)
with st.expander("πŸ“„ View Prompt"):
st.code(prompt)
if st.button("πŸš€ Run Role Prompt", key="rp"):
with st.spinner("Expert analyzing..."):
result = call_groq(prompt, GROQ_API_KEY)
st.success(result)
else:
st.warning("Enter text above to analyze.")
with tab5:
st.subheader("πŸ“‹ Template Prompting")
st.info("**What is it?** Use structured templates with [TASK], [INPUT], [FORMAT] sections.")
task = st.selectbox("Choose task:", ["summarize", "translate", "rewrite"])
if user_text:
prompt = template_prompt(user_text, task)
with st.expander("πŸ“„ View Prompt"):
st.code(prompt)
if st.button("πŸš€ Run Template Prompt", key="tp"):
with st.spinner("Processing..."):
result = call_groq(prompt, GROQ_API_KEY)
st.success(result)
else:
st.warning("Enter text above to analyze.")
# ---- FOOTER ----
st.markdown("---")
st.markdown("""
### πŸ“– Prompting Techniques Used
| Technique | Description |
|---|---|
| ⚑ Zero-Shot | No examples, direct task |
| πŸ“š Few-Shot | 2-3 examples before task |
| πŸ”— Chain-of-Thought | Step-by-step reasoning |
| 🎭 Role Prompting | Assign AI a persona/role |
| πŸ“‹ Template Prompting | Structured [TASK][INPUT][OUTPUT] format |
""")