atharvsawant96 commited on
Commit
5a9082d
·
verified ·
1 Parent(s): 1951284

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +20 -73
app.py CHANGED
@@ -1,78 +1,25 @@
1
- import gradio as gr
2
- from transformers import AutoTokenizer, AutoModelForSequenceClassification
3
- import torch
4
 
5
- # Load model and tokenizer
6
- @gr.on_startup()
7
- def load_model():
8
- global tokenizer, model
9
- tokenizer = AutoTokenizer.from_pretrained("web3se/SmartBERT-v3")
10
- model = AutoModelForSequenceClassification.from_pretrained("web3se/SmartBERT-v3")
11
- model.eval()
12
- return model, tokenizer
13
 
14
- # Function to analyze smart contract
15
- def analyze_contract(contract_code):
16
- if not contract_code:
17
- return {"error": "No contract code provided"}
18
-
19
- try:
20
- # Tokenize input
21
- inputs = tokenizer(contract_code, return_tensors="pt", truncation=True, max_length=512)
22
-
23
- # Perform inference
24
- with torch.no_grad():
25
- outputs = model(**inputs)
26
-
27
- # Process outputs
28
- logits = outputs.logits
29
- probabilities = torch.nn.functional.softmax(logits, dim=-1)
30
-
31
- # Get predicted class and confidence
32
- predicted_class = torch.argmax(probabilities, dim=-1).item()
33
- confidence = probabilities[0, predicted_class].item()
34
-
35
- # Map class index to label
36
- labels = model.config.id2label
37
- predicted_label = labels[predicted_class]
38
-
39
- # Format all class probabilities for display
40
- all_probs = {labels[i]: f"{prob.item()*100:.2f}%" for i, prob in enumerate(probabilities[0])}
41
- sorted_probs = dict(sorted(all_probs.items(), key=lambda item: float(item[1].rstrip('%')), reverse=True))
42
-
43
- # Format the result as markdown for better display
44
- result_md = f"## Analysis Results\n\n"
45
- result_md += f"**Prediction:** {predicted_label}\n\n"
46
- result_md += f"**Confidence:** {confidence*100:.2f}%\n\n"
47
- result_md += "### All Class Probabilities:\n\n"
48
-
49
- for label, prob in sorted_probs.items():
50
- result_md += f"- {label}: {prob}\n"
51
-
52
- return result_md
53
-
54
- except Exception as e:
55
- return f"Error: {str(e)}"
56
 
57
- # Create Gradio interface
58
- title = "Smart Contract Analyzer (SmartBERT-v3)"
59
- description = """
60
- This app uses web3se/SmartBERT-v3 model to analyze smart contracts.
61
- Simply paste your smart contract code in the text area below and click "Analyze".
62
- """
63
 
64
- iface = gr.Interface(
65
- fn=analyze_contract,
66
- inputs=gr.Textbox(lines=15, placeholder="Paste your smart contract code here...", label="Smart Contract Code"),
67
- outputs=gr.Markdown(label="Analysis Results"),
68
- title=title,
69
- description=description,
70
- examples=[
71
- # You can add example smart contracts here
72
- ["pragma solidity ^0.8.0;\n\ncontract SimpleStorage {\n uint256 private value;\n \n function set(uint256 _value) public {\n value = _value;\n }\n \n function get() public view returns (uint256) {\n return value;\n }\n}"]
73
- ],
74
- allow_flagging="never"
75
- )
76
 
77
- # Launch the app
78
- iface.launch()
 
 
 
1
+ from fastapi import FastAPI
2
+ from pydantic import BaseModel
3
+ from transformers import RobertaTokenizer, RobertaForMaskedLM, pipeline
4
 
5
+ app = FastAPI()
 
 
 
 
 
 
 
6
 
7
+ # Load SmartBERT v3
8
+ model_name = "web3se/SmartBERT-v3"
9
+ tokenizer = RobertaTokenizer.from_pretrained(model_name)
10
+ model = RobertaForMaskedLM.from_pretrained(model_name)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
 
12
+ # Define API input format
13
+ class ContractRequest(BaseModel):
14
+ contract_code: str
 
 
 
15
 
16
+ @app.post("/analyze/")
17
+ async def analyze_contract(request: ContractRequest):
18
+ fill_mask = pipeline('fill-mask', model=model, tokenizer=tokenizer)
19
+ outputs = fill_mask(request.contract_code)
20
+ return {"predictions": outputs}
 
 
 
 
 
 
 
21
 
22
+ # Run the FastAPI server
23
+ if __name__ == "__main__":
24
+ import uvicorn
25
+ uvicorn.run(app, host="0.0.0.0", port=7860)