ErikDaska commited on
Commit
be263ff
·
verified ·
1 Parent(s): 60732ea

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +71 -32
src/streamlit_app.py CHANGED
@@ -1,40 +1,79 @@
1
- import altair as alt
2
- import numpy as np
3
- import pandas as pd
4
  import streamlit as st
 
 
5
 
6
- """
7
- # Welcome to Streamlit!
 
 
 
 
8
 
9
- Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
10
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
11
- forums](https://discuss.streamlit.io).
 
 
 
12
 
13
- In the meantime, below is an example of what you can do with just a few lines of code:
14
- """
 
 
 
 
 
 
 
 
 
 
15
 
16
- num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
17
- num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
 
 
 
 
18
 
19
- indices = np.linspace(0, 1, num_points)
20
- theta = 2 * np.pi * num_turns * indices
21
- radius = indices
 
 
 
22
 
23
- x = radius * np.cos(theta)
24
- y = radius * np.sin(theta)
 
 
 
 
25
 
26
- df = pd.DataFrame({
27
- "x": x,
28
- "y": y,
29
- "idx": indices,
30
- "rand": np.random.randn(num_points),
31
- })
32
-
33
- st.altair_chart(alt.Chart(df, height=700, width=700)
34
- .mark_point(filled=True)
35
- .encode(
36
- x=alt.X("x", axis=None),
37
- y=alt.Y("y", axis=None),
38
- color=alt.Color("idx", legend=None, scale=alt.Scale()),
39
- size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
40
- ))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
+ from transformers import AutoTokenizer, AutoModelForCausalLM
3
+ import torch
4
 
5
+ # Set page configuration
6
+ st.set_page_config(
7
+ page_title="GPT-2 Code Generator",
8
+ page_icon="💻",
9
+ layout="wide"
10
+ )
11
 
12
+ # Title and description
13
+ st.title("💻 GPT-2 Code Generation Model Tester")
14
+ st.markdown(
15
+ f"Testing model: **[ErikDaska/lr_5e-05](https://huggingface.co/ErikDaska/lr_5e-05)**"
16
+ )
17
+ st.write("Enter a prompt or a partial function definition below to see how your model completes it.")
18
 
19
+ # Cache the model and tokenizer loading so it doesn't reload on every button press
20
+ @st.cache_resource
21
+ def load_model():
22
+ model_name = "ErikDaska/lr_5e-05"
23
+ with st.spinner("Loading model and tokenizer from Hugging Face... This might take a minute."):
24
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
25
+ model = AutoModelForCausalLM.from_pretrained(model_name)
26
+
27
+ # Check if GPU is available
28
+ device = "cuda" if torch.cuda.is_available() else "cpu"
29
+ model.to(device)
30
+ return tokenizer, model, device
31
 
32
+ try:
33
+ tokenizer, model, device = load_model()
34
+ st.success("Model loaded successfully!", icon="✅")
35
+ except Exception as e:
36
+ st.error(f"Error loading model: {e}")
37
+ st.stop()
38
 
39
+ # Sidebar for generation parameters
40
+ st.sidebar.header("Generation Settings")
41
+ max_length = st.sidebar.slider("Max Length", min_value=10, max_value=512, value=128, step=10)
42
+ temperature = st.sidebar.slider("Temperature (Creativity)", min_value=0.1, max_value=1.5, value=0.7, step=0.1)
43
+ top_p = st.sidebar.slider("Top-p (Nucleus Sampling)", min_value=0.0, max_value=1.0, value=0.9, step=0.05)
44
+ do_sample = st.sidebar.checkbox("Use Sampling", value=True)
45
 
46
+ # Main UI text input
47
+ prompt = st.text_area(
48
+ "Enter Code Prompt:",
49
+ value="def calculate_factorial(n):\n # This function calculates the factorial of a number",
50
+ height=150
51
+ )
52
 
53
+ # Generation trigger
54
+ if st.button("Generate Code", type="primary"):
55
+ if not prompt.strip():
56
+ st.warning("Please enter a prompt first.")
57
+ else:
58
+ with st.spinner("Generating code..."):
59
+ # Encode input
60
+ inputs = tokenizer(prompt, return_tensors="pt").to(device)
61
+
62
+ # Generate tokens
63
+ with torch.no_grad():
64
+ output_sequences = model.generate(
65
+ input_ids=inputs["input_ids"],
66
+ attention_mask=inputs.get("attention_mask"),
67
+ max_length=max_length + len(inputs["input_ids"][0]),
68
+ temperature=temperature,
69
+ top_p=top_p,
70
+ do_sample=do_sample,
71
+ pad_token_id=tokenizer.eos_token_id
72
+ )
73
+
74
+ # Decode output
75
+ generated_code = tokenizer.decode(output_sequences[0], skip_special_tokens=True)
76
+
77
+ # Display results
78
+ st.subheader("Generated Output:")
79
+ st.code(generated_code, language="python")