import gradio as gr import csv import re import tempfile import os import requests # Load system prompt from file with open("system_instructions.txt", "r", encoding="utf-8") as f: ECO_PROMPT = f.read() # Hugging Face configuration HF_API_KEY = os.environ.get("HF_API_KEY") HF_API_URL = "https://api-inference.huggingface.co/models/meta-llama/Meta-Llama-3-8B-Instruct" def format_llama3_prompt(system_prompt, question, answer): """Format prompt according to Llama3's chat template""" return f"""<|begin_of_text|><|start_header_id|>system<|end_header_id|> {system_prompt}<|eot_id|><|start_header_id|>user<|end_header_id|> Question: {question} Answer: {answer} Please provide a numerical score between 1-5 based on the guidelines.<|eot_id|><|start_header_id|>assistant<|end_header_id|> """ def score_qa(question, answer): """Get score from Llama3 via Hugging Face API""" try: prompt = format_llama3_prompt(ECO_PROMPT, question, answer) headers = { "Authorization": f"Bearer {HF_API_KEY}", "Content-Type": "application/json" } payload = { "inputs": prompt, "parameters": { "max_new_tokens": 5, "temperature": 0.1, "return_full_text": False } } response = requests.post(HF_API_URL, json=payload, headers=headers) response.raise_for_status() output = response.json()[0]['generated_text'] match = re.search(r"\d+", output) return int(match.group(0)) if match else 1 except Exception as e: print(f"API Error: {str(e)}") return 1 # Fallback score def judge_ecolinguistics_from_csv(csv_file): """Process CSV and generate results (unchanged from original)""" rows = [] with open(csv_file.name, "r", encoding="utf-8") as f: reader = csv.DictReader(f) rows = list(reader) results = [] total_score = 0 for r in rows: sc = score_qa(r.get("question", ""), r.get("answer", "")) total_score += sc results.append({ "question_number": r.get("question_number", ""), "score": sc }) with tempfile.NamedTemporaryFile(mode="w", delete=False, suffix=".csv", encoding="utf-8") as out_file: writer = csv.DictWriter(out_file, fieldnames=["question_number", "score"]) writer.writeheader() writer.writerows(results) writer.writerow({"question_number": "Total", "score": total_score}) out_path = out_file.name percentage = (total_score / (len(rows) * 5)) * 100 if rows else 0.0 percentage_display = f"""

🌱 Overall Score: {percentage:.1f}%

""" return out_path, percentage_display # Custom theme and styling (unchanged from original) custom_theme = gr.themes.Default().set( body_background_fill="#f8fff9", button_primary_background_fill="#38a169", button_primary_text_color="#ffffff", button_primary_background_fill_hover="#2e7d32", ) css = """ .gradio-container { max-width: 800px !important; } #upload-box { border: 2px dashed #38a169 !important; padding: 30px !important; border-radius: 15px !important; background: #f8fff9 !important; min-height: 150px !important; } #upload-box:hover { border-color: #2e7d32 !important; background: #f0fff4 !important; } #download-box { border: 2px solid #38a169 !important; padding: 20px !important; border-radius: 15px !important; background: #f8fff9 !important; } #logo { border-radius: 15px !important; border: 2px solid #38a169 !important; padding: 5px !important; background: white !important; } .dark #logo { background: #f0fff4 !important; } .footer { text-align: center; padding: 15px !important; background: #e8f5e9 !important; border-radius: 8px !important; margin-top: 25px !important; } """ with gr.Blocks(theme=custom_theme, css=css) as demo: # Header Section with gr.Row(): gr.Image("logo.png", show_label=False, width=200, height=200, elem_id="logo") gr.Markdown("""

🌿 EcoLingua

Sustainable Communication Assessment Platform

""") # Main Content with gr.Column(variant="panel"): gr.Markdown(""" ## 📤 Upload Your Q&A CSV

Required CSV format:

question_number,question,answer
1,"Question text...","Answer text..."
2,"Another question...","Another answer..."
""") with gr.Row(): csv_input = gr.File( label=" ", file_types=[".csv"], elem_id="upload-box" ) csv_output = gr.File( label="Download Results", interactive=False, elem_id="download-box" ) html_output = gr.HTML() csv_input.change( judge_ecolinguistics_from_csv, inputs=csv_input, outputs=[csv_output, html_output] ) # Footer gr.Markdown(""" """) if __name__ == "__main__": demo.launch()