ak2603 commited on
Commit
f8d688e
·
1 Parent(s): 48c69e7

llama generation fixed and code refactored signly

Browse files
Files changed (3) hide show
  1. app.py +83 -85
  2. llama.py +49 -0
  3. mt5.py +100 -0
app.py CHANGED
@@ -1,100 +1,98 @@
1
- # app.py
2
  import streamlit as st
3
  from transformers import pipeline
 
4
 
5
  @st.cache_resource
6
- def load_model(model_name):
7
- if model_name == "mt5-small":
8
- return pipeline("summarization", model="ak2603/mt5-small-synthetic-data-plus-translated")
9
- # Add space for other models here
10
- elif model_name == "Llama 3.2":
11
- return pipeline("text-generation", model="Walid777/llama3-8b-emails-summarization")
12
- elif model_name == "Llama 7b Instruct":
13
- return None # Placeholder for future implementation
14
- else:
15
- raise ValueError("Model not supported")
 
 
16
 
17
- # Sample emails with reference summaries (for demonstration only)
18
- SAMPLES = {
19
- "Sample 1": (
20
- """
21
- Sehr geehrte Damen und Herren,
22
- Ich bitte um die Kündigung meines Vertrages, da ich umziehe.
23
- Vertragsnummer: 40887935006
24
- Zählernummer: 17760731625925
25
- Mit freundlichen Grüßen
26
- Falk Rosemann, Truppring 7, 02044 Wernigerode
27
- """,
28
- "Der Kunde bittet um die Kündigung seines Vertrages aufgrund eines Umzugs und gibt die Vertrags- und Zählernummer an."
29
- ),
30
- "Sample 2": (
31
- """
32
- Die versprochene Rabattaktion wurde in meiner letzten Rechnung nicht berücksichtigt.
33
- Mit freundlichen Grüßen
34
- Prof. Vinko Caspar B.Eng., Jolanda-Pruschke-Platz 835, 42943 Neustadtner Waldnaab
35
- """,
36
- "Der Kunde erwähnt, dass die versprochene Rabattaktion in der letzten Rechnung nicht berücksichtigt wurde."
37
- ),
38
- "Sample 3": (
39
- """
40
- Sehr geehrte Damen und Herren,
41
- Ich habe vor zwei Wochen eine Rechnung erhalten, die ich nicht nachvollziehen kann. Bitte erklären Sie die Details.
42
- Herzliche Grüße
43
- Kirstin Girschner-Meister, Oderwaldallee 510, 35412 Halberstadt
44
- """,
45
- "Der Kunde erwähnt, dass die versprochene Rabattaktion in der letzten Rechnung nicht berücksichtigt wurde und erwartet eine Überprüfung und Korrektur der Rechnung."
46
-
47
- )
48
- }
49
 
50
- # UI Layout
51
- st.title("🇩🇪 German Email Summarizer")
52
- st.markdown("Fine-tuned summarization for German emails")
53
 
54
- # Sidebar for model selection and sample emails
55
  with st.sidebar:
56
- st.header("⚙️ Settings")
57
- model_choice = st.selectbox("Choose Model", ["mt5-small", "Llama 3.2", "Llama 7b Instruct"], index=0)
58
- sample_choice = st.selectbox("Try Sample Email", ["Custom Input"] + list(SAMPLES.keys()))
 
 
 
 
 
 
 
 
59
 
60
- # Load the selected model
61
- summarizer = load_model(model_choice)
62
 
63
- # Main interface
64
- col1, col2 = st.columns(2)
65
  with col1:
66
- if sample_choice == "Custom Input":
67
- input_text = st.text_area("Input Email", height=300, placeholder="Paste your email here...")
68
- else:
69
- input_text = st.text_area("Input Email", value=SAMPLES[sample_choice][0], height=300)
 
 
 
70
 
71
  with col2:
72
- if st.button("Generate Summary"):
73
- if summarizer is None:
74
- st.error("Selected model is not implemented yet.")
 
75
  else:
76
- with st.spinner("Generating summary..."):
77
- try:
78
- # Generate summary
79
- summary_output = summarizer(
80
- input_text,
81
- max_length=150,
82
- do_sample=True,
83
- repetition_penalty=1.5
84
- )[0]
85
-
86
- # Dynamically select key based on pipeline task
87
- result_key = 'summary_text' if summarizer.task == 'summarization' else 'generated_text'
88
- result = summary_output[result_key]
89
-
90
- st.success("**Generated Summary:**")
91
- st.write(result)
92
-
93
- # Show sample comparison only if a sample is selected
94
- if sample_choice != "Custom Input" and sample_choice in SAMPLES:
95
- st.divider()
96
- st.markdown(f"**Sample Reference Summary ({sample_choice}):**")
97
- st.write(SAMPLES[sample_choice][1])
98
 
99
- except Exception as e:
100
- st.error(f"Error generating summary: {str(e)}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
  from transformers import pipeline
3
+ from llama import load_llama_model, generate_llama_summary, PROMPT_TEMPLATE
4
 
5
  @st.cache_resource
6
+ def load_all_models():
7
+ """Pre-load all models during app initialization"""
8
+ with st.spinner("Loading models... This may take a few minutes"):
9
+ models = {
10
+ "mt5-small": pipeline(
11
+ "summarization",
12
+ model="ak2603/mt5-small-synthetic-data-plus-translated"
13
+ ),
14
+ "Llama 3.2": load_llama_model(),
15
+ "Llama 7b Instruct": None # Placeholder
16
+ }
17
+ return models
18
 
19
+ # Initialize models when app loads
20
+ models = load_all_models()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
 
22
+ # Streamlit UI Configuration
23
+ st.set_page_config(page_title="Email Summarizer", layout="wide")
24
+ st.title("📧 Automated Email Summarization")
25
 
26
+ # Sidebar Controls
27
  with st.sidebar:
28
+ st.header("Configuration")
29
+ model_choice = st.selectbox(
30
+ "Select Model",
31
+ ["mt5-small", "Llama 3.2", "Llama 7b Instruct"],
32
+ index=0
33
+ )
34
+
35
+ st.markdown("---")
36
+ st.markdown("**Model Information:**")
37
+ st.info(f"Selected model: {model_choice}")
38
+ st.info(f"Total loaded models: {len([m for m in models.values() if m is not None])}")
39
 
40
+ # Main Content Area
41
+ col1, col2 = st.columns([2, 1])
42
 
 
 
43
  with col1:
44
+ st.subheader("Input Email")
45
+ email_input = st.text_area(
46
+ "Paste your email here:",
47
+ height=300,
48
+ key="input_text",
49
+ placeholder="Enter email content here..."
50
+ )
51
 
52
  with col2:
53
+ st.subheader("Summary Generation")
54
+ if st.button("Generate Summary", use_container_width=True):
55
+ if not email_input:
56
+ st.error("Please enter some email content first!")
57
  else:
58
+ try:
59
+ selected_model = models[model_choice]
60
+
61
+ if selected_model is None:
62
+ st.error("Selected model is not implemented yet")
63
+ else:
64
+ with st.spinner("Generating summary..."):
65
+ if model_choice == "mt5-small":
66
+ result = selected_model(
67
+ email_input,
68
+ max_length=150,
69
+ do_sample=True,
70
+ repetition_penalty=1.5
71
+ )[0]['summary_text']
72
+ elif model_choice == "Llama 3.2":
73
+ model_obj, tokenizer = selected_model
74
+ result = generate_llama_summary(
75
+ email_input,
76
+ model_obj,
77
+ tokenizer,
78
+ PROMPT_TEMPLATE
79
+ )
80
 
81
+ # Display results
82
+ st.success("**Generated Summary:**")
83
+ st.write(result)
84
+
85
+ # Add export options
86
+ st.download_button(
87
+ label="Download Summary",
88
+ data=result,
89
+ file_name="email_summary.txt",
90
+ mime="text/plain"
91
+ )
92
+
93
+ except Exception as e:
94
+ st.error(f"Error generating summary: {str(e)}")
95
+
96
+ # Footer
97
+ st.markdown("---")
98
+ st.markdown("_Automated email summarization system v1.0_")
llama.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import AutoTokenizer, AutoModelForCausalLM
2
+
3
+ PROMPT_TEMPLATE = """
4
+ You are an expert summarizer. Generate concise German summaries based on the email content,
5
+ following this structure: 'Der Kunde ... und erwartet ...'. The summaries need to be short. Here are some examples:
6
+ - Der Kunde übermittelt den Kontoauszug mit einer Abbuchung von 103,22€ und erwartet die Bestätigung der Abbuchung.
7
+ - Der Kunde möchte die Zahlungsart von Überweisung auf Lastschrift ändern und erwartet die Änderung der Zahlungsart durch die Unternehmensvertretung.
8
+ - Der Kunde übermittelt fehlende Angaben wie Übergabedatum und Zählerstand und erwartet die Verarbeitung der bereitgestellten Informationen.
9
+ - Der Kunde teilt die Beendigung des Gasbezugs aufgrund der Installation einer Wärmepumpe mit und erwartet den Abschluss des Gasvertrags und Bestätigung.
10
+ - Der Kunde sendet Daten und Papiere zur Entsperrung des Stromzählers.
11
+ - Der Kunde bittet um Korrektur der berechneten Abschlagszahlung für August 2023 und erwartet die Überprüfung und Anpassung der Zahlung.
12
+ - Der Kunde fragt nach der Abrechnung für einen beendeten Vertrag und erwartet die Erstellung und Zusendung der Abrechnung.
13
+ - Der Kunde bittet um Stellungnahme oder Korrektur, da der E.ON Plus Rabatt nicht berücksichtigt wurde und erwartet die Überprüfung und Korrektur der Rechnungen.
14
+ - Der Kunde sendet ein unterschriebenes Formular zurück und bittet um Kenntnisnahme und erwartet die Verarbeitung des Formulars.
15
+ - Der Kunde bittet um eine Ratenzahlung von 30 Euro monatlich für die letzte Stromrechnung und erwartet die Vereinbarung der Ratenzahlung.
16
+
17
+ ### Email:
18
+ {}
19
+
20
+ ### Summary:
21
+ """
22
+ def load_llama_model():
23
+ """Load Llama model and tokenizer with optimized settings"""
24
+ tokenizer = AutoTokenizer.from_pretrained("Walid777/llama3-8b-emails-summarization")
25
+ model = AutoModelForCausalLM.from_pretrained(
26
+ "Walid777/llama3-8b-emails-summarization",
27
+ device_map="auto",
28
+ torch_dtype="auto"
29
+ )
30
+ return model, tokenizer
31
+
32
+ def generate_llama_summary(email, model, tokenizer, prompt_template):
33
+ """Generate summary using structured prompt template"""
34
+ formatted_prompt = prompt_template.format(email)
35
+
36
+ inputs = tokenizer(
37
+ formatted_prompt,
38
+ return_tensors="pt"
39
+ ).to(model.device)
40
+
41
+ outputs = model.generate(
42
+ **inputs,
43
+ max_new_tokens=128,
44
+ temperature=0.7,
45
+ pad_token_id=tokenizer.eos_token_id
46
+ )
47
+
48
+ full_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
49
+ return full_text.split("### Summary:")[-1].strip()
mt5.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # app.py
2
+ import streamlit as st
3
+ from transformers import pipeline
4
+
5
+ @st.cache_resource
6
+ def load_model(model_name):
7
+ if model_name == "mt5-small":
8
+ return pipeline("summarization", model="ak2603/mt5-small-synthetic-data-plus-translated")
9
+ # Add space for other models here
10
+ elif model_name == "Llama 3.2":
11
+ return pipeline("text-generation", model="Walid777/llama3-8b-emails-summarization")
12
+ elif model_name == "Llama 7b Instruct":
13
+ return None # Placeholder for future implementation
14
+ else:
15
+ raise ValueError("Model not supported")
16
+
17
+ # Sample emails with reference summaries (for demonstration only)
18
+ SAMPLES = {
19
+ "Sample 1": (
20
+ """
21
+ Sehr geehrte Damen und Herren,
22
+ Ich bitte um die Kündigung meines Vertrages, da ich umziehe.
23
+ Vertragsnummer: 40887935006
24
+ Zählernummer: 17760731625925
25
+ Mit freundlichen Grüßen
26
+ Falk Rosemann, Truppring 7, 02044 Wernigerode
27
+ """,
28
+ "Der Kunde bittet um die Kündigung seines Vertrages aufgrund eines Umzugs und gibt die Vertrags- und Zählernummer an."
29
+ ),
30
+ "Sample 2": (
31
+ """
32
+ Die versprochene Rabattaktion wurde in meiner letzten Rechnung nicht berücksichtigt.
33
+ Mit freundlichen Grüßen
34
+ Prof. Vinko Caspar B.Eng., Jolanda-Pruschke-Platz 835, 42943 Neustadtner Waldnaab
35
+ """,
36
+ "Der Kunde erwähnt, dass die versprochene Rabattaktion in der letzten Rechnung nicht berücksichtigt wurde."
37
+ ),
38
+ "Sample 3": (
39
+ """
40
+ Sehr geehrte Damen und Herren,
41
+ Ich habe vor zwei Wochen eine Rechnung erhalten, die ich nicht nachvollziehen kann. Bitte erklären Sie die Details.
42
+ Herzliche Grüße
43
+ Kirstin Girschner-Meister, Oderwaldallee 510, 35412 Halberstadt
44
+ """,
45
+ "Der Kunde erwähnt, dass die versprochene Rabattaktion in der letzten Rechnung nicht berücksichtigt wurde und erwartet eine Überprüfung und Korrektur der Rechnung."
46
+
47
+ )
48
+ }
49
+
50
+ # UI Layout
51
+ st.title("🇩🇪 German Email Summarizer")
52
+ st.markdown("Fine-tuned summarization for German emails")
53
+
54
+ # Sidebar for model selection and sample emails
55
+ with st.sidebar:
56
+ st.header("⚙️ Settings")
57
+ model_choice = st.selectbox("Choose Model", ["mt5-small", "Llama 3.2", "Llama 7b Instruct"], index=0)
58
+ sample_choice = st.selectbox("Try Sample Email", ["Custom Input"] + list(SAMPLES.keys()))
59
+
60
+ # Load the selected model
61
+ summarizer = load_model(model_choice)
62
+
63
+ # Main interface
64
+ col1, col2 = st.columns(2)
65
+ with col1:
66
+ if sample_choice == "Custom Input":
67
+ input_text = st.text_area("Input Email", height=300, placeholder="Paste your email here...")
68
+ else:
69
+ input_text = st.text_area("Input Email", value=SAMPLES[sample_choice][0], height=300)
70
+
71
+ with col2:
72
+ if st.button("Generate Summary"):
73
+ if summarizer is None:
74
+ st.error("Selected model is not implemented yet.")
75
+ else:
76
+ with st.spinner("Generating summary..."):
77
+ try:
78
+ # Generate summary
79
+ summary_output = summarizer(
80
+ input_text,
81
+ max_length=150,
82
+ do_sample=True,
83
+ repetition_penalty=1.5
84
+ )[0]
85
+
86
+ # Dynamically select key based on pipeline task
87
+ result_key = 'summary_text' if summarizer.task == 'summarization' else 'generated_text'
88
+ result = summary_output[result_key]
89
+
90
+ st.success("**Generated Summary:**")
91
+ st.write(result)
92
+
93
+ # Show sample comparison only if a sample is selected
94
+ if sample_choice != "Custom Input" and sample_choice in SAMPLES:
95
+ st.divider()
96
+ st.markdown(f"**Sample Reference Summary ({sample_choice}):**")
97
+ st.write(SAMPLES[sample_choice][1])
98
+
99
+ except Exception as e:
100
+ st.error(f"Error generating summary: {str(e)}")