Document / app.py
SlouchyBuffalo's picture
Create app.py
45b358c verified
import gradio as gr
import spaces
from huggingface_hub import InferenceClient
import json
# Initialize the Llama 3.3 model client with Cerebras provider
import os
try:
client = InferenceClient(
"meta-llama/Llama-3.3-70B-Instruct",
provider="cerebras",
token=os.getenv("HF_TOKEN"),
)
except Exception as e:
print(f"Error initializing Cerebras client: {e}")
# Fallback to default provider
client = InferenceClient("meta-llama/Llama-3.3-70B-Instruct")
# Turabian-based prompts for each stage
TURABIAN_PROMPTS = {
"stage_1": """Based on Turabian's method for developing research arguments, analyze this topic and create a commonsense argument with:
1. A clear main CLAIM (what you're arguing)
2. 2-3 supporting REASONS (why readers should accept your claim)
3. Types of EVIDENCE needed (what would support your reasons)
4. Present it as everyday conversation logic
Make it simple and foundational - this is just the starting point.
Topic: {input}
Format your response as:
CLAIM: [Your main argument]
REASON 1: [First supporting reason]
REASON 2: [Second supporting reason]
REASON 3: [Third reason if needed]
EVIDENCE TYPES NEEDED: [What kind of evidence you'd need]""",
"stage_2": """Help transition this commonsense argument into a research argument framework suitable for academic writing:
1. Identify what needs strengthening for a scholarly audience
2. Note areas requiring more formal evidence
3. Suggest how to frame this as a cooperative conversation with skeptical but receptive colleagues
4. Highlight the gap between commonsense and research-level argumentation
Current Commonsense Argument: {input}
Format your response with:
STRENGTHS TO BUILD ON: [What's already strong]
AREAS NEEDING DEVELOPMENT: [What needs more work]
ACADEMIC FRAMING: [How to present to scholars]
NEXT STEPS: [What to focus on in Stage 3]""",
"stage_3a": """Transform this working hypothesis into a specific, supportable academic claim:
1. Make it an assertion that clearly demands support
2. Ensure it's specific and focused (not too broad)
3. Check that you can realistically support it with available evidence
4. Make sure it goes beyond obvious or trivial statements
Working Hypothesis: {input}
Provide:
REFINED CLAIM: [Your specific, supportable claim]
WHY THIS WORKS: [Why this claim is effective]
POTENTIAL CHALLENGES: [What might be difficult to prove]
SCOPE NOTES: [What you're including/excluding]""",
"stage_3b": """Develop comprehensive reasons and evidence strategy for this claim:
1. Generate multiple strong supporting reasons
2. Identify primary source evidence needed
3. Assess evidence quality, quantity, and type requirements
4. Note potential challenges readers might raise about your evidence
Claim: {input}
Provide:
REASON 1: [First major reason]
- Evidence needed: [Specific evidence for this reason]
REASON 2: [Second major reason]
- Evidence needed: [Specific evidence for this reason]
REASON 3: [Third reason if applicable]
- Evidence needed: [Specific evidence for this reason]
PRIMARY SOURCES REQUIRED: [What original sources you need]
EVIDENCE QUALITY STANDARDS: [What makes strong evidence here]
POTENTIAL EVIDENCE CHALLENGES: [What readers might question]""",
"stage_3c": """Anticipate objections and questions from careful, skeptical readers:
1. List questions skeptical readers might ask
2. Identify internal soundness challenges (evidence quality, reason consistency)
3. Identify external soundness challenges (alternative views, exceptions)
4. Suggest strong responses to key objections
Argument: {input}
Provide:
READER QUESTIONS: [What will they ask?]
INTERNAL CHALLENGES: [Questions about evidence/logic]
EXTERNAL CHALLENGES: [Alternative interpretations/views]
KEY OBJECTION 1: [Most important objection]
- Your Response: [How you'll address it]
KEY OBJECTION 2: [Second most important]
- Your Response: [How you'll address it]
ACKNOWLEDGMENT STRATEGY: [How to show you've considered these]""",
"stage_3d": """Identify and articulate the warrants (underlying principles) connecting your reasons to your claim:
1. Explain the underlying principles/assumptions
2. Create clear When-Then statements
3. Check if readers will likely accept these warrants
4. Note any limiting conditions
Reason: {reason}
Claim: {claim}
Provide:
UNDERLYING PRINCIPLE: [The basic assumption connecting reason to claim]
WHEN-THEN STATEMENT: [When X, then Y format]
WARRANT ACCEPTABILITY: [Will readers accept this principle?]
POTENTIAL WARRANT CHALLENGES: [What if readers question the principle?]
LIMITING CONDITIONS: [When might this warrant not apply?]
MAKING IT EXPLICIT: [How to clearly state this in your argument]""",
"stage_4a": """Create a comprehensive storyboard/outline including all argument elements:
1. Research question
2. Working hypothesis/claim
3. Reasons and evidence
4. Acknowledgments and responses
5. Warrants
Argument Elements: {input}
Create:
RESEARCH QUESTION: [Your driving question]
MAIN CLAIM: [Your central argument]
STORYBOARD OUTLINE:
1. Introduction
- Hook/Context
- Research Question
- Claim Preview
2. Reason 1 + Evidence
- Warrant
- Potential Objection + Response
3. Reason 2 + Evidence
- Warrant
- Potential Objection + Response
4. [Additional reasons as needed]
5. Conclusion
- Claim Restatement
- Broader Implications
FLOW CHECK: [How sections connect logically]""",
"stage_4b": """Organize this argument structure to meet reader needs and expectations:
1. Suggest optimal ordering strategies
2. Recommend transitional structure
3. Consider what academic readers expect
4. Plan logical flow between sections
Argument Elements: {input}
Provide:
RECOMMENDED ORGANIZATION: [Best structure approach]
- Chronological / Topical / Simple-to-Complex / etc.
SECTION ORDER: [Specific sequence]
TRANSITIONAL STRATEGY: [How sections will connect]
READER EXPECTATIONS: [What readers need to see when]
LOGICAL FLOW NOTES: [Why this order works]
ALTERNATIVE APPROACHES: [Other viable structures]""",
"stage_4c": """Sketch working introduction and conclusion that effectively frame your argument:
1. Draft introduction that hooks readers and previews argument
2. Draft conclusion that reinforces argument and shows significance
3. Ensure they work together as a frame
Main Argument: {input}
Create:
INTRODUCTION DRAFT:
- Opening Hook: [Engaging start]
- Context/Background: [Essential background]
- Research Question: [Your driving question]
- Claim Statement: [Clear claim]
- Roadmap: [What's coming]
CONCLUSION DRAFT:
- Claim Restatement: [Reaffirm your argument]
- Key Evidence Summary: [Main support]
- Broader Implications: [Why it matters]
- Future Research: [What's next]
FRAME COHERENCE: [How intro and conclusion work together]""",
"stage_4d": """Identify and define key terms that will provide conceptual coherence throughout your paper:
1. Select terms representing core concepts
2. Ensure terms will run consistently through the paper
3. Check for conceptual clarity and consistency
Argument: {input}
Provide:
KEY TERMS TO DEFINE:
1. [Term 1]: [Definition and importance]
2. [Term 2]: [Definition and importance]
3. [Term 3]: [Definition and importance]
[Continue as needed]
CONCEPTUAL CONSISTENCY: [How terms relate to each other]
DEFINITION STRATEGY: [Where/how to define terms]
USAGE GUIDELINES: [How to use terms consistently]
POTENTIAL CONFUSION: [Terms readers might misunderstand]""",
"stage_5": """Provide comprehensive drafting guidance and best practices:
1. Effective writing habits
2. Source integration techniques
3. Evidence relevance demonstration
4. Using headings and key terms effectively
Writing Plan: {input}
Guidance:
WRITING HABITS:
- Daily writing schedule suggestions
- Productivity techniques
- Dealing with writer's block
SOURCE INTEGRATION:
- When to quote vs. paraphrase vs. summarize
- How to introduce sources effectively
- Attribution best practices
EVIDENCE CONNECTION:
- Making evidence relevance clear
- Linking evidence to reasons and claims
- Handling complex or detailed evidence
STRUCTURE MAINTENANCE:
- Using headings effectively
- Tracking key terms
- Maintaining argument thread
DRAFTING TIPS: [Practical writing advice]""",
"stage_6": """Create a comprehensive revision checklist based on Turabian's standards:
1. Check for argument blind spots
2. Review introduction, conclusion, and claim clarity
3. Assess overall body coherence
4. Provide paragraph-level revision guidance
Draft Description: {input}
Revision Checklist:
ARGUMENT STRENGTH:
β–‘ Blind spots check (unconsidered counterarguments?)
β–‘ Alternative interpretations addressed?
β–‘ Evidence gaps filled?
STRUCTURAL CLARITY:
β–‘ Introduction clearly frames argument?
β–‘ Conclusion reinforces without repeating?
β–‘ Claim visible and specific?
BODY COHERENCE:
β–‘ Key terms used consistently?
β–‘ Section breaks logical?
β–‘ Each section contributes to main argument?
β–‘ Transitions smooth and clear?
PARAGRAPH LEVEL:
β–‘ Each paragraph has clear purpose?
β–‘ Evidence clearly supports reasons?
β–‘ Warrants made explicit where needed?
REVISION PRIORITIES: [What to focus on first]"""
}
# Track user progress through stages
def get_stage_info(stage_key):
stage_info = {
"stage_1": {"name": "Commonsense Argument", "description": "Create your foundational argument"},
"stage_2": {"name": "Research Transition", "description": "Move from commonsense to academic"},
"stage_3a": {"name": "Claim Development", "description": "Refine your specific claim"},
"stage_3b": {"name": "Evidence Mapping", "description": "Plan reasons and evidence"},
"stage_3c": {"name": "Objection Analysis", "description": "Anticipate reader challenges"},
"stage_3d": {"name": "Warrant Identification", "description": "Connect reasons to claims"},
"stage_4a": {"name": "Storyboard Creation", "description": "Outline your argument"},
"stage_4b": {"name": "Organization Planning", "description": "Structure for readers"},
"stage_4c": {"name": "Introduction & Conclusion", "description": "Frame your argument"},
"stage_4d": {"name": "Key Terms", "description": "Define core concepts"},
"stage_5": {"name": "Drafting Guidance", "description": "Write your first draft"},
"stage_6": {"name": "Revision Checklist", "description": "Polish your argument"}
}
return stage_info.get(stage_key, {"name": "Unknown", "description": ""})
# Main processing function
@spaces.GPU
def process_stage(stage, input_text, reason_text="", claim_text=""):
"""Process input through selected Turabian stage"""
if not input_text.strip():
return "Please provide input text to analyze."
# Get the appropriate prompt - fixed the key mapping
prompt_template = TURABIAN_PROMPTS.get(stage)
if not prompt_template:
return f"Error: Stage {stage} not found."
# Handle special case for warrant stage that needs both reason and claim
if stage == "stage_3d":
if not reason_text.strip() or not claim_text.strip():
return "For warrant analysis, please provide both a reason and a claim."
prompt = prompt_template.format(reason=reason_text, claim=claim_text)
else:
prompt = prompt_template.format(input=input_text)
try:
# Generate response using Llama 3.3
messages = [{"role": "user", "content": prompt}]
response = client.chat_completion(
messages=messages,
max_tokens=1500,
temperature=0.7,
top_p=0.9
)
return response.choices[0].message.content
except Exception as e:
return f"Error processing request: {str(e)}"
# Custom CSS for better styling
custom_css = """
.stage-container {
border: 2px solid #4CAF50;
border-radius: 10px;
padding: 20px;
margin: 10px 0;
background-color: #f9f9f9;
}
.stage-title {
color: #2E7D32;
font-size: 1.2em;
font-weight: bold;
margin-bottom: 10px;
}
.progress-indicator {
background-color: #E3F2FD;
padding: 10px;
border-radius: 5px;
margin-bottom: 15px;
}
.output-box {
background-color: #FAFAFA;
border: 1px solid #E0E0E0;
border-radius: 5px;
padding: 15px;
font-family: monospace;
line-height: 1.6;
}
"""
# Main Gradio interface
with gr.Blocks(title="Turabian Research Argument Assistant", css=custom_css, theme=gr.themes.Soft()) as app:
gr.Markdown("""
# πŸ“š Turabian Research Argument Assistant
### *Based on "A Manual for Writers of Research Papers, Theses, and Dissertations" by Kate L. Turabian*
Develop your research argument step-by-step using Turabian's proven methodology. This tool guides you through all 6 stages from commonsense argument to final revision.
""")
with gr.Row():
with gr.Column(scale=2):
gr.Markdown("## 🎯 Select Your Stage")
stage = gr.Radio(
choices=[
("πŸ“ Stage 1: Commonsense Argument", "stage_1"),
("πŸ”„ Stage 2: Research Transition", "stage_2"),
("πŸ—οΈ Stage 3A: Claim Development", "stage_3a"),
("πŸ“Š Stage 3B: Evidence Mapping", "stage_3b"),
("❓ Stage 3C: Objection Analysis", "stage_3c"),
("πŸ”— Stage 3D: Warrant Identification", "stage_3d"),
("πŸ“‹ Stage 4A: Storyboard Creation", "stage_4a"),
("πŸ“ Stage 4B: Organization Planning", "stage_4b"),
("✍️ Stage 4C: Introduction & Conclusion", "stage_4c"),
("πŸ”‘ Stage 4D: Key Terms", "stage_4d"),
("πŸ“ Stage 5: Drafting Guidance", "stage_5"),
("πŸ” Stage 6: Revision Checklist", "stage_6")
],
value="stage_1",
label="Choose Your Current Stage"
)
# Dynamic stage information
stage_info = gr.Markdown("**Stage 1: Commonsense Argument** - Create your foundational argument")
# Input section
gr.Markdown("## πŸ“ Your Input")
input_text = gr.Textbox(
label="Main Input",
placeholder="Enter your topic, argument, or text for this stage...",
lines=8,
max_lines=15
)
# Special inputs for warrant stage
with gr.Row(visible=False) as warrant_inputs:
reason_text = gr.Textbox(
label="Reason",
placeholder="Enter the specific reason...",
lines=3
)
claim_text = gr.Textbox(
label="Claim",
placeholder="Enter the specific claim...",
lines=3
)
process_btn = gr.Button("πŸš€ Process Stage", variant="primary", size="lg")
with gr.Column(scale=3):
gr.Markdown("## πŸ“‹ Stage Output")
output = gr.Textbox(
label="Analysis Results",
lines=30,
max_lines=40,
show_copy_button=True,
elem_classes=["output-box"]
)
gr.Markdown("""
## πŸ“– How to Use This Tool
1. **Start with Stage 1** - Input your basic topic/idea
2. **Progress sequentially** - Each stage builds on the previous
3. **Copy outputs** - Use results from one stage as input for the next
4. **Take your time** - Turabian's method requires careful development
## πŸ’‘ Tips
- Keep outputs from each stage for reference
- Don't skip stages - each builds essential elements
- Stage 3D (Warrants) requires both a reason and claim
- Use stage 4+ outputs to guide your actual writing
""")
# Update stage information when selection changes
def update_stage_info(stage_key):
info = get_stage_info(stage_key)
stage_desc = f"**{info['name']}** - {info['description']}"
# Show/hide warrant special inputs
if stage_key == "stage_3d":
return stage_desc, gr.update(visible=True)
else:
return stage_desc, gr.update(visible=False)
stage.change(
fn=update_stage_info,
inputs=[stage],
outputs=[stage_info, warrant_inputs]
)
# Process button click
process_btn.click(
fn=process_stage,
inputs=[stage, input_text, reason_text, claim_text],
outputs=output,
show_progress=True
)
if __name__ == "__main__":
app.launch()